title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
Python: Check if a numpy array contains an object with specific attribute
39,782,113
<p>I want to check if there is any object with a specific attribute in my numpy array:</p> <pre><code>class Test: def __init__(self, name): self.name = name l = numpy.empty( (2,2), dtype=object) l[0][0] = Test("A") l[0][1] = Test("B") l[1][0] = Test("C") l[1][1] = Test("D") </code></pre> <p>I know that following line of code working for a list, but what is the alternative process for a numpy array?</p> <pre><code>print numpy.any(l[:,0].name == "A") </code></pre>
1
2016-09-30T00:56:32Z
39,782,767
<p>There are a number SO questions about object dtype arrays, and even some about getting or testing the attributes of the elements of such arrays. The general point is that such an array behaves much like a list. For the most part you have to iterate over the array as though it were a list. Most of the cool things that you can do with numeric arrays like <code>add</code>, <code>multiply</code> etc do not apply. Or your objects have to implement specific methods for the actions to propagate down to the objects.</p> <pre><code>In [15]: class Test: ...: def __init__(self,name): ...: self.name=name ...: def __repr__(self): # added for nice display ...: return 'Test:%s'%self.name ...: In [16]: A = np.empty((2,2),dtype=object) </code></pre> <p>I can assign all the values at once using <code>flat[:]</code> and list:</p> <pre><code>In [17]: A.flat[:]=[Test('A'),Test('B'),Test('C'),Test('D')] In [18]: A # try this display without the `repr` Out[18]: array([[Test:A, Test:B], [Test:C, Test:D]], dtype=object) </code></pre> <p>this returns False because I did not define a <code>cmp</code> for the class; that is <code>Test('A')==Test('A')</code> is also False.</p> <pre><code>In [19]: Test('A') in A Out[19]: False In [20]: A[0,1].name Out[20]: 'B' </code></pre> <p>This is true because it is an identity test </p> <pre><code>In [21]: A[0,1] in A Out[21]: True </code></pre> <p>Since <code>A</code> is 2d, a simple list comprehension on it does not work, at least not for testing attributes. <code>a</code> in this case is a row of <code>A</code>, a 1d object array:</p> <pre><code>In [23]: [a.name for a in A] ... AttributeError: 'numpy.ndarray' object has no attribute 'name' </code></pre> <p>To get the names I have to iterated on <code>A.flat</code>; I can apply the <code>in</code> test to the resulting list:</p> <pre><code>In [24]: [a.name for a in A.flat] Out[24]: ['A', 'B', 'C', 'D'] In [25]: 'B' in [a.name for a in A.flat] Out[25]: True </code></pre> <p><code>np.vectorize</code> is a way of writing functions that operate on arrays of various shapes. It uses <code>np.frompyfunc</code>, which in this case works just as well, if not better.</p> <pre><code>In [27]: foo = np.frompyfunc(lambda a: a.name, 1,1) In [28]: foo(A) Out[28]: array([['A', 'B'], ['C', 'D']], dtype=object) In [29]: 'C' in foo(A) Out[29]: True </code></pre> <p>Or I could define a version that does the <code>name</code> equality test. Notice this takes 2 inputs</p> <pre><code>In [30]: bar = np.frompyfunc(lambda a,b: b == a.name, 2, 1) In [32]: bar(A,'C') Out[32]: array([[False, False], [True, False]], dtype=object) </code></pre> <p>I can even test 2 arrays against each other with broadcasting:</p> <pre><code>In [37]: bar(A,np.array(['A','D'])[:,None,None]) Out[37]: array([[[True, False], [False, False]], [[False, False], [False, True]]], dtype=object) </code></pre> <p><code>frompyfunc</code> iterates as the <code>[a for a in A.flat]</code> does, but is somewhat faster, and throws all the power of numpy broadcasting at the task.</p>
1
2016-09-30T02:32:08Z
[ "python", "python-2.7", "numpy" ]
Named optional argument and multiple argument order
39,782,137
<p>I have a function wrapper like this. </p> <pre><code>def funcWrapper(fn_ng, order=None, *args ): def clsr(X): if order is not None: X = calc_poli_dsX(X, order) return fn_ng(X, *args); return clsr; </code></pre> <p>However, if I use this function as below:</p> <pre><code>mGrdnt = funcWrapper( gd.squared_error, dsX1, dy, order=None) mGrdnt = funcWrapper( gd.squared_error, dsX1, dy) </code></pre> <p>I have error of</p> <pre><code> TypeError: funcWrapper() got multiple values for keyword argument 'order' </code></pre> <p>My guess was that, if I do not specify 'order', funcWrapper will pass 'dsX1' and 'dy' are passed as *arg, but it turned out they are not. No matter I specify an optional argument, it seems that 'dsX1' and 'dy' all go into the 'order' named optional argument.</p> <p>How can I make a function wrapper that can pass dsX1 and dy into *arg when the optional argument is/or is not specified?</p>
0
2016-09-30T01:01:28Z
39,782,229
<p>You can just modify the call:</p> <pre><code>arr = [dsX1, dy] funcWrapper(gd.squared_error, None, *arr) </code></pre> <p>or you can do something like this: </p> <pre><code>funcWrapper(gd.squared_error, [dsX1, dy]) </code></pre>
1
2016-09-30T01:12:31Z
[ "python", "closures" ]
Modify multiple keys of dictionary by a mapping dictionary
39,782,190
<p>I have 2 dict, one original and one for mapping the original one's key to another value simultaneously,for instance:</p> <p><strong>original dict</strong></p> <pre><code>built_dict={'China':{'deportivo-cuenca-u20':{'danny':'test1'}}, 'Germany':{'ajax-amsterdam-youth':{'lance':'test2'}}} </code></pre> <p><strong>mapping dict</strong></p> <pre><code>club_team_dict={'deportivo-cuenca-u20':'deportivo','ajax-amsterdam-youth':'ajax'} </code></pre> <p>It works well if I use the following code to change the key of the nested dict of original dict,like</p> <pre><code>def club2team(built_dict,club_team_dict): for row in built_dict: # print test_dict[row] for sub_row in built_dict[row]: for key in club_team_dict: # the key of club_team_dict must be a subset of test_dict,or you have to check it and then replace it if sub_row==key: built_dict[row][club_team_dict[sub_row]] = built_dict[row].pop(sub_row) return built_dict </code></pre> <p>and the <strong>result</strong></p> <pre><code>{'Germany': {'ajax': {'lance': 'test2'}}, 'China': {'deportivo': {'danny': 'test1'}}} </code></pre> <p>so far so good, however if I have a dict with multiple key mapping to the same key,for example,my original dict is like</p> <pre><code>built_dict={'China':{'deportivo-cuenca-u20':{'danny':'test1'}}, 'Germany':{'ajax-amsterdam-youth':{'lance':'test2'}, 'ajax-amsterdam':{'tony':'test3'}}} </code></pre> <p>and the mapping dict with more then 1 key mapping to the same value,like:</p> <pre><code>club_team_dict={'deportivo-cuenca-u20':'deportivo', 'ajax-amsterdam-youth':'ajax', 'ajax-amsterdam':'ajax'} </code></pre> <p>as you can see, both <code>'ajax-amsterdam-youth'</code>and <code>'ajax-amsterdam-youth'</code> are mapping to <code>'ajax'</code>,and the trouble is when I use the same code to execute it, the original dict's size has been changed during the iteration</p> <pre><code>RuntimeError: dictionary changed size during iteration </code></pre> <p>I want to get a result with nested list for the same key like this</p> <pre><code>{'Germany': {'ajax':[{'lance': 'test2'}, {'tony' : 'test3'}]}}, 'China': {'deportivo': [{'danny': 'test1'}]}} </code></pre> <p>Any help will be appreciate,thank you, and I will keep looking for an answer by myself.</p> <hr>
0
2016-09-30T01:08:17Z
39,782,420
<p>Well I have found a solution for this,the code:</p> <pre><code>def club2team(built_dict,club_team_dict): for row in built_dict: # print test_dict[row] for sub_row in built_dict[row].keys(): for key in club_team_dict: # the key of club_team_dict must be a subset of test_dict,or you have to check it and then replace it if sub_row==key: # built_dict[row][club_team_dict[sub_row]] = built_dict[row].pop(sub_row) built_dict[row].setdefault(club_team_dict[sub_row],[]).append(built_dict[row].pop(sub_row)) return built_dict </code></pre> <p>pay attention to the <code>for sub_row in built_dict[row].keys():</code> and <code>setdefault()</code> method, I used to believe that in <code>python 2.7</code>, the default iteration for dict is just iterate the keys(), however, this time it proves it's a little different, maybe you have better solution, please show me and it will be appreciate,thank you</p>
0
2016-09-30T01:39:13Z
[ "python", "dictionary" ]
Iterating through list (Python)
39,782,221
<pre><code>collection = ["81851 19AJA01", "68158 17ARB03", "104837 20AAH02", </code></pre> <p>I have a list that extends on like this and I would like to sort them based on the first 2 digits of the second part of each. I'm really rushed right now so some help would be nice. </p> <p>I tried this and it didn't work. I'm not doing this for a class I'd really appropriate some help </p> <pre><code>for x in collection: counter = 0 i=0 for y in len(str(x)): if (x[i] == '1'): counter == 1 elif (x[i] == '2'): counter == 2 elif x[i] == '0' and counter == 2: counter = 2 elif x[i] == '9' and counter == 1: counter = 3 elif x[i] == '8' and counter == 1: counter = 4 elif x[i] == '7' and counter == 1: counter = 5 i = i + 1 if (counter==2): freshmen.append(x) elif (counter==3): sophomores.append(x) elif (counter==4): juniors.append(x) elif (counter==5): seniors.append(x) </code></pre>
-2
2016-09-30T01:11:57Z
39,782,236
<p>Use the <a href="https://docs.python.org/3/library/functions.html#sorted" rel="nofollow"><code>key</code> function</a> to define a custom sorting rule:</p> <pre><code>In [1]: collection = ["81851 19AJA01", "68158 17ARB03", "104837 20AAH02"] In [2]: sorted(collection, key=lambda x: int(x.split()[1][:2])) Out[2]: ['68158 17ARB03', '81851 19AJA01', '104837 20AAH02'] </code></pre>
3
2016-09-30T01:13:41Z
[ "python" ]
How to use cross_val_score with random_state
39,782,243
<p>I'm getting different values for different runs ... what am I doing wrong here:</p> <pre><code>X=np.random.random((100,5)) y=np.random.randint(0,2,(100,)) clf=RandomForestClassifier() cv = StratifiedKFold(y, random_state=1) s = cross_val_score(clf, X,y,scoring='roc_auc', cv=cv) print(s) # [ 0.42321429 0.44360902 0.34398496] s = cross_val_score(clf, X,y,scoring='roc_auc', cv=cv) print(s) # [ 0.42678571 0.46804511 0.36090226] </code></pre>
0
2016-09-30T01:14:27Z
39,787,608
<p>The mistake you are making is calling the <a href="http://scikit-learn.org/stable/modules/generated/sklearn.ensemble.RandomForestClassifier.html" rel="nofollow"><code>RandomForestClassifier</code></a> whose default arg, <code>random_state</code> is None. So, it picks up the seed generated by <code>np.random</code> to produce the random output.</p> <p>The <code>random_state</code> in both <a href="http://scikit-learn.org/stable/modules/generated/sklearn.model_selection.StratifiedKFold.html#sklearn.model_selection.StratifiedKFold" rel="nofollow"><code>StratifiedKFold</code></a> and <code>RandomForestClassifier</code> need to be the same inorder to produce equal arrays of scores of cross validation.</p> <p><strong>Illustration:</strong></p> <pre><code>X=np.random.random((100,5)) y=np.random.randint(0,2,(100,)) clf = RandomForestClassifier(random_state=1) cv = StratifiedKFold(y, random_state=1) # Setting random_state is not necessary here s = cross_val_score(clf, X,y,scoring='roc_auc', cv=cv) print(s) ##[ 0.57612457 0.29044118 0.30514706] print(s) ##[ 0.57612457 0.29044118 0.30514706] </code></pre> <p>Another way of countering it would be to not provide <code>random_state</code> args for both RFC and SKF. But, simply providing the <code>np.random.seed(value)</code> to create the random integers at the beginning. These would also create equal arrays at the output.</p>
3
2016-09-30T09:00:31Z
[ "python", "machine-learning", "scikit-learn" ]
Scrapy - encoding issue - scraping out quotes
39,782,247
<p>I have this class:</p> <pre><code>class PitchforkTracks(scrapy.Spider): name = "pitchfork_tracks" allowed_domains = ["pitchfork.com"] start_urls = [ "http://pitchfork.com/reviews/best/tracks/?page=1", "http://pitchfork.com/reviews/best/tracks/?page=2", "http://pitchfork.com/reviews/best/tracks/?page=3", "http://pitchfork.com/reviews/best/tracks/?page=4", "http://pitchfork.com/reviews/best/tracks/?page=5", ] def parse(self, response): for sel in response.xpath('//div[@class="track-details"]/div[@class="row"]'): item = PitchforkItem() item['artist'] = sel.xpath('.//li/text()').extract_first() item['track'] = sel.xpath('.//h2[@class="title"]/text()').extract_first() yield item </code></pre> <p>scraping this item:</p> <pre><code>&lt;h2 class="title" data-reactid="...&gt;“Colours”&lt;/h2&gt; </code></pre> <p>results, however, print like this:</p> <pre><code>{'artist': u'The Avalanches', 'track': u'\u201cColours\u201d'} </code></pre> <p><strong>where and how</strong> do I strip out the <code>quotes</code>, i.e, <code>\u201c</code> and <code>\u201d</code>?</p>
1
2016-09-30T01:14:46Z
39,782,625
<p>Inside <code>parse(self, response)</code>, add:</p> <pre><code>item['track'] = sel.xpath('.//h2[@class="title"]/text()').extract_first().strip(u'\u201c\u201d') </code></pre>
1
2016-09-30T02:11:23Z
[ "python", "scrapy" ]
Loop through categories recursively
39,782,278
<p>I'm building a python function which returns an array to be used in a select dropdown field. I have tried two versions so far. </p> <p>Both of them work, with the first returning a properly formatted select field. However, the first solution only goes two levels deep. I intend to add more depth to the categories. </p> <p>My second example is my attempt at doing this recursively to support more levels. It works but I'm wondering how I can optimize it and add dashes similar to the first example.</p> <pre><code># first example two levels deep, formatted properly with dashes def build_choice_tree(): categories = Category.query.get(1).children items = [(1, 'None')] for root in categories: items.append((root.id, root.name)) if root.children: for subcat1 in root.children: items.append((subcat1.id, '- ' + subcat1.name)) if subcat1.children: for subcat2 in subcat1.children: items.append((subcat2.id, '--' + subcat2.name)) return items # second example goes multiple levels, needs dashes def build_choice_tree2(): categories = Category.query.get(1).children items = [] def loop(categories): for category in categories: items.append((category.id, category.name)) if category.children: loop(category.children) return items result = loop(categories) return result </code></pre>
1
2016-09-30T01:19:00Z
39,782,394
<p>I change you example 2, and it will add dashes after the id, but it won't add spaces like your example 1.</p> <pre><code># second example goes multiple levels, needs dashes def build_choice_tree2(): # For the convenience of the test, I changed `categories` to a list. categories = [{ 'id': 1, 'name': 'root', 'children': [{ 'id': 2, 'name': 'child1', 'children': [{ 'id': 3, 'name': 'child2', }] }] }] items = [] def loop(categories, depth): for category in categories: items.append((category['id'], '-' * depth + ' ' + category['name'])) if category.get('children'): loop(category['children'], depth + 1) return items result = loop(categories, 0) print(result) return result if __name__ == '__main__': build_choice_tree2() </code></pre>
1
2016-09-30T01:36:19Z
[ "python", "recursion" ]
Loop through categories recursively
39,782,278
<p>I'm building a python function which returns an array to be used in a select dropdown field. I have tried two versions so far. </p> <p>Both of them work, with the first returning a properly formatted select field. However, the first solution only goes two levels deep. I intend to add more depth to the categories. </p> <p>My second example is my attempt at doing this recursively to support more levels. It works but I'm wondering how I can optimize it and add dashes similar to the first example.</p> <pre><code># first example two levels deep, formatted properly with dashes def build_choice_tree(): categories = Category.query.get(1).children items = [(1, 'None')] for root in categories: items.append((root.id, root.name)) if root.children: for subcat1 in root.children: items.append((subcat1.id, '- ' + subcat1.name)) if subcat1.children: for subcat2 in subcat1.children: items.append((subcat2.id, '--' + subcat2.name)) return items # second example goes multiple levels, needs dashes def build_choice_tree2(): categories = Category.query.get(1).children items = [] def loop(categories): for category in categories: items.append((category.id, category.name)) if category.children: loop(category.children) return items result = loop(categories) return result </code></pre>
1
2016-09-30T01:19:00Z
39,782,439
<p>Use a counter to store the number of dashes you want to add and multiply the dashes by that count. Also to make a function truly recursive you need to add the <code>return</code> statement.</p> <pre><code>def build_choice_tree2(): categories = Category.query.get(1).children items = [] count = 1 def loop(categories, count): for category in categories: items.append((category.id,'-' * count, category.name)) if category.children: count +=1 return loop(category.children, count) return items return loop(categories, count) </code></pre> <p>Personally i would separate <code>loop</code> into a different method like this and avoid the inner <code>loop</code> method in build_choice_tree2. i'll also make <code>items</code> a default argument. since default arguments (mutable) are evaluated at function definition time, it will never get reset to it's original value of an empty list.</p> <pre><code>def loop(categories, count=1, items=[]): for category in categories: items.append((category.id,'-' * count, category.name)) if category.children: count +=1 return loop(category.children, count) return items </code></pre>
2
2016-09-30T01:41:22Z
[ "python", "recursion" ]
Python handling NoneType when parsing tables
39,782,283
<p>I am trying to compare two tables (table_a and table_b) and subtract the last column of table_a from the last column of table_b. However, table_a includes an extra row and is causing me to get a NoneType Error. Is there a away I can still include the "Plums" row from table_a and just output 'NULL' for the delta cell? Below is my testable code.</p> <p>Current Code:</p> <pre><code>from datetime import datetime import itertools table_a = ( (datetime(2016, 9, 28, 0, 0), 'Apples', 650, 700, 850), (datetime(2016, 9, 28, 0, 0), 'Oranges', 900, 950, 1000), (datetime(2016, 9, 28, 0, 0), 'Grapes', 1050, 1100, 1150), (datetime(2016, 9, 28, 0, 0), 'Plums', 2000, 3000, 4000) ) table_b = ( (datetime(2016, 9, 27, 0, 0), 'Apples', 50, 150, 200), (datetime(2016, 9, 27, 0, 0), 'Oranges', 250, 350, 400), (datetime(2016, 9, 27, 0, 0), 'Grapes', 450, 550, 600), ) table_format = '{:&lt;10}|{:&lt;8}|{:&lt;8}|{:&lt;8}|{:&lt;8}|{:&lt;12}' line_sep = ('-' * 60) print(line_sep) print(table_format.format('Date', 'Count_1', 'Count_2', 'Count_3' , 'Count_4', 'Count_4_Delta')) for a, b in itertools.zip_longest(table_a, table_b): l = str(a[0])[0:10] m = a[1] n = a[2] o = a[3] p = a[4] q = b[4] print(line_sep) print(table_format.format(l, m, n, o, p, (p-q))) </code></pre> <p>Output with Error:</p> <pre><code>------------------------------------------------------------ Date |Count_1 |Count_2 |Count_3 |Count_4 |Count_4_Delta ------------------------------------------------------------ 2016-09-28|Apples |650 |700 |850 |650 ------------------------------------------------------------ 2016-09-28|Oranges |900 |950 |1000 |600 ------------------------------------------------------------ 2016-09-28|Grapes |1050 |1100 |1150 |550 Traceback (most recent call last): File "/media/test.py", line 30, in &lt;module&gt; q = b[4] TypeError: 'NoneType' object is not subscriptable </code></pre> <p>If I add a if statement to remove NoneType it prints the table without an error but excludes the "Plums" row.</p> <pre><code>for a, b in itertools.zip_longest(table_a, table_b): if a and b is not None: l = str(a[0])[0:10] m = a[1] n = a[2] o = a[3] p = a[4] q = b[4] print(line_sep) print(table_format.format(l, m, n, o, p, (p-q))) </code></pre> <p>Output with If Statement:</p> <pre><code>------------------------------------------------------------ Date |Count_1 |Count_2 |Count_3 |Count_4 |Count_4_Delta ------------------------------------------------------------ 2016-09-28|Apples |650 |700 |850 |650 ------------------------------------------------------------ 2016-09-28|Oranges |900 |950 |1000 |600 ------------------------------------------------------------ 2016-09-28|Grapes |1050 |1100 |1150 |550 </code></pre> <p>I would like to have the below output. Where the "Plums" row still prints but has the string 'NULL" for the delta cell.</p> <p>Desired Output:</p> <pre><code>------------------------------------------------------------ Date |Count_1 |Count_2 |Count_3 |Count_4 |Count_4_Delta ------------------------------------------------------------ 2016-09-28|Apples |650 |700 |850 |650 ------------------------------------------------------------ 2016-09-28|Oranges |900 |950 |1000 |600 ------------------------------------------------------------ 2016-09-28|Grapes |1050 |1100 |1150 |550 ------------------------------------------------------------ 2016-09-27|Plums |2000 |3000 |4000 |NULL </code></pre>
1
2016-09-30T01:19:44Z
39,782,328
<p><a href="https://docs.python.org/3/library/itertools.html#itertools.zip_longest" rel="nofollow"><code>itertools.zip_longest</code></a> accepts an optional <code>fillvalue</code> parameter. If it's provided, it is used instead of <code>None</code>:</p> <pre><code>&gt;&gt;&gt; list(itertools.zip_longest([1, 2, 3], [4, 5])) [(1, 4), (2, 5), (3, None)] &gt;&gt;&gt; list(itertools.zip_longest([1, 2, 3], [4, 5], fillvalue='NULL')) [(1, 4), (2, 5), (3, 'NULL')] </code></pre> <p>You can provide empty row (a list of NULL values) as the <code>fillvalue</code>:</p> <pre><code>class EmptyValue: def __sub__(self, other): return 'NULL' def __rsub__(self, other): return 'NULL' empty_row = [None, 'NULL', EmptyValue(), EmptyValue(), EmptyValue()] for a, b in itertools.zip_longest(table_a, table_b, fillvalue=empty_row): ... </code></pre>
2
2016-09-30T01:25:56Z
[ "python", "python-3.x", "parsing", "itertools", "nonetype" ]
Python handling NoneType when parsing tables
39,782,283
<p>I am trying to compare two tables (table_a and table_b) and subtract the last column of table_a from the last column of table_b. However, table_a includes an extra row and is causing me to get a NoneType Error. Is there a away I can still include the "Plums" row from table_a and just output 'NULL' for the delta cell? Below is my testable code.</p> <p>Current Code:</p> <pre><code>from datetime import datetime import itertools table_a = ( (datetime(2016, 9, 28, 0, 0), 'Apples', 650, 700, 850), (datetime(2016, 9, 28, 0, 0), 'Oranges', 900, 950, 1000), (datetime(2016, 9, 28, 0, 0), 'Grapes', 1050, 1100, 1150), (datetime(2016, 9, 28, 0, 0), 'Plums', 2000, 3000, 4000) ) table_b = ( (datetime(2016, 9, 27, 0, 0), 'Apples', 50, 150, 200), (datetime(2016, 9, 27, 0, 0), 'Oranges', 250, 350, 400), (datetime(2016, 9, 27, 0, 0), 'Grapes', 450, 550, 600), ) table_format = '{:&lt;10}|{:&lt;8}|{:&lt;8}|{:&lt;8}|{:&lt;8}|{:&lt;12}' line_sep = ('-' * 60) print(line_sep) print(table_format.format('Date', 'Count_1', 'Count_2', 'Count_3' , 'Count_4', 'Count_4_Delta')) for a, b in itertools.zip_longest(table_a, table_b): l = str(a[0])[0:10] m = a[1] n = a[2] o = a[3] p = a[4] q = b[4] print(line_sep) print(table_format.format(l, m, n, o, p, (p-q))) </code></pre> <p>Output with Error:</p> <pre><code>------------------------------------------------------------ Date |Count_1 |Count_2 |Count_3 |Count_4 |Count_4_Delta ------------------------------------------------------------ 2016-09-28|Apples |650 |700 |850 |650 ------------------------------------------------------------ 2016-09-28|Oranges |900 |950 |1000 |600 ------------------------------------------------------------ 2016-09-28|Grapes |1050 |1100 |1150 |550 Traceback (most recent call last): File "/media/test.py", line 30, in &lt;module&gt; q = b[4] TypeError: 'NoneType' object is not subscriptable </code></pre> <p>If I add a if statement to remove NoneType it prints the table without an error but excludes the "Plums" row.</p> <pre><code>for a, b in itertools.zip_longest(table_a, table_b): if a and b is not None: l = str(a[0])[0:10] m = a[1] n = a[2] o = a[3] p = a[4] q = b[4] print(line_sep) print(table_format.format(l, m, n, o, p, (p-q))) </code></pre> <p>Output with If Statement:</p> <pre><code>------------------------------------------------------------ Date |Count_1 |Count_2 |Count_3 |Count_4 |Count_4_Delta ------------------------------------------------------------ 2016-09-28|Apples |650 |700 |850 |650 ------------------------------------------------------------ 2016-09-28|Oranges |900 |950 |1000 |600 ------------------------------------------------------------ 2016-09-28|Grapes |1050 |1100 |1150 |550 </code></pre> <p>I would like to have the below output. Where the "Plums" row still prints but has the string 'NULL" for the delta cell.</p> <p>Desired Output:</p> <pre><code>------------------------------------------------------------ Date |Count_1 |Count_2 |Count_3 |Count_4 |Count_4_Delta ------------------------------------------------------------ 2016-09-28|Apples |650 |700 |850 |650 ------------------------------------------------------------ 2016-09-28|Oranges |900 |950 |1000 |600 ------------------------------------------------------------ 2016-09-28|Grapes |1050 |1100 |1150 |550 ------------------------------------------------------------ 2016-09-27|Plums |2000 |3000 |4000 |NULL </code></pre>
1
2016-09-30T01:19:44Z
39,782,367
<p><a href="https://docs.python.org/3/library/itertools.html#itertools.zip_longest" rel="nofollow">zip_longest</a> returns a singular <code>None</code> type when it runs out of values. You want a list of <code>None</code>s or you get a <code>TypeError</code> when you try and use the subscript <code>[]</code> operator. </p> <p>Use the optional fillvalue to get a list of <code>None</code>s and then test for <code>None</code> when you format for output so you don't get another <code>TypeError</code> when you try and do <code>p-q</code> when <code>q</code> is <code>None</code>:</p> <pre><code>for a, b in itertools.zip_longest(table_a, table_b,fillvalue=[None]*5): l = str(a[0])[0:10] m = a[1] n = a[2] o = a[3] p = a[4] q = b[4] print(line_sep) print(table_format.format(l, m, n, o, p, (p-q) if q is not None else 'NULL')) </code></pre>
1
2016-09-30T01:33:13Z
[ "python", "python-3.x", "parsing", "itertools", "nonetype" ]
Displaying Legend in Matplotlib Basemap
39,782,391
<p>I have a basemap plotted using the following code snippet:</p> <pre><code>#setting the size plt.figure(figsize=(20,10)) #iterating through each country in shape file and filling them with color assigned using the colors array for nshape,seg in enumerate(m.countries): #getting x,y co-ordinates xx,yy = zip(*seg) #getting the corresponding color color = colors[countryisos[nshape]] #plotting them on the map plt.fill(xx,yy,color,edgecolor=color) #setting the parallels with 10 degree interval from -90 to 90 degrees parallels = np.arange(-80.,81,10.) m.drawparallels(parallels,labels=[True,True,True,True]) #setting the meridians with 20 degree interval from -180 to 180 degrees meridians = np.arange(10.,351.,20.) m.drawmeridians(meridians,labels=[True,False,False,True]) #setting the title for the plot plt.title('Number of Disasters by Country: 1981-2014') </code></pre> <p>Three colours are assigned to colors array using this function.</p> <pre><code>colors={} #iterating through each country in shape file and setting the corresponding color for s in countryisos: if countvalues[s]&lt;=200: colors[s] = 'orange' elif countvalues[s]&gt;200 and countvalues[s]&lt;=400: colors[s] = 'yellow' else: colors[s] = 'red' </code></pre> <p>How can set a legend for this plot showing three colours each defining a range? I cannot use 'label' parameter inside plot function since it is in a for loop.</p>
0
2016-09-30T01:35:46Z
39,782,772
<p>Solved it using patches in matplotlib. I just added this code below to display the custom legend.</p> <pre><code>#setting the legend for the plot using patch lt = mpatches.Patch(color='orange', label='&lt;200') btwn = mpatches.Patch(color='yellow', label='200-400') gt = mpatches.Patch(color='red', label='&gt;400') plt.legend(handles=[lt,btwn,gt],title='Number of disasters', loc=3) </code></pre>
1
2016-09-30T02:32:50Z
[ "python", "pandas", "matplotlib" ]
Remove punctuations in pandas
39,782,418
<pre><code>code: df['review'].head() index review output: 0 These flannel wipes are OK, but in my opinion </code></pre> <p>I want to remove punctuations from the column of the dataframe and create a new column.</p> <pre><code>code: import string def remove_punctuations(text): return text.translate(None,string.punctuation) df["new_column"] = df['review'].apply(remove_punctuations) Error: return text.translate(None,string.punctuation) AttributeError: 'float' object has no attribute 'translate' </code></pre> <p>I am using python 2.7. Any suggestions would be helpful.</p>
0
2016-09-30T01:39:04Z
39,782,704
<p>I solved the problem by looping through the string.punctuation</p> <pre><code>def remove_punctuations(text): for punctuation in string.punctuation: text = text.replace(punctuation, '') return text </code></pre> <p>You can call the function the same way you did and It should work.</p> <pre><code>df["new_column"] = df['review'].apply(remove_punctuations) </code></pre>
1
2016-09-30T02:23:03Z
[ "python", "python-2.7", "pandas" ]
Remove punctuations in pandas
39,782,418
<pre><code>code: df['review'].head() index review output: 0 These flannel wipes are OK, but in my opinion </code></pre> <p>I want to remove punctuations from the column of the dataframe and create a new column.</p> <pre><code>code: import string def remove_punctuations(text): return text.translate(None,string.punctuation) df["new_column"] = df['review'].apply(remove_punctuations) Error: return text.translate(None,string.punctuation) AttributeError: 'float' object has no attribute 'translate' </code></pre> <p>I am using python 2.7. Any suggestions would be helpful.</p>
0
2016-09-30T01:39:04Z
39,782,973
<p>Using <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.replace.html" rel="nofollow">Pandas str.replace</a> and regex:</p> <pre><code>df["new_column"] = df['review'].str.replace('[^\w\s]','') </code></pre>
2
2016-09-30T02:59:49Z
[ "python", "python-2.7", "pandas" ]
How to loop through keys in a dict to find the corresponding value?
39,782,484
<p>When a user enters a name (e.g. "Jim") as an argument for an instance of my "Test" class, the <code>def find</code> function is called and for-loops through all the names in the dict matching "Jim". If <code>def find</code> finds the key word "Jim" in the dict, then it should print out the corresponding value. But when I run the code it just says "None". What do I need to change so that invoking <code>def find</code> results in the print statement 'worked'??</p> <pre><code>class Test(object): def __init__(self, x=0): # error in (def find)? self.x = x c = None # error while looping in the for loop? users = { 'John': 1, 'Jim': 2, 'Bob': 3 } def find(self, x): # The user is supposed to type in the name "x" for self.c in self.users: # it goes through the dictionary if x == self.users[self.c]: # If x is equal to key it prints worked print('worked') else: pass beta = Test() print(beta.find('Jim')) </code></pre>
-2
2016-09-30T01:49:01Z
39,782,619
<p>@nk001,<br> I think this is a little more like what you are trying for:</p> <pre><code>class Test(object): def __init__(self, x=0): self.x = x # &lt;-- indent the __init__ statements users = { # &lt;-- users = { 'John': 1, # KEY: VALUE, 'Jim': 2, # KEY: VALUE, 'Bob': 3 # KEY: VALUE, } # } def find(self, x): # &lt;-- The user passes the "x" argument for i in self.users: # &lt;-- Now it goes through the dictionary if x == i: # &lt;-- If ARGV('x') == KEY return 'worked' # &lt;-- Then RETURN 'worked' else: pass beta = Test() print(beta.find("Jim"), beta.users["Jim"]) </code></pre> <p>There's a couple different ways to get the 'worked' msg and the corresponding Value printed, this is just an example to demonstrate accessing the dict[KEY] to get the VALUE. </p> <p>Also, I'm just assuming you meant an if/else block, and not a for/else? Indentation is critical w/Python. Also, your original script was returning None because there was no explicit <code>return</code> in your for loop - hence, when the function is called in the printing statement <code>print(beta.find('Jim'))</code> when the function finishes it returns nothing ("None"). Hope that helps!</p>
2
2016-09-30T02:10:13Z
[ "python" ]
How to loop through keys in a dict to find the corresponding value?
39,782,484
<p>When a user enters a name (e.g. "Jim") as an argument for an instance of my "Test" class, the <code>def find</code> function is called and for-loops through all the names in the dict matching "Jim". If <code>def find</code> finds the key word "Jim" in the dict, then it should print out the corresponding value. But when I run the code it just says "None". What do I need to change so that invoking <code>def find</code> results in the print statement 'worked'??</p> <pre><code>class Test(object): def __init__(self, x=0): # error in (def find)? self.x = x c = None # error while looping in the for loop? users = { 'John': 1, 'Jim': 2, 'Bob': 3 } def find(self, x): # The user is supposed to type in the name "x" for self.c in self.users: # it goes through the dictionary if x == self.users[self.c]: # If x is equal to key it prints worked print('worked') else: pass beta = Test() print(beta.find('Jim')) </code></pre>
-2
2016-09-30T01:49:01Z
39,782,629
<p>I write a worked code:</p> <pre><code>class Test(object): users = { 'John': 1, 'Jim': 2, 'Bob': 3 } def __init__(self, x=0): # So I don't get an error in (def find) self.x = x def find(self, x): # The user is suppose to type in the name "x" for name in Test.users.keys(): # it goes through the dictionary if x == name: # If x is equal to key it prints worked print('worked', self.users[name]) else: pass beta = Test() beta.find('Jim') </code></pre> <ol> <li>You don not need the <code>self.c</code>.</li> <li>The <code>users</code> is a class variable, you need to visit it by <code>Test.users</code>.</li> <li>Your names is stored as the keys of the dict. So you need to get them by <code>Test.users.keys()</code></li> <li>The statement <code>print(beta.find('Jim'))</code> will print the return value of the <code>find</code>. But you don't return a value manually, you will get a <code>None</code> in your output.</li> </ol>
1
2016-09-30T02:12:13Z
[ "python" ]
Django: extending models of other apps
39,782,563
<p>I'm working on small ERP-like project on Django which contains different apps (Products, Sales, Purchases, Accounting, MRP, ...). A few of them have dependencies (for example, a Sales app requires the Products app).</p> <p>For the sake of modularity and loose-coupling, I'm trying to keep the apps as independent as possible. However, it would be extremely useful and make things way simpler if the apps could extend (add new fields) tables in the models of their dependencies (for instance, Sales would add a <code>can_be_sold</code> BooleanField in one of the tables within the scope of Products, if it is installed).</p> <p>This way when a user internally chooses to install an app, the required changes in the database are made for it to integrate properly with the dependencies. The user installs only the apps he needs without having to provide unnecessary or unrelated information a priori in the dependencies.</p> <p>I thought of making one-to-one relationships with the dependencies, but this solution doesn't convince me because (a) it doesn't seem very efficient to make so many new tables for maybe one or two extra fields, and (b) working with forms and signals would be a hassle (making code harder to mantain if many apps are installed and decreasing modularity overall). </p> <p>Inheritance or abstract classes also seem inappropriate, because I'm not trying to create a model for, say, a subproduct, but rather grow or expand on existing information (entries) in a table.</p> <p>What is the best way to achieve this? Should I be looking into writing custom migration operations? Otherwise, are there better approaches? Thanks!</p>
1
2016-09-30T02:02:50Z
39,900,585
<p>I d recommend you to create a database tabel to save all your possible registered modules and class. so you can use it as variable python code inside an eval statement. and if you have pre-defined methods names, in this approach bellow i called it common_method.</p> <p>you don t even need to have an abstract class</p> <pre><code>my_evaluated_code = 'from '+mymodule_var_name + ' import ' + myclass_var_name +' as custommodule' eval(my_evaluated_code) custommodule.common_method() </code></pre>
1
2016-10-06T15:55:43Z
[ "python", "django", "django-models", "django-migrations", "django-apps" ]
How to transfer data from Django to Ext JS
39,782,576
<p>I'm new to web programming. I would like to create a simple Django application with Ext JS interface. Task: The user enters data into a database using forms and sees the database upgrade.It has been done to solve the problem as follows. Written Django application.</p> <p><strong>views.py</strong></p> <pre class="lang-python prettyprint-override"><code>def addProduct(request): if request.method == 'POST': form = ProductForm(request.POST) if form.is_valid(): data = form.cleaned_data product_name = data['product_name'] product_price = data['product_price'] Products.objects.create(name=product_name, price=product_price) else: form = ProductForm() return render(request, 'addProduct.html', { 'ProductsList': Products.objects.all(), 'form': form, # 'Title': 'Range of products', # 'product_name': 'type product name here', }) </code></pre> <p><strong>template</strong></p> <pre class="lang-html prettyprint-override"><code> &lt;!DOCTYPE html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;meta charset="UTF-8"&gt; &lt;title&gt;{{ Title }}&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;table&gt; &lt;tr&gt; &lt;th&gt;Name&lt;/th&gt; &lt;th&gt;Product&lt;/th&gt; &lt;/tr&gt; {% for current in ProductsList %} &lt;tr&gt; &lt;td&gt;{{ current.name }}&lt;/td&gt; &lt;td&gt;{{ current.price }}&lt;/td&gt; &lt;/tr&gt; {% endfor %} &lt;/table&gt; &lt;form action="check/" method="post"&gt; {% csrf_token %} {{ form }} &lt;input type="submit" value="ADD" /&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p><strong>forms.py</strong></p> <pre class="lang-python prettyprint-override"><code>class ProductForm(forms.Form): product_name = forms.CharField(max_length=100) product_price = forms.IntegerField() </code></pre> <p><strong>models.py</strong></p> <pre class="lang-python prettyprint-override"><code>class Products(models.Model): name = models.CharField(max_length=30) price = models.IntegerField() </code></pre> <p>This works well.</p> <p><a href="http://i.stack.imgur.com/HfzLj.png" rel="nofollow"><img src="http://i.stack.imgur.com/HfzLj.png" alt="Result"></a></p> <p>Now I would like to use <em>Ext.grid.Panel</em> component from Ext JS to render table. Question: How do I transfer data from Django to Ext JS? </p> <p><strong><em>UPDATE</em></strong></p> <p>I wrote a simple grid, but it turns out the table is empty. What am I doing wrong?</p> <pre><code> Ext.onReady(function () { Ext.define('Products', { extend: 'Ext.data.Model', fields: [{ name: 'Name', type: 'string' }, { name: 'Price', type: 'int' }] }); var store = Ext.create('Ext.data.Store', { model: 'Products', autoLoad: true, proxy: { type: 'rest', url: 'http://127.0.0.1:8000/products/', reader: { type: 'json' } } }); Ext.create('Ext.grid.Panel', { title: 'Products', height: 200, width: 400, store: store, columns: [{ header: 'Name', dataIndex: 'Name' }, { header: 'Price', dataIndex: 'Price' }], renderTo: Ext.getBody() }); }); </code></pre> <p>I also updated the Django project using Django Rest Framework for REST technology:</p> <pre><code>class ProductsList(generics.ListCreateAPIView): queryset = Products.objects.all() serializer_class = ProductsSerializer class ProductDetail(generics.RetrieveUpdateDestroyAPIView): queryset = Products.objects.all() serializer_class = ProductsSerializer </code></pre>
0
2016-09-30T02:04:16Z
39,783,319
<p>Use ajax.</p> <p>just like this:</p> <pre><code>$('#likes').click(function () { var catid; catid = $(this).attr("data-catid"); $.get('/rango/like_category/', {category_id: catid}, function (data) { $('#like_count').html(data); $('#likes').hide(); }); }); </code></pre>
0
2016-09-30T03:40:53Z
[ "python", "django", "extjs" ]
How to transfer data from Django to Ext JS
39,782,576
<p>I'm new to web programming. I would like to create a simple Django application with Ext JS interface. Task: The user enters data into a database using forms and sees the database upgrade.It has been done to solve the problem as follows. Written Django application.</p> <p><strong>views.py</strong></p> <pre class="lang-python prettyprint-override"><code>def addProduct(request): if request.method == 'POST': form = ProductForm(request.POST) if form.is_valid(): data = form.cleaned_data product_name = data['product_name'] product_price = data['product_price'] Products.objects.create(name=product_name, price=product_price) else: form = ProductForm() return render(request, 'addProduct.html', { 'ProductsList': Products.objects.all(), 'form': form, # 'Title': 'Range of products', # 'product_name': 'type product name here', }) </code></pre> <p><strong>template</strong></p> <pre class="lang-html prettyprint-override"><code> &lt;!DOCTYPE html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;meta charset="UTF-8"&gt; &lt;title&gt;{{ Title }}&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;table&gt; &lt;tr&gt; &lt;th&gt;Name&lt;/th&gt; &lt;th&gt;Product&lt;/th&gt; &lt;/tr&gt; {% for current in ProductsList %} &lt;tr&gt; &lt;td&gt;{{ current.name }}&lt;/td&gt; &lt;td&gt;{{ current.price }}&lt;/td&gt; &lt;/tr&gt; {% endfor %} &lt;/table&gt; &lt;form action="check/" method="post"&gt; {% csrf_token %} {{ form }} &lt;input type="submit" value="ADD" /&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p><strong>forms.py</strong></p> <pre class="lang-python prettyprint-override"><code>class ProductForm(forms.Form): product_name = forms.CharField(max_length=100) product_price = forms.IntegerField() </code></pre> <p><strong>models.py</strong></p> <pre class="lang-python prettyprint-override"><code>class Products(models.Model): name = models.CharField(max_length=30) price = models.IntegerField() </code></pre> <p>This works well.</p> <p><a href="http://i.stack.imgur.com/HfzLj.png" rel="nofollow"><img src="http://i.stack.imgur.com/HfzLj.png" alt="Result"></a></p> <p>Now I would like to use <em>Ext.grid.Panel</em> component from Ext JS to render table. Question: How do I transfer data from Django to Ext JS? </p> <p><strong><em>UPDATE</em></strong></p> <p>I wrote a simple grid, but it turns out the table is empty. What am I doing wrong?</p> <pre><code> Ext.onReady(function () { Ext.define('Products', { extend: 'Ext.data.Model', fields: [{ name: 'Name', type: 'string' }, { name: 'Price', type: 'int' }] }); var store = Ext.create('Ext.data.Store', { model: 'Products', autoLoad: true, proxy: { type: 'rest', url: 'http://127.0.0.1:8000/products/', reader: { type: 'json' } } }); Ext.create('Ext.grid.Panel', { title: 'Products', height: 200, width: 400, store: store, columns: [{ header: 'Name', dataIndex: 'Name' }, { header: 'Price', dataIndex: 'Price' }], renderTo: Ext.getBody() }); }); </code></pre> <p>I also updated the Django project using Django Rest Framework for REST technology:</p> <pre><code>class ProductsList(generics.ListCreateAPIView): queryset = Products.objects.all() serializer_class = ProductsSerializer class ProductDetail(generics.RetrieveUpdateDestroyAPIView): queryset = Products.objects.all() serializer_class = ProductsSerializer </code></pre>
0
2016-09-30T02:04:16Z
39,801,650
<p>I see two ways: 1) Make special server action, that will be return JSON-based view. On main template create Ext.grid.Grid with remote store, that will request data from server action, that returns JSON. It's mostly usable case. Look here example: <a href="http://docs.sencha.com/extjs/6.2.0/modern/Ext.grid.Grid.html" rel="nofollow">http://docs.sencha.com/extjs/6.2.0/modern/Ext.grid.Grid.html</a> - grid <a href="http://docs.sencha.com/extjs/6.2.0/modern/Ext.data.Store.html" rel="nofollow">http://docs.sencha.com/extjs/6.2.0/modern/Ext.data.Store.html</a> - store</p> <p>2) Make html table with data, and transform it to ExtJS grid like here: <a href="http://examples.sencha.com/extjs/6.2.0/examples/classic/grid/binding.html" rel="nofollow">http://examples.sencha.com/extjs/6.2.0/examples/classic/grid/binding.html</a></p>
0
2016-10-01T00:04:11Z
[ "python", "django", "extjs" ]
List contains exactly three of the same elements?
39,782,641
<p>This will return Boolean True if the list has three of the same integers given. It will return a Boolean False if it does not have three of the same integers. I am having trouble writing this. Does the count feature do this? Also, is importing an empty list necessary? I have this and I get the error "'int' object has no attribute 'count'". Thank you!</p> <pre><code> def threeOfAKind(aList,n): if aList.count(n): return True else: return False </code></pre> <p>threeOfAKind([1,2,3,4,4,4],4]) should return True I tried aList.count(n) but now I get True no matter what I call </p>
0
2016-09-30T02:13:52Z
39,793,809
<p>This line:</p> <pre><code>if aList.count(n): </code></pre> <p>is the reason why your code is not working.</p> <p>The <code>count</code> function of <code>list</code> returns the number of occurences of <code>n</code> in the list. If your arguments are [1,2,3,4,4,4] and 4, <code>aList.count(n)</code> will return 3 because 4 occurs 3 times in the list.</p> <p>So the line of code above is basically the same as:</p> <pre><code>if 3: </code></pre> <p>Now 3 will get converted to a boolean value because that's what expected for an <code>if</code> condition. If you want to know 3 is converted to True or False, just try <code>bool(3)</code> in your interactive Python interpreter.</p> <p>What you want is to check if <code>n</code> occures 3 times in the list, so you may need to compare the returned value of <code>aList.count(n)</code> with something? You obvisouly don't want to return True if <code>aList.count(n)</code> returns 2 or 4, do you?</p>
0
2016-09-30T14:25:10Z
[ "python", "list", "count", "integer" ]
Automatically Run a Script in my Browser console after opening a link using Python
39,782,670
<p>I want to run some JavaScript in my browser DevTools console. So far, I have opened up a specific website only through it. Can it be done in Python?</p> <p>Right now, I am using the following code:</p> <pre><code>url = 'http://some-website.com/' webbrowser.open(url) </code></pre> <p>What I want to do now is open up the DevTools console panel and then run a script through it automatically? Can it be done by using Python or some other tool along with Python?</p>
0
2016-09-30T02:18:25Z
39,782,792
<p>I don't belive this can be done, as </p> <blockquote> <p>ChromeDriver 2 and the DevTools windows both compete for the same automation channel, and ChromeDriver automatically closes the DevTools window in order for it to work.</p> </blockquote> <p>See here for more: <a href="http://stackoverflow.com/questions/18420769/chrome-developer-tools-closes-instantly-when-attempting-to-debug-webdriver-e2e-t">Chrome Developer Tools closes instantly when attempting to debug WebDriver E2E test</a></p>
0
2016-09-30T02:34:35Z
[ "javascript", "python", "selenium", "google-chrome-devtools" ]
speed improvement in postgres INSERT command
39,782,681
<p>I am writing a program to load data into a particular database. This is what I am doing right now ...</p> <pre><code> conn = psycopg2.connect("dbname='%s' user='postgres' host='localhost'"%dbName) cur = conn.cursor() lRows = len(rows) i, iN = 0, 1000 while True: if iN &gt;= lRows: # write the last of the data, and break ... iN = lRows values = [dict(zip(header, r)) for r in rows[i:iN]] cur.executemany( insertString, values ) conn.commit() break values = [dict(zip(header, r)) for r in rows[i:iN]] cur.executemany( insertString, values ) conn.commit() i += 1000 iN += 1000 cur.close() conn.close() </code></pre> <p>I am aware about <a href="http://stackoverflow.com/questions/758945/whats-the-fastest-way-to-do-a-bulk-insert-into-postgres">this</a> question about the use of the <code>COPY</code> command. However, I need to do some bookkeeping on my files before I can upload the files into a database. Hence I am using Python in this manner. </p> <p>I have a couple of questions on how to make things faster ...</p> <ol> <li>Would it be better (or possible) to do many <code>cur.executemany()</code> statements and a single <code>conn.commit()</code> at the end? This means that I will put a <em>single</em> <code>conn.commit()</code> statement just before the <code>cur.close()</code> statement.</li> <li>I have always seen other people use <code>cur.executemany()</code> for batches of like 1000 or so records. Is this generally the case or is it possible to just do an <code>cur.executemany()</code> on the entire set of records that I read from the file. I would potentially have hundreds of thousands of records, or maybe a little over a million records. (I have sufficient RAM to fit the entire file in memory). How do I know the upper limit of the number of records that I can upload at any one time. </li> <li>I am making a fresh connection to the database for every file that I am opening. I am doing this because, this process is taking me many days to complete and I dont want issues with connection to corrupt the entirety of the data, if the connection is lost at any time. I have over a thousand files that I need to go through. Are these thousand connections that we are making going to be a significant part of the time that is used for the process?</li> <li>Are there any other things that I am doing in the program that I shouldn't be doing that can shorten the total time for the process?</li> </ol> <p>Thanks very much for any help that I can get. Sorry for the questions being so basic. I am just starting with databases in Python, and for some reason, I don't seem to have any definitive answer to any of these questions right now. </p>
2
2016-09-30T02:19:55Z
39,787,963
<ol> <li><p>As you mentioned at p.3 you are worried about database connection, that might break, so if you use one <code>conn.commit()</code> only after all inserts, you can easily loose already inserted, but not commited data if your connection breaks before <code>conn.commit()</code>. If you do <code>conn.commit()</code> after each <code>cur.executemany()</code>, you won't loose everything, only the last batch. So, it's up to you and depends on a workflow you need to support.</p></li> <li><p>The number of records per batch is a trade-off between insertion speed and other things. You need to choose value that satisfies your requirements, you can test your script with 1000 records per batch, with 10000 per batch and check the difference. The case of inserting whole file within one <code>cur.executemany()</code> has an advantage of an atomicity: if it has been executed, that means all records from this particular file have been inserted, so we're back to p. 1.</p></li> <li><p>I think the cost of establishing a new connection in your case does not really matter. Let's say, if it takes one second to establish new connection, with 1000 files it will be 1000 seconds spent on connection within days.</p></li> <li><p>The program itself looks fine, but I would still recommend you to take a look on <code>COPY TO</code> command with <code>UNLOGGED</code> or <code>TEMPORARY</code> tables, it will really speed up your imports.</p></li> </ol>
1
2016-09-30T09:17:23Z
[ "python", "postgresql", "psycopg2" ]
Print a list of items separated by commas but with the word "and" before the last item
39,782,689
<p>I've been working on this for two days. This is what the assignment states:</p> <blockquote> <p>Say you have a list value like this: <code>listToPrint = ['apples', 'bananas', 'tofu', 'cats']</code> Write a program that prints a list with all the items separated by a comma and a space, with "and" inserted before the last item. For example, the above list would print <code>'apples, bananas, tofu, and cats'</code>. But your program should be able to work with any list not just the one shown above. Because of this, you will need to use a loop in case the list to print is shorter or longer than the above list.</p> </blockquote> <p>This is what I have thus far:</p> <pre><code>listToPrint = [] while True: newWord = input("a, b, and c ") if newWord == "": break else: listToPrint.append(newWord) </code></pre>
2
2016-09-30T02:21:02Z
39,783,442
<p>Here is how I would do it, but be careful if this is for school. Your instructor will frown on you if any of the things I have done below are using features or techniques that haven't yet been covered.</p> <pre><code>listToPrint = ['a', 'b', 'c'] def list_to_string(L, sep = '', last_sep = None): if last _sep is None: return sep.join(L) else: return sep.join(L[:-1]) + last_sep + L[-1] print(list_to_string(listToPrint, sep = ', ', last_sep = ', and ')) </code></pre> <p>Here's a bit more of a beginner version: </p> <pre><code>listToPrint = ['a', 'b', 'c'] list_length = len(listToPrint) result = "" count = 0 for item in listToPrint: count = count + 1 if count == list_length: result = result + "and " + item else: result = result + item + ", " </code></pre> <p>This one doesn't work with only one item in the list. </p>
0
2016-09-30T03:57:00Z
[ "python", "list", "python-3.x", "loops", "for-loop" ]
Print a list of items separated by commas but with the word "and" before the last item
39,782,689
<p>I've been working on this for two days. This is what the assignment states:</p> <blockquote> <p>Say you have a list value like this: <code>listToPrint = ['apples', 'bananas', 'tofu', 'cats']</code> Write a program that prints a list with all the items separated by a comma and a space, with "and" inserted before the last item. For example, the above list would print <code>'apples, bananas, tofu, and cats'</code>. But your program should be able to work with any list not just the one shown above. Because of this, you will need to use a loop in case the list to print is shorter or longer than the above list.</p> </blockquote> <p>This is what I have thus far:</p> <pre><code>listToPrint = [] while True: newWord = input("a, b, and c ") if newWord == "": break else: listToPrint.append(newWord) </code></pre>
2
2016-09-30T02:21:02Z
39,783,454
<p>The code you've shown appears to be solving a different problem than what your assignment wants you to do. The assignment is focused on <code>print</code>ing the values from a provided <code>list</code>, while your code is all about <code>input</code>ing items from the user and putting them into a list. It could make sense to do one and then the other, but for the assignment that you've given in the comments, the <code>input</code> code is completely irrelevant.</p> <p>Here's how I'd solve that assignment (probably with code that you don't understand yet):</p> <pre><code>print("{}, and {}".format(", ".join(list_to_print[:-1]), list_to_print[-1])) </code></pre> <p>A more "novice friendly" approach would look more like this:</p> <pre><code>for item in list_to_print[:-1]: print(item, end=', ') print('and', list_to_print[-1]) </code></pre>
1
2016-09-30T03:58:05Z
[ "python", "list", "python-3.x", "loops", "for-loop" ]
How to measure the length of a 2-dimensional path in separate steps
39,782,696
<p>I am a newbie in python. I am stuck by finding the length of a path in 2d. I have no idea what I'm doing wrong. Please help!</p> <pre><code>import math vector1 = v1 vector2 = v2 def length (v): """ Length of a vector in 2-space. Params: v (2-tuple) vector in 2-space Returns: (float) length """ v = sqrt(v1**2 + v2**2) return v def dist (P,Q): """ Distance in 2-space. Params: P (2-tuple): a point in 2-space Q (2-tuple): another point in 2-space Returns: (float) dist (P,Q) """ dist = [(Q - P) **2] dist = math.sqrt(sum(dist)) return dist P = [p0, p1] Q = [q0, q1] def pathLength2d (pt): """Length of a 2-dimensional path. Standard length as measured by a ruler. Params: pt (list of 2-tuples): path in 2-space Returns: (float) length of this path """ pt = math.hypot(q0 - p0, q1 -p1) return pt print (pathLength2d ([(0,0), (1,1)])) </code></pre>
0
2016-09-30T02:21:42Z
39,783,369
<p>Yes, please fix your formatting, shift everything by four spaces.</p> <p>But I believe your first method is:</p> <pre><code> def length(v): """ Length of a vector in 2-space. Params: v (2-tuple) vector in 2-space Returns: (float) length """ v = sqrt(v1**2 + v2**2) return v </code></pre> <p>That method doesn't know what v1 and v2 are, you need to define them like this:</p> <pre><code>def length(v): """ Length of a vector in 2-space. Params: v (2-tuple) vector in 2-space Returns: (float) length """ v1 = v(0) v2 = v(1) v = math.sqrt(v1**2 + v2**2) return v </code></pre> <p>you also need to use <code>math.sqrt</code> </p> <p>For the distance function, you can't subtract two tuples like that. you'll need something as follows:</p> <pre><code>def dist(P, Q): """ Distance in 2-space. Params: P (2-tuple): a point in 2-space Q (2-tuple): another point in 2-space Returns: (float) dist (P,Q) """ dist = math.sqrt((P[0] - Q[0])**2 + (P[1]-Q[1])**2) return dist </code></pre>
0
2016-09-30T03:46:43Z
[ "python", "python-3.x", "vector", "euclidean-distance" ]
Translate cURL headers command to python-requests
39,782,699
<p>I need to pass a POST containing a token to a website to get an auth key, I've done it successfully using cURL with this statement:</p> <p><code>curl -D - --request POST https://login.website.com/g/aaa/authorize --data-urlencode token=[TOKEN] </code></p> <p>However, I cannot seem to get the same outcome using the Python requests module:</p> <p><code>auth_token = requests.post('https://login.website.com/g/aaa/authorize', data=token)</code></p> <p><code>auth_token.text</code> just gives me <code>'Unauthorized'</code></p> <p>I've tried passing the data kawrg as :</p> <ul> <li>straight JSON </li> <li>a string</li> <li>adding <code>token=</code> to the beginning of the string</li> <li>using <code>params</code> instead of data and passing it JSON (this gets me <code>unexpected argument: {"token" : "value....."}</code>)</li> </ul> <p>What is the significance of <code>-D</code> and <code>--data-urlencode</code> (as opposed to just <code>--data</code>) in this case, should I be trying to dump a header as an argument into the <code>requests.post()</code>?</p> <p><em>ЕDIT:</em> In the cURL output, the auth_key also is printed before any of the json starts:</p> <pre><code>Set-Cookie: auth_key=[auth_key]; Domain=.website.com; expires=Fri, 30-Sep-2016 01:41:09 GMT; httponly; Max-Age=14399; Path=/ </code></pre>
1
2016-09-30T02:22:26Z
39,783,252
<p>Found the answer, <code>requests.json()</code> needed to be used instead of <code>json.dumps(data)</code>, the latter is improperly formatted, so this code worked out fine:</p> <pre><code>s.token = requests.post(url, data=data) s.recieved = s.token.json() t = requests.post(url, data=s.recieved) </code></pre>
0
2016-09-30T03:34:48Z
[ "python", "curl", "python-requests" ]
Parsed timed_id3 values from HLS stream
39,782,706
<p>How do I parse timed_id3 values taken from a HLS stream chunk?</p> <p>Twitch stream chunks contain info like encoding time in a 3rd data stream that ffprobe identifies as timed_id3, the extracted data is:</p> <pre><code>b'\x00\x00\x00\x020TRCK\x00\x00\x00\x06\x00\x00\x033936\x00TDEN\x00\x00\x00\x15\x00\x00\x032016-09-30T02:01:11\x00TDTG\x00\x00\x00\x15\x00\x00\x032016-09-30T02:01:18\x00TOFN\x00\x00\x00\x1a\x00\x00\x03index-0000003936-tI2q.ts\x00TSSE\x00\x00\x00\x15\x00\x00\x03libavtwitch: 730c86\x00TXXX\x00\x00\x01\x15\x00\x00\x03segmentmetadata\x00{"broadc_s":1,"cmd":"ld_lat_data","ingest_r":2,"ingest_s":3,"stream_offset":15624,"transc_r":1475200871542,"transc_s":1475200878899}\xbd\x00\x00\x00\x01\xce\x8cM\x9d\x10\x8e%\xe9\xfe' </code></pre> <p>It's sort of parseable and contains common ID3 values but does not seem to be full ID3 data. Based on the ID3 spec it should start with a 'ID3' identifier value and other values but it doesn't, and all id3 parsing libraries I tried fail parsing it because of that.</p> <p>It seems timed_id3 in HLS streams is different from normal id3 info for mp3 files.</p>
1
2016-09-30T02:23:17Z
39,814,987
<p>Timed metadata is part of the HLS specification, A quick google search would have provided the answer. <a href="https://developer.apple.com/library/content/documentation/AudioVideo/Conceptual/HTTP_Live_Streaming_Metadata_Spec/Introduction/Introduction.html" rel="nofollow">https://developer.apple.com/library/content/documentation/AudioVideo/Conceptual/HTTP_Live_Streaming_Metadata_Spec/Introduction/Introduction.html</a></p>
1
2016-10-02T07:55:31Z
[ "python", "ffmpeg", "id3", "mpeg2-ts", "id3v2" ]
Sum Series with Functions - Continously adding previous answers?
39,782,752
<p>I'm learning the concepts of functions in Python and could use a little advice. </p> <p>I'm trying to write a program that will use the algebraic function <code>m(i) = (i) / (i + 1)</code> for inputs 1 through 20. So far I've got that to work, but now I want to add all previous outputs together for each new output. It could be I'm just not grasping the mathematical concept of this and that's why I'm not getting it right in my code.</p> <p>Ideally this would be the result table I'm trying to get:</p> <pre><code>i m(i) 1 0.50 2 1.17 ... 19 16.40 20 17.35 </code></pre> <p>Currently what I have is:</p> <pre><code>def equation(i): mi = ((i) / (i + 1)) return mi def main(): for i in range(1,21): print(format(i, '2d')," ",format(equation(i), '.2f')) main() </code></pre> <p>The output I'm seeing in my shell is:</p> <pre><code> 1 0.50 2 0.67 3 0.75 4 0.80 5 0.83 6 0.86 7 0.88 8 0.89 9 0.90 10 0.91 11 0.92 12 0.92 13 0.93 14 0.93 15 0.94 16 0.94 17 0.94 18 0.95 19 0.95 20 0.95 </code></pre> <p>I feel like I'm off to a good start, but how can I add all the m(i) together for each new line? Like in the 'ideal' example I posted, it takes 0.5 + 0.67 giving 1.17 and so on.</p> <p>Thank you in advance!</p>
0
2016-09-30T02:29:37Z
39,782,782
<p>Try this:</p> <pre><code>def equation(i): if i &lt;= 0: return 0 mi = ((i) / (i + 1)) return mi + equation(i - 1) </code></pre>
0
2016-09-30T02:33:42Z
[ "python", "function", "math", "sum", "continuous" ]
Sum Series with Functions - Continously adding previous answers?
39,782,752
<p>I'm learning the concepts of functions in Python and could use a little advice. </p> <p>I'm trying to write a program that will use the algebraic function <code>m(i) = (i) / (i + 1)</code> for inputs 1 through 20. So far I've got that to work, but now I want to add all previous outputs together for each new output. It could be I'm just not grasping the mathematical concept of this and that's why I'm not getting it right in my code.</p> <p>Ideally this would be the result table I'm trying to get:</p> <pre><code>i m(i) 1 0.50 2 1.17 ... 19 16.40 20 17.35 </code></pre> <p>Currently what I have is:</p> <pre><code>def equation(i): mi = ((i) / (i + 1)) return mi def main(): for i in range(1,21): print(format(i, '2d')," ",format(equation(i), '.2f')) main() </code></pre> <p>The output I'm seeing in my shell is:</p> <pre><code> 1 0.50 2 0.67 3 0.75 4 0.80 5 0.83 6 0.86 7 0.88 8 0.89 9 0.90 10 0.91 11 0.92 12 0.92 13 0.93 14 0.93 15 0.94 16 0.94 17 0.94 18 0.95 19 0.95 20 0.95 </code></pre> <p>I feel like I'm off to a good start, but how can I add all the m(i) together for each new line? Like in the 'ideal' example I posted, it takes 0.5 + 0.67 giving 1.17 and so on.</p> <p>Thank you in advance!</p>
0
2016-09-30T02:29:37Z
39,782,803
<p>You just need an accumulator to save the values of equation(i)</p> <p>Here's my solution:</p> <pre><code>def equation(i): mi = ((i) / (i + 1)) return mi acc = 0 for i in range(1,21): acc += equation(i) print(format(i, '2d')," ",format(acc, '.2f')) </code></pre>
0
2016-09-30T02:35:33Z
[ "python", "function", "math", "sum", "continuous" ]
Sum Series with Functions - Continously adding previous answers?
39,782,752
<p>I'm learning the concepts of functions in Python and could use a little advice. </p> <p>I'm trying to write a program that will use the algebraic function <code>m(i) = (i) / (i + 1)</code> for inputs 1 through 20. So far I've got that to work, but now I want to add all previous outputs together for each new output. It could be I'm just not grasping the mathematical concept of this and that's why I'm not getting it right in my code.</p> <p>Ideally this would be the result table I'm trying to get:</p> <pre><code>i m(i) 1 0.50 2 1.17 ... 19 16.40 20 17.35 </code></pre> <p>Currently what I have is:</p> <pre><code>def equation(i): mi = ((i) / (i + 1)) return mi def main(): for i in range(1,21): print(format(i, '2d')," ",format(equation(i), '.2f')) main() </code></pre> <p>The output I'm seeing in my shell is:</p> <pre><code> 1 0.50 2 0.67 3 0.75 4 0.80 5 0.83 6 0.86 7 0.88 8 0.89 9 0.90 10 0.91 11 0.92 12 0.92 13 0.93 14 0.93 15 0.94 16 0.94 17 0.94 18 0.95 19 0.95 20 0.95 </code></pre> <p>I feel like I'm off to a good start, but how can I add all the m(i) together for each new line? Like in the 'ideal' example I posted, it takes 0.5 + 0.67 giving 1.17 and so on.</p> <p>Thank you in advance!</p>
0
2016-09-30T02:29:37Z
39,782,833
<p>You can do something like this. </p> <pre><code>#!/usr/bin/python def equation(i): mi = (float(i) / (i + 1)) return mi def main(): sumOfMi = 0 for i in range(1,21): sumOfMi+= equation(i) print(format(i, '2d')," ",format(sumOfMi, '.2f')) main() </code></pre>
0
2016-09-30T02:40:41Z
[ "python", "function", "math", "sum", "continuous" ]
Sum Series with Functions - Continously adding previous answers?
39,782,752
<p>I'm learning the concepts of functions in Python and could use a little advice. </p> <p>I'm trying to write a program that will use the algebraic function <code>m(i) = (i) / (i + 1)</code> for inputs 1 through 20. So far I've got that to work, but now I want to add all previous outputs together for each new output. It could be I'm just not grasping the mathematical concept of this and that's why I'm not getting it right in my code.</p> <p>Ideally this would be the result table I'm trying to get:</p> <pre><code>i m(i) 1 0.50 2 1.17 ... 19 16.40 20 17.35 </code></pre> <p>Currently what I have is:</p> <pre><code>def equation(i): mi = ((i) / (i + 1)) return mi def main(): for i in range(1,21): print(format(i, '2d')," ",format(equation(i), '.2f')) main() </code></pre> <p>The output I'm seeing in my shell is:</p> <pre><code> 1 0.50 2 0.67 3 0.75 4 0.80 5 0.83 6 0.86 7 0.88 8 0.89 9 0.90 10 0.91 11 0.92 12 0.92 13 0.93 14 0.93 15 0.94 16 0.94 17 0.94 18 0.95 19 0.95 20 0.95 </code></pre> <p>I feel like I'm off to a good start, but how can I add all the m(i) together for each new line? Like in the 'ideal' example I posted, it takes 0.5 + 0.67 giving 1.17 and so on.</p> <p>Thank you in advance!</p>
0
2016-09-30T02:29:37Z
39,782,835
<p>You could do it with a generator: </p> <pre><code>def equation(i): n = 0 tot = 0 while n &lt; i: n += 1 mi = n/(n+n) tot += mi yield n, tot def main(): for i, mi in equation(21): print(format(i, '2d')," ",format(mi, '.2f')) </code></pre>
0
2016-09-30T02:40:53Z
[ "python", "function", "math", "sum", "continuous" ]
Sum Series with Functions - Continously adding previous answers?
39,782,752
<p>I'm learning the concepts of functions in Python and could use a little advice. </p> <p>I'm trying to write a program that will use the algebraic function <code>m(i) = (i) / (i + 1)</code> for inputs 1 through 20. So far I've got that to work, but now I want to add all previous outputs together for each new output. It could be I'm just not grasping the mathematical concept of this and that's why I'm not getting it right in my code.</p> <p>Ideally this would be the result table I'm trying to get:</p> <pre><code>i m(i) 1 0.50 2 1.17 ... 19 16.40 20 17.35 </code></pre> <p>Currently what I have is:</p> <pre><code>def equation(i): mi = ((i) / (i + 1)) return mi def main(): for i in range(1,21): print(format(i, '2d')," ",format(equation(i), '.2f')) main() </code></pre> <p>The output I'm seeing in my shell is:</p> <pre><code> 1 0.50 2 0.67 3 0.75 4 0.80 5 0.83 6 0.86 7 0.88 8 0.89 9 0.90 10 0.91 11 0.92 12 0.92 13 0.93 14 0.93 15 0.94 16 0.94 17 0.94 18 0.95 19 0.95 20 0.95 </code></pre> <p>I feel like I'm off to a good start, but how can I add all the m(i) together for each new line? Like in the 'ideal' example I posted, it takes 0.5 + 0.67 giving 1.17 and so on.</p> <p>Thank you in advance!</p>
0
2016-09-30T02:29:37Z
39,782,862
<pre><code>def function(i): return i/(i+1) e = 0 for i in range(1, 21): print(i, end=' ') e += function(i) print(e) </code></pre> <p>Seems you just need to increment resulting return from function to variable.Good luck!</p>
0
2016-09-30T02:44:24Z
[ "python", "function", "math", "sum", "continuous" ]
Open excel file through Python win32com which having foreign language in a filename
39,782,802
<p>I am trying to open excel file through win32com. But when I run a code with foreign(Korean) language then it gives an error which wans't happened with a english filename.</p> <p>How do I solve this problem?</p> <pre><code>#-*- coding: utf-8 -*- import os import win32com.client xl=win32com.client.Dispatch("Excel.Application") xl.Visible = True xl.Workbooks.Open(os.path.join(os.getcwd(), "Nikkei225_10월.xlsm")) xl.Application.Quit() # Comment this out if your excel script closes del xl </code></pre> <p>Here is an error message:</p> <pre><code>com_error: (-2147352567, '\xbf\xb9\xbf\xdc\xb0\xa1 \xb9\xdf\xbb\xfd\xc7\xdf\xbd\xc0\xb4\xcf\xb4\xd9.', (0, u'Microsoft Office Excel', u"'C:\\Users\\Jongho\\dev_jhk\\VNI Automation Pilot Test\\Nikkei225_10?? xlsm.xlsx'\uc744(\ub97c) \ucc3e\uc744 \uc218 \uc5c6\uc2b5\ub2c8\ub2e4. \ud30c\uc77c \uc774\ub984\uc758 \ucca0\uc790\uc640 \ud30c\uc77c \uc704\uce58\uac00 \uc815\ud655\ud55c\uc9c0 \ud655\uc778\ud558\uc2ed\uc2dc\uc624.\n\n\ucd5c\uadfc\uc5d0 \uc0ac\uc6a9\ud55c \ud30c\uc77c \ubaa9\ub85d\uc5d0 \uc788\ub294 \ud30c\uc77c\uc744 \uc5f4\ub824\uba74 \ud30c\uc77c\uc758 \uc774\ub984\uc774 \ubcc0\uacbd\ub418\uac70\ub098 \ud30c\uc77c\uc774 \uc774\ub3d9 \ub610\ub294 \uc0ad\uc81c\ub418\uc9c0 \uc54a\uc558\ub294\uc9c0 \ud655\uc778\ud558\uc2ed\uc2dc\uc624.", u'C:\\Program Files\\Microsoft Office\\Office12\\1042\\XLMAIN11.CHM', 0, -2146827284), None) </code></pre>
0
2016-09-30T02:35:31Z
39,785,490
<p>It was an encoding problem.</p> <pre><code>#-*- coding: utf-8 -*- import os import win32com.client xl=win32com.client.Dispatch("Excel.Application") xl.Visible = True xl.Workbooks.Open("C:\\Users\\Jongho\\dev_jhk\\VNI Automation Pilot Test\\Nikkei225_10\xbf\xf9.xlsm") xl.Application.Quit() # Comment this out if your excel script closes del xl </code></pre>
0
2016-09-30T06:58:10Z
[ "python", "excel", "win32com" ]
script that able to download zip file from server
39,782,899
<p>Can you please help me to make script in python that do the following:</p> <ol> <li>download zip file http (I already have a code for this one)</li> <li>download zip file in <code>file://&lt;server location&gt;</code>, I have problem with this one. the location of the file is in <code>file://&lt;server location&gt;file.zip</code></li> </ol> <p>can't download the #2 file :(</p> <p>Code below, #1 is working if using HTTP, but when using <code>file:////</code> it's not working. Anybody has idea how to download a zip file from <code>file:////</code>?</p> <pre><code>import urllib2 response = urllib2.urlopen('file:////server/file.zip') print response.info() html = response.read() # do something response.close() # best practice to close the file </code></pre>
-1
2016-09-30T02:48:43Z
39,785,199
<p>urllib2 does not have handlers for the <code>file://</code> protocol; I think it will open local files if there is <em>no</em> protocol given (<code>//server/file.zip</code>), but I've never used that, and haven't tested it. If you have a local file name, you can just use <code>open()</code> and <code>read()</code> rather than urrlib2.</p> <p>Your code will be simpler if you use <code>with closing</code> (from <code>contextlib</code>); opened files are already context managers in Python 2.7 and 3.x, so they're even easier to use.</p>
0
2016-09-30T06:40:32Z
[ "python", "urllib2" ]
Changing Chrome Preferences Through Script
39,782,947
<p>Is it possible to alter your preferences <a href="http://chrome://settings/search#privacy" rel="nofollow">Preferences</a> on your chrome browser through a script? Is this done with selenium? Can anyone help me by writing a python script to change one radio button on the chrome preferences page? Thanks</p>
-1
2016-09-30T02:55:49Z
39,788,284
<p>Here you can find the list of chrome options and capabilities you can pass to the chromedriver in order to modify some preferences.</p> <p><a href="https://sites.google.com/a/chromium.org/chromedriver/capabilities" rel="nofollow">https://sites.google.com/a/chromium.org/chromedriver/capabilities</a></p> <p>Hope it helps!</p>
0
2016-09-30T09:34:56Z
[ "python", "selenium" ]
Append first item into array list when still have space in array list
39,782,951
<p>let's say I need to store 2 elements into a list.</p> <p>I have 5 items: apple, orange, lemon, papaya, banana</p> <p>These items i save in a text file, hence there're 5 lines.</p> <p>I connect the file and start read line by line. Everytime I read a line I append one item in array. Each time the array will fill up by 2 items and when it's full I will empty it and store the next 2 items.</p> <p>What should I do when it reach the last item? I still have one extra place and I plan to store the 1st item again?</p> <p>Example:</p> <pre><code>1st time store apple, orange, 2nd time store lemon, papaya, 3rd time store banana, apple 4th time store orange, lemon </code></pre> <p>loop........</p> <p>My current code is unable do so:</p> <pre><code>def function(): fo = open("1.txt", "r") print "Name of the file: ", fo.name sent_count=0 ele = [] while True: lines = fo.readlines() for line in lines: sent_count+=1 if(sent_count%4!=0): ele.append(lines[sent_count-1]) if(sent_count%4==0): ele.append(lines[sent_count-1]) for i in ele: print i ele = [] print(sent_count) time.sleep(1) </code></pre>
0
2016-09-30T02:55:59Z
39,783,172
<p>Actually you can avoid clearing your <code>ele</code> array. There are some useful built-in modules like <code>collection</code>. It allow you to create your custom array. You can set the <code>maxlen</code> of your array. Moreover you can set left/right append.</p> <pre><code>d = collections.deque([], maxlen=2) </code></pre> <p>means that array <code>d</code> can contain inly two item and if we append one more it will we appended by right side(default). Moreover you don't need(if data is not dynamically changed) to reopen your file. Once you opened it you can repeat its lines with the help of `itertools'. It has loads of nice functions I recommend you to look through these modules. </p> <pre><code>for i in itertools.repeat([1,2,3], 10): print(i) </code></pre> <p>will print iterator <code>[1,2,3]</code> 10 times.</p> <p>So the overall code looks like this, but I believe you can optimize it and write more efficient code.</p> <pre><code>import itertools import collections data = ['apple', 'orange', 'lemon', 'papaya', 'banana'] d = collections.deque(maxlen=2) for i in itertools.repeat(data, 10): for item in i: d.append(item) print(d) </code></pre> <p>try it and see the output. Good luck! By the way just make some changes so that it works for <code>python 2.7</code>. There is almost no difference besides <code>print</code> function. <code>python 2.7</code> also has these modules.</p>
0
2016-09-30T03:25:31Z
[ "python", "arrays", "python-2.7", "loops" ]
Hover tool not working in Bokeh
39,782,955
<p>I have a table that contains the number of times a student accessed an activity.</p> <pre><code> df_act5236920.head() activities studs 0 3.0 student 1 1 4.0 student 10 2 5.0 student 11 3 6.0 student 12 4 2.0 student 13 5 4.0 student 14 6 19.0 student 15 </code></pre> <p>If I try to add the hover tool to the bar chart created by this dataframe through the code below:</p> <pre><code> from bokeh.charts import Bar from bokeh.models import Legend from collections import OrderedDict TOOLS = "pan,wheel_zoom,box_zoom,reset,hover,save" bar = Bar(df_act5236920,values='activities',label='studs',title = "Activity 5236920 performed by students", xlabel="Students",ylabel="Activity",legend=False,tools=TOOLS) hover = bar.select_one(HoverTool) hover.point_policy = "follow_mouse" hover.tooltips = OrderedDict([ ("Student Name", "@studs"), ("Access Count", "@activities"), ]) show(bar) </code></pre> <p>When I hover over the bar chart, it shows the student value but not the activities values, I even tried using "$activities" but the result is still the same.</p> <p><a href="http://i.stack.imgur.com/kne1z.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/kne1z.jpg" alt="enter image description here"></a></p> <p>I tried using ColumnDataSource instead of DataFrame based on other stack overflow questions I read, as is apparent in the code below:</p> <pre><code>source = ColumnDataSource(ColumnDataSource.from_df(df_act5236920)) from collections import OrderedDict TOOLS = "pan,wheel_zoom,box_zoom,reset,hover,save" bar = Bar('studs','activities',source=source, title = "Activity 5236920 performed by students",tools=TOOLS) hover = bar.select_one(HoverTool) hover.point_policy = "follow_mouse" hover.tooltips = OrderedDict([ ("Student Name", "@studs"), ("Access Count", "@activities"), ]) show(bar) </code></pre> <p>It gives me the following error:</p> <pre><code> --------------------------------------------------------------------------- TypeError Traceback (most recent call last) &lt;ipython-input-76-81505464c390&gt; in &lt;module&gt;() 3 # bar = Bar(df_act5236920,values='activities',label='studs',title = "Activity 5236920 performed by students", 4 # xlabel="Students",ylabel="Activity",legend=False,tools=TOOLS) ----&gt; 5 bar = Bar('studs','activities',source=source, title = "Activity 5236920 performed by students",tools=TOOLS) 6 hover = bar.select_one(HoverTool) 7 hover.point_policy = "follow_mouse" C:\Anaconda2\lib\site-packages\bokeh\charts\builders\bar_builder.pyc in Bar(data, label, values, color, stack, group, agg, xscale, yscale, xgrid, ygrid, continuous_range, **kw) 319 kw['y_range'] = y_range 320 --&gt; 321 chart = create_and_build(BarBuilder, data, **kw) 322 323 # hide x labels if there is a single value, implying stacking only C:\Anaconda2\lib\site-packages\bokeh\charts\builder.pyc in create_and_build(builder_class, *data, **kws) 66 # create the new builder 67 builder_kws = {k: v for k, v in kws.items() if k in builder_props} ---&gt; 68 builder = builder_class(*data, **builder_kws) 69 70 # create a chart to return, since there isn't one already C:\Anaconda2\lib\site-packages\bokeh\charts\builder.pyc in __init__(self, *args, **kws) 292 # make sure that the builder dimensions have access to the chart data source 293 for dim in self.dimensions: --&gt; 294 getattr(getattr(self, dim), 'set_data')(data) 295 296 # handle input attrs and ensure attrs have access to data C:\Anaconda2\lib\site-packages\bokeh\charts\properties.pyc in set_data(self, data) 170 data (`ChartDataSource`): the data source associated with the chart 171 """ --&gt; 172 self.selection = data[self.name] 173 self._chart_source = data 174 self._data = data.df TypeError: 'NoneType' object has no attribute '__getitem__' </code></pre> <p>I even tried creating the ColumnDataSource from scratch by passing the columns of the dataframe to it in the form of a list of values, but I still got the same error as the one shown above</p> <pre><code>source = ColumnDataSource(data=dict( studs=students, activities=activity_5236920, )) </code></pre> <p>I'm having the same issue when I try to implement the hovertool on a heatmap as well. Can anyone help in how to fix this?</p>
3
2016-09-30T02:57:10Z
39,793,409
<p>So, after going through a lot of the documentation, I've finally figured out a few things.</p> <p>Firstly, the NoneType error was due to the fact that for a bar chart, you need to pass the dataframe as well as the ColumnDataSource, for the bar-chart to display. So the code needed to be:</p> <pre><code>bar = Bar(df_act5236920,values='activities',label='studs',title = "Activity 5236920 performed by students", xlabel="Students",ylabel="Activity",legend=False,tools=TOOLS,source=source) </code></pre> <p>Notice how the dataframe name and source=source are both mentioned in the Bar() method. For the second issue of the value not being displayed, I used @height which essentially displayed the height of the selected bar, which in this case was the count value.</p> <pre><code>hover.tooltips = OrderedDict([ ("Student Name", "@studs"), ("Access Count", "@height"), ]) </code></pre> <p>For the student name value, @x and @studs both work. But the only thing I still couldn't resolve was that although I have mentioned the ColumnDataSource "source", it didn't really accomplish anything for me because when I try to use @activities in hover.tooltips, it still gives me a response of "???". So, I'm not sure what that is all about. And it is an issue that I'm sturggling with in another Time Series visualisation that I'm trying to build.</p>
0
2016-09-30T14:05:14Z
[ "python", "pandas", "hover", "tooltip", "bokeh" ]
split python list given the index start
39,782,958
<p>I have looked at this:<a href="http://stackoverflow.com/questions/18570740/python-split-a-list-into-sub-lists-based-on-index-ranges">Split list into sublist based on index ranges</a></p> <p>But my problem is slightly different. I have a list</p> <pre><code>List = ['2016-01-01', 'stuff happened', 'details', '2016-01-02', 'more stuff happened', 'details', 'report'] </code></pre> <p>I need to split it up into sublists based on the dates. Basically it's an event log but due to shitty DB design the system concats separate update messages for an event into one big list of strings. I have:</p> <pre><code>Event_indices = [i for i, word in enumerate(List) if re.match(date_regex_return_all = "(\d+\-\d+\-\d+",word)] </code></pre> <p>which for my example will give:</p> <pre><code>[0,3] </code></pre> <p>Now I need split the list into separate lists based on the indexes. So for my example ideally I want to get:</p> <pre><code>[List[0], [List[1], List[2]]], [List[3], [List[4], List[5], List[6]] ] </code></pre> <p>so the format is:</p> <pre><code>[event_date, [list of other text]], [event_date, [list of other text]] </code></pre> <p>There are also edge cases where there is no date string which would be the format of:</p> <pre><code>Special_case = ['blah', 'blah', 'stuff'] Special_case_2 = ['blah', 'blah', '2015-01-01', 'blah', 'blah'] result_special_case = ['', [Special_case[0], Special_case[1],Special_case[2] ]] result_special_case_2 = [ ['', [ Special_case_2[0], Special_case_2[1] ] ], [Special_case_2[2], [ Special_case_2[3],Special_case_2[4] ] ] ] </code></pre>
2
2016-09-30T02:57:32Z
39,783,211
<p>You don't need to perform a two-pass grouping at all, because you can use <a href="https://docs.python.org/3/library/itertools.html#itertools.groupby" rel="nofollow"><code>itertools.groupby</code></a> to both segment by dates and their associated events in a single pass. By avoiding the need to compute indices and then slice a <code>list</code> using them, you could process a generator that provides the values one at a time, avoiding memory issues if your inputs are huge. To demonstrate, I've taken your original <code>List</code> and expanded it a bit to show this handles edge cases correctly:</p> <pre><code>import re from itertools import groupby List = ['undated', 'garbage', 'then', 'twodates', '2015-12-31', '2016-01-01', 'stuff happened', 'details', '2016-01-02', 'more stuff happened', 'details', 'report', '2016-01-03'] datere = re.compile(r"\d+\-\d+\-\d+") # Precompile regex for speed def group_by_date(it): # Make iterator that groups dates with dates and non-dates with dates grouped = groupby(it, key=lambda x: datere.match(x) is not None) for isdate, g in grouped: if not isdate: # We had a leading set of undated events, output as undated yield ['', list(g)] else: # At least one date found; iterate with one loop delay # so final date can have events included (all others have no events) lastdate = next(g) for date in g: yield [lastdate, []] lastdate = date # Final date pulls next group (which must be events or the end of the input) try: # Get next group of events events = list(next(grouped)[1]) except StopIteration: # There were no events for final date yield [lastdate, []] else: # There were events associated with final date yield [lastdate, events] print(list(group_by_date(List))) </code></pre> <p>which outputs (newlines added for readability):</p> <pre><code>[['', ['undated', 'garbage', 'then', 'twodates']], ['2015-12-31', []], ['2016-01-01', ['stuff happened', 'details']], ['2016-01-02', ['more stuff happened', 'details', 'report']], ['2016-01-03', []]] </code></pre>
1
2016-09-30T03:30:04Z
[ "python", "string", "list" ]
split python list given the index start
39,782,958
<p>I have looked at this:<a href="http://stackoverflow.com/questions/18570740/python-split-a-list-into-sub-lists-based-on-index-ranges">Split list into sublist based on index ranges</a></p> <p>But my problem is slightly different. I have a list</p> <pre><code>List = ['2016-01-01', 'stuff happened', 'details', '2016-01-02', 'more stuff happened', 'details', 'report'] </code></pre> <p>I need to split it up into sublists based on the dates. Basically it's an event log but due to shitty DB design the system concats separate update messages for an event into one big list of strings. I have:</p> <pre><code>Event_indices = [i for i, word in enumerate(List) if re.match(date_regex_return_all = "(\d+\-\d+\-\d+",word)] </code></pre> <p>which for my example will give:</p> <pre><code>[0,3] </code></pre> <p>Now I need split the list into separate lists based on the indexes. So for my example ideally I want to get:</p> <pre><code>[List[0], [List[1], List[2]]], [List[3], [List[4], List[5], List[6]] ] </code></pre> <p>so the format is:</p> <pre><code>[event_date, [list of other text]], [event_date, [list of other text]] </code></pre> <p>There are also edge cases where there is no date string which would be the format of:</p> <pre><code>Special_case = ['blah', 'blah', 'stuff'] Special_case_2 = ['blah', 'blah', '2015-01-01', 'blah', 'blah'] result_special_case = ['', [Special_case[0], Special_case[1],Special_case[2] ]] result_special_case_2 = [ ['', [ Special_case_2[0], Special_case_2[1] ] ], [Special_case_2[2], [ Special_case_2[3],Special_case_2[4] ] ] ] </code></pre>
2
2016-09-30T02:57:32Z
39,783,483
<p>Try:</p> <pre><code>def split_by_date(arr, patt='\d+\-\d+\-\d+'): results = [] srch = re.compile(patt) rec = ['', []] for item in arr: if srch.match(item): if rec[0] or rec[1]: results.append(rec) rec = [item, []] else: rec[1].append(item) if rec[0] or rec[1]: results.append(rec) return results </code></pre> <p>Then:</p> <pre><code>normal_case = ['2016-01-01', 'stuff happened', 'details', '2016-01-02', 'more stuff happened', 'details', 'report'] special_case_1 = ['blah', 'blah', 'stuff', '2016-11-11'] special_case_2 = ['blah', 'blah', '2015/01/01', 'blah', 'blah'] print(split_by_date(normal_case)) print(split_by_date(special_case_1)) print(split_by_date(special_case_2, '\d+\/\d+\/\d+')) </code></pre>
1
2016-09-30T04:02:16Z
[ "python", "string", "list" ]
TensorFlow issue with feed_dict not being noticed when using batching
39,783,039
<p>I have been trying to do the mnist tutorial with png files, and have gotten most things to the point where they make sense.</p> <p>The gist of the code is <a href="https://gist.github.com/ThaHypnotoad/4438a6658c89bb803bd74080e78cf170" rel="nofollow">here</a> however I'm going to walk through what it does and where the issue is happening.</p> <p>I have a function that generates filenames that I can give to the slice_input_producer.</p> <pre><code>def gen_file_names_and_labels(rootDir): """goes through the directory structure and extracts images and labels from each image.""" file_names = [] labels = [] for file_name in glob.glob(rootDir+'/*/*'): file_type_removed = file_name.split('.')[0] split_by_dir = file_type_removed.split('/') file_names.append(file_name) labels.append(int(split_by_dir[2])) #getting the folder it's in, turning into an int, and using as label return file_names, labels </code></pre> <p>This behaves as expected.</p> <p>In the body I run this function for training and testing, and turning them into tensors, passing those tensors into a slice_input_producer</p> <pre><code>sess = tf.InteractiveSession() #THERE A PIPELINE FOR BOTH TESTING AND TRAINING. THEY COME IN PAIRS image_list_train, label_list_train = gen_file_names_and_labels('mnist_png/training') image_list_test, label_list_test = gen_file_names_and_labels('mnist_png/testing') images_train = tf.convert_to_tensor(image_list_train,dtype=tf.string) images_test = tf.convert_to_tensor(image_list_test,dtype=tf.string) #remember that these aren't the actual images, just file_names labels_train = tf.convert_to_tensor(label_list_train,dtype=tf.int32) labels_test = tf.convert_to_tensor(label_list_test,dtype=tf.int32) input_queue_train = tf.train.slice_input_producer([images_train ,labels_train] , shuffle=True) input_queue_test = tf.train.slice_input_producer([images_train ,labels_train] , shuffle=True) </code></pre> <p>this part also works correctly.</p> <p>This is where things get strange.</p> <pre><code>asdf = tf.placeholder(tf.int32) input_queue = tf.cond( asdf&gt;0, lambda: input_queue_train, lambda: input_queue_test) # input_queue = input_queue_test image, label = read_images_from_disk(input_queue) image_reshaped = tf.reshape( image, [28,28,1]) image_batch, label_batch = tf.train.batch([image_reshaped,label],batch_size=50) </code></pre> <p>The variable asdf was renamed in anger as it was the bearer of bad news. See the plan here was to use different queues for training and testing. I planned to feed_dict a single int that would work as an ad-hoc boolean for switching between the two.</p> <pre><code>coord = tf.train.Coordinator() threads = tf.train.start_queue_runners(coord=coord) sess.run(tf.initialize_all_variables()) print(label_batch.eval(feed_dict={asdf:0,keep_prob:1.0})) for i in range(500): # batch = mnist.train.next_batch(50) if i%20 ==0: train_accuracy = accuracy.eval(feed_dict={keep_prob:1.0,asdf:0}) print("step %d, training accuracy %g"%(i, train_accuracy)) train_step.run(feed_dict={keep_prob:0.9,asdf:0}) </code></pre> <p>When running it though, I get the error: "You must feed a value for placeholder tensor 'Placeholder' with dtype int32" which is strange because <em>I am feeding it.</em></p> <p>using the "print(foo.eval(feed_dict={asdf:0,keep_prob:1.0)) I was able to notice some interesting phenomena. It seems that the switching works fine when I evaluate the individual variables declared "image, label" that come out of "read_images_from_disk(input_queue)"</p> <p>However if I try to evaluate the batching that comes right after, I get the aforementioned error.</p> <p>What am I doing wrong with batching to make this happen? Is there a better way to do this switching between testing and training sets? What is the meaning of life the universe and everything? I'm counting on you StackOverflow. You're my only hope.</p>
0
2016-09-30T03:08:33Z
39,793,174
<p>In answer to your question, "Is there a better way to do this switching between testing and training sets?", yes there is. <code>tf.cond()</code> evaluates both functions at each step (see <a href="https://www.tensorflow.org/versions/r0.10/api_docs/python/control_flow_ops.html#cond" rel="nofollow">here</a>) and therefore unnecessarily accesses both queues. <a href="http://stackoverflow.com/questions/39617686/tensorflow-data-input-toggle-train-validation/39620485#39620485">This SO discussion</a> and the associated links provide a couple of better alternatives:</p> <ul> <li>use <code>tf.placeholder_with_default()</code> for your test data</li> <li>use <code>make_template</code></li> </ul>
1
2016-09-30T13:52:23Z
[ "python", "tensorflow", "batching" ]
wxPython: Redirecting events on other widgets (TextCtrl)
39,783,070
<p>The case study doesn't seem too hard to explain, but I guess TextCtrl in wxPython aren't often used in this way. So here it is: I have a simple window with two TextCtrls. One is an input widget (the user is supposed to enter commands there), the second is an output widget (the system displays the result of the commands). The output field is a read-only TextCtrl, only the system can write in it.</p> <p>So far so good. Now, I would like to intercept events in the output widget: If users type in this output field (a read-only widget), they should be redirected to the input field and the text they have begun typing should appear there. The first part isn't complicated: I intercept the EVT_KEY_DOWN on the output widget and can do something like self.input.SetFocus(). However, the key that has been pressed by the user is lost. If he/she began to type something, she has to start over again. This is supposed to be a shortcut feature (no matter in what field the user type, it should be written in the input widget).</p> <p>A short note on why I do this, since it can still quite stupid: Sighted users don't often fool around with read-only widgets; they see them and leave them alone. This application is mostly designed for users with screen readers, who have to move around the output field. The cursor is therefore often there, and a key press doesn't have any effect (since it's a read-only widget). It would be great if, on typing in the output widget, the user was redirected to the input field, with the text he was typing already in this widget.</p> <pre><code>import wx class MyFrame(wx.Frame): def __init__(self, parent): wx.Frame.__init__(self, parent) self.panel = MyPanel(self) self.Show() self.Maximize() class MyPanel(wx.Panel): def __init__(self, parent): wx.Panel.__init__(self, parent) sizer = wx.BoxSizer(wx.VERTICAL) self.SetSizer(sizer) # Input field self.input = wx.TextCtrl(self, -1, "", size=(125, -5), style=wx.TE_PROCESS_ENTER) # Ouput self.output = wx.TextCtrl(self, -1, "", size=(600, 400), style=wx.TE_MULTILINE|wx.TE_READONLY) # Add the output fields in the sizer sizer.Add(self.input) sizer.Add(self.output, proportion=8) # Event handler self.output.Bind(wx.EVT_KEY_DOWN, self.OnKeyDown) def OnKeyDown(self, e): """A key is pressed in the output widget.""" modifiers = e.GetModifiers() key = e.GetUnicodeKey() if not key: key = e.GetKeyCode() print "From there, we should redirect to the input" self.input.SetFocus() # Let's run that app = wx.App() MyFrame(None) app.MainLoop() </code></pre>
0
2016-09-30T03:12:16Z
39,796,778
<p>Give <code>self.input.EmulateKeyPress(e)</code> a try. If you're on Windows it should work fine. On other platforms it is not perfect, but basically works there too.</p> <p>Other options would be to use <code>wx.UiActionSimulator</code>, or simply to append the new character to the input textctrl in your code.</p>
1
2016-09-30T17:17:27Z
[ "python", "events", "widget", "wxpython", "textctrl" ]
python manipulations on lists
39,783,098
<p>I have 2 lists</p> <pre><code>l1 = ('A','B','C') l2 = ('X','Y','Z') </code></pre> <p>I want to create a list based on these 2 </p> <p>result = ('A is same as X', 'B is same as Y', 'C is same as Z')</p> <p>when I concatenate , I do not get the result I expect How can I combine the lists ? Thanks PMV</p>
0
2016-09-30T03:16:19Z
39,783,155
<p>You can <code>zip</code> the lists together which will combine the two lists into a list of tuples and then iterate over those tuples.</p> <pre><code>z = zip(l1,l2) #[(A,X), (B,Y), (C,Z)] result = ["{0} is the same as {1}".format(t[0], t[1]) for t in z] # ['A is the same as X', 'B is the same as Y', 'C is the same as Z'] </code></pre>
0
2016-09-30T03:23:40Z
[ "python", "string", "list", "data-manipulation" ]
python manipulations on lists
39,783,098
<p>I have 2 lists</p> <pre><code>l1 = ('A','B','C') l2 = ('X','Y','Z') </code></pre> <p>I want to create a list based on these 2 </p> <p>result = ('A is same as X', 'B is same as Y', 'C is same as Z')</p> <p>when I concatenate , I do not get the result I expect How can I combine the lists ? Thanks PMV</p>
0
2016-09-30T03:16:19Z
39,783,169
<p>the zip() function can help you here.</p> <pre><code>result = [] for a, b in zip(l1, l2): result.append("{0} is same as {1}".format(a, b)) </code></pre>
2
2016-09-30T03:25:20Z
[ "python", "string", "list", "data-manipulation" ]
python manipulations on lists
39,783,098
<p>I have 2 lists</p> <pre><code>l1 = ('A','B','C') l2 = ('X','Y','Z') </code></pre> <p>I want to create a list based on these 2 </p> <p>result = ('A is same as X', 'B is same as Y', 'C is same as Z')</p> <p>when I concatenate , I do not get the result I expect How can I combine the lists ? Thanks PMV</p>
0
2016-09-30T03:16:19Z
39,783,279
<p>Just a more direct way...</p> <pre><code>&gt;&gt;&gt; map('{} is same as {}'.format, l1, l2) ['A is same as X', 'B is same as Y', 'C is same as Z'] </code></pre>
0
2016-09-30T03:37:44Z
[ "python", "string", "list", "data-manipulation" ]
Why is plt.errorbox giving me continuous graph when I just want data in dots?
39,783,277
<p>I'm using errorbox in matplotlib to plot a graph in which </p> <pre><code>x1 = (0, 100, 60, 20, 80, 40) y1 = (0.0, 0.058823529411764705, 0.058823529411764705, 0.0, 0.0, 0.0) plt.figure() plt.errorbar(x1, y1) plt.title("Errors") plt.show() </code></pre> <p>This would give me continuous lines instead of separate 6 data points? How can I fix it to just yield 6 data points? I tried using 'o' as the 3rd argument for pet.errorbar(x1,y1, 'o').</p>
0
2016-09-30T03:37:38Z
39,783,562
<p>You may use the following properties:</p> <pre><code>plt.errorbar(x1, y1,ls='None', marker = 'o') </code></pre>
2
2016-09-30T04:12:56Z
[ "python", "matplotlib", "errorbar" ]
Within Dango, how do I add a new value to request.POST data before saving?
39,783,299
<p>I'm trying to allow the user to either manually enter a text field if they have the license info, or let it auto generate (based on form info) if its original content.</p> <p>I'm stuck because from my tests (using print command) the form is correctly updating with the information given in the form if LicenseTag field is left blank. The issue is that the updated information is not being saved in the database. After research this seems to be an issue of immutability, which is why I added request.POST.copy() and tested the commented out section defining mutability=True.</p> <p>Here's my views.py</p> <pre><code>def STLupload(request): if request.method == 'POST': form = NewUpload(request.POST, request.FILES) data = request.POST.copy() if form.is_valid(): #Dis gona need alot of work firstname = request.user.first_name lastname = request.user.last_name displayname = request.user.display_name email = request.user.email if (firstname or lastname == "None"): if displayname == "None": liscname = email else: liscname = '%s %s' % (firstname, lastname) else: liscname = displayname filetitle = request.POST.get( 'Title' , '') lisc = '%s %s' % (filetitle, liscname) if data['LicenseTag'] == "": ''' mutable = request.POST._mutable request.POST._mutable = True request.POST['LicenseTag'] = lisc request.POST._mutable = mutable ''' data['LicenseTag'] = lisc print (request.POST.get( 'LicenseTag' , '')) print ("blank") else: print (form) #Save current username comment = form.save(commit=False) comment.user = request.user comment.save() #Flash success message messages.add_message(request, messages.SUCCESS, "File uploaded successful") # Redirect to the document list after POST return HttpResponseRedirect(reverse_lazy('STLup')) else: form = NewUpload() # A empty, unbound form </code></pre> <p>Can anyone help me figure out how to save the generated information into my database?</p> <p><strong>Edit #1</strong></p> <p>Models.py</p> <pre><code> from django.db import models import os #import django.db.models.deletion from django.db import models from django.core.exceptions import ValidationError from django.core.files.storage import FileSystemStorage from django.utils.translation import ugettext_lazy as _ from django.utils import timezone from django.conf import settings from django.contrib.auth.models import User # Create your models here. def user_directory_path(instance, filename): # file will be uploaded to MEDIA_ROOT/user_&lt;id&gt;/&lt;filename&gt; return os.path.join('uploads', str(instance.Title), filename) def validate_file_extension(value): ext = os.path.splitext(value.name)[1] valid_extensions = ['.stl','.STL'] if not ext in valid_extensions: raise ValidationError(u'Please upload a .stl file type only') def validate_img_extension(value): ext = os.path.splitext(value.name)[1] valid_extensions = ['.jpg','.png','.JPG'] if not ext in valid_extensions: raise ValidationError(u'Please upload a .jpg or .png only') class UploadedFiles(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, blank=True, null=True) STL = models.FileField(_('STL Upload'), upload_to=user_directory_path, validators=[validate_file_extension]) Photo = models.ImageField(_('Photo'), upload_to=user_directory_path, validators=[validate_img_extension]) Title = models.CharField(_('Title of object'), max_length=40, blank=False, null=True, unique=False) Category = models.CharField(_('Category'), max_length=40, blank=False, null=True, unique=False) SubCategory = models.CharField(_('SubCategory'), max_length=40, blank=True, null=True, unique=False) SubSubCategory = models.CharField(_('*SubSubCategory (optional)'), max_length=40, blank=True, null=True, unique=False) FileType = models.BooleanField(_('Local?'), default=0, unique=False) Description = models.TextField(_('File Description'), max_length=200, blank=True, null=True, unique=False) LicenseTag = models.CharField(_('*License (optional, leave blank for original content)'), max_length=200, blank=True, null=True, unique=False) Xdim_mm = models.IntegerField(_('X dimension (mm)'), default=0) Ydim_mm = models.IntegerField(_('Y dimension (mm)'), default=0) Zdim_mm = models.IntegerField(_('Z dimension (mm)'), default=0) pub_date = models.DateTimeField(_('date_joined'), default=timezone.now) </code></pre> <p>Here is my forms.py.</p> <pre><code>from django import forms from django.core.validators import MinLengthValidator from .models import UploadedFiles class NewUpload(forms.ModelForm): class Meta: model = UploadedFiles fields = ('Title', 'STL','Photo','Description', 'Category', 'SubCategory', 'SubSubCategory', 'LicenseTag') </code></pre>
2
2016-09-30T03:39:21Z
39,783,826
<p>As I see it the best way is to override the save method in your model.</p> <pre><code>class UploadedFiles(models.Model): def save(self, *args, **kwargs): if not self.LicenseTag: if self.user: liscname = self.user.get_full_name() or self.user.email self.LicenseTag = "{0} {1}".format(liscname, self.Title) super(UploadFiles,self).save(*args,**kwargs) </code></pre> <p>Then the same thing works in your admin without having to do a lot of hard work. I have taken the liberty to optimize how the license tag is derived. </p> <p>Now your view becomes a whole lot simpler.</p> <pre><code>def STLupload(request): if request.method == 'POST': form = NewUpload(request.POST, request.FILES) if form.is_valid(): lisc = '%s %s' % (filetitle, liscname) #Save current username comment = form.save(commit=False) comment.user = request.user comment.save() #Flash success message messages.add_message(request, messages.SUCCESS, "File uploaded successful") # Redirect to the document list after POST return HttpResponseRedirect(reverse_lazy('STLup')) else: form = NewUpload() # A empty, unbound form </code></pre>
0
2016-09-30T04:43:18Z
[ "python", "django", "request", "immutability" ]
Iterating over numbers within XPath
39,783,329
<p>I am using the Selenium webdriver in Python to find elements on a web page to process, in the way shown below: </p> <pre><code>driver.find_element_by_xpath('//div[@class="gsc-cursor-page" and text()="1"]') </code></pre> <p>Ideally, I would like to go through all the texts within that div, <code>text()="1"</code>, <code>text()="2"</code>, ... <code>text()="10"</code>, etc. But since the whole xpath is a string, somehow I cannot find a way to write an iteration <code>for i in range(10)</code> without breaking the inner structure. </p> <p>The closest I could get is </p> <pre><code>mypath = '//div[@class="gsc-cursor-page" and text()="' + str(i) + '"]' next = driver.find_element_by_xpath(path) </code></pre> <p>But this also leads to error. Any suggestions on how to solve this issue?</p>
2
2016-09-30T03:41:44Z
39,783,380
<p>This XPath,</p> <pre><code>//div[@class="gsc-cursor-page" and number() &gt;= 1 and number() &lt;= 10] </code></pre> <p>will select all of the <code>div</code> elements of the specified <code>@class</code> with values in the range of <code>1..10</code>.</p> <hr> <p><strong>Specific Python/Selenium code to address OP's comment</strong></p> <pre><code>xp = "//div[@class="gsc-cursor-page" and number() &gt;= 1 and number() &lt;= 10]" for div in driver.find_elements_by_xpath(xp): div.click() </code></pre>
2
2016-09-30T03:48:59Z
[ "python", "html", "xml", "selenium", "xpath" ]
Iterating over numbers within XPath
39,783,329
<p>I am using the Selenium webdriver in Python to find elements on a web page to process, in the way shown below: </p> <pre><code>driver.find_element_by_xpath('//div[@class="gsc-cursor-page" and text()="1"]') </code></pre> <p>Ideally, I would like to go through all the texts within that div, <code>text()="1"</code>, <code>text()="2"</code>, ... <code>text()="10"</code>, etc. But since the whole xpath is a string, somehow I cannot find a way to write an iteration <code>for i in range(10)</code> without breaking the inner structure. </p> <p>The closest I could get is </p> <pre><code>mypath = '//div[@class="gsc-cursor-page" and text()="' + str(i) + '"]' next = driver.find_element_by_xpath(path) </code></pre> <p>But this also leads to error. Any suggestions on how to solve this issue?</p>
2
2016-09-30T03:41:44Z
39,800,840
<p>somehow I am able to put in the variable for iteration through "position" instead of usnig the internal text of a div. thanks for all of your helps and tips!</p> <pre><code>driver.find_element_by_xpath('//div[@class="gsc-cursor"]/div[position()='+str(i)+']') </code></pre>
-1
2016-09-30T22:16:08Z
[ "python", "html", "xml", "selenium", "xpath" ]
Can a MagicMock object be iterated over?
39,783,460
<p>What I would like to do is this...</p> <pre><code>x = MagicMock() x.iter_values = [1, 2, 3] for i in x: i.method() </code></pre> <p>I am trying to write a unit test for this function but I am unsure about how to go about mocking all of the methods called without calling some external resource...</p> <pre><code>def wiktionary_lookup(self): """Looks up the word in wiktionary with urllib2, only to be used for inputting data""" wiktionary_page = urllib2.urlopen( "http://%s.wiktionary.org/wiki/%s" % (self.language.wiktionary_prefix, self.name)) wiktionary_page = fromstring(wiktionary_page.read()) definitions = wiktionary_page.xpath("//h3/following-sibling::ol/li") print definitions.text_content() defs_list = [] for i in definitions: print i i = i.text_content() i = i.split('\n') for j in i: # Takes out an annoying "[quotations]" in the end of the string, sometimes. j = re.sub(ur'\u2003\[quotations \u25bc\]', '', j) if len(j) &gt; 0: defs_list.append(j) return defs_list </code></pre> <p>EDIT:</p> <p>I may be misusing mocks, I am not sure. I am trying to unit-test this <code>wiktionary_lookup</code> method without calling external services...so I mock urlopen..I mock fromstring.xpath() but as far as I can see I need to also iterate through the return value of <code>xpath()</code> and call a method "<code>text_contents()</code>" so that is what I am trying to do here.</p> <p>If I have totally misunderstood how to unittest this method then please tell me where I have gone wrong... </p> <p>EDIT (adding current unittest code)</p> <pre><code>@patch("lang_api.models.urllib2.urlopen") @patch("lang_api.models.fromstring") def test_wiktionary_lookup_2(self, fromstring, urlopen): """Looking up a real word in wiktionary, should return a list""" fromstring().xpath.return_value = MagicMock( content=["test", "test"], return_value='test\ntest2') # A real word should give an output of definitions output = self.things.model['word'].wiktionary_lookup() self.assertEqual(len(output), 2) </code></pre>
1
2016-09-30T03:59:22Z
39,811,615
<p>What you actually want to do is not return a <code>Mock</code> with a <code>return_value=[]</code>. You actually want to return a <code>list</code> of <code>Mock</code> objects. Here is a snippet of your test code with the correct components and a small example to show how to test one of the iterations in your loop: </p> <pre><code>@patch('d.fromstring') @patch('d.urlopen') def test_wiktionary(self, urlopen_mock, fromstring_mock): urlopen_mock.return_value = Mock() urlopen_mock.return_value.read.return_value = "some_string_of_stuff" mocked_xpath_results = [Mock()] fromstring_mock.return_value.xpath.return_value = mocked_xpath_results mocked_xpath_results[0].text_content.return_value = "some string" </code></pre> <p>So, to dissect the above code to explain what was done to correct your problem: </p> <p>The first thing to help us with testing the code in the for loop is to create a list of mock objects per: </p> <pre><code>mocked_xpath_results = [Mock()] </code></pre> <p>Then, as you can see from </p> <pre><code>fromstring_mock.return_value.xpath.return_value = mocked_xpath_results </code></pre> <p>We are setting the <code>return_value</code> of the <code>xpath</code> call to our list of mocks per <code>mocked_xpath_results</code>. </p> <p>As an example of how to do things inside your list, I added how to mock within the loop, which is shown with:</p> <pre><code>mocked_xpath_results[0].text_content.return_value = "some string" </code></pre> <p>In unittests (this might be a matter of opinion) I like to be explicit, so I'm accessing the list item explicitly and determining what should happen. </p> <p>Hope this helps. </p>
1
2016-10-01T21:27:16Z
[ "python", "django", "unit-testing", "mocking" ]
Can substitute default softmax with self-implemented one in TensorFlow?
39,783,470
<p>I just wonder could the softmax provided by the TensorFlow package, namely, tensorflow.nn.softmax, be substituted by one implemented by myself?</p> <p>I run the original tutorial file mnist_softmax.py with cross_entropy calculation:</p> <pre><code>cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(tf.nn.softmax(y)), reduction_indices=[1])) </code></pre> <p>it will give a cross validate accuracy rate 0.9195, it quite makes sense.</p> <p>However, I do some changes, like below:</p> <pre><code># Create the model x = tf.placeholder(tf.float32, [None, 784]) W = tf.Variable(tf.zeros([784, 10])) b = tf.Variable(tf.zeros([10])) y = tf.matmul(x, W) + b # The below two lines are added by me, an equivalent way to calculate softmax, at least in my opinion y1 = tf.reduce_sum(y) y2 = tf.scalar_mul(1.0 / y1, y) # Define loss and optimizer y_ = tf.placeholder(tf.float32, [None, 10]) ... cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y2), reduction_indices=[1])) train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy) </code></pre> <p>However, the cross validate accuracy rate is only 0.098.</p> <p>Anyone has any insight into this problem? Thanks a lot.</p>
0
2016-09-30T04:00:39Z
39,783,838
<p>Your <code>y2</code> as a matter of fact is not equivalent to computing softmax. Softmax is</p> <pre><code>softmax(y) = e^y / S </code></pre> <p>Where <code>S</code> is a normalizing factor (the sum of <code>e^y</code> across all <code>y</code>s). Also, when you compute the normalizing factor, you only need to reduce the sum over the classes, not over the samples. More proper way would be</p> <pre><code>y1 = tf.reduce_sum(tf.exp(y), reduction_indices=[1]) y2 = tf.scalar_mul(1.0 / y1, tf.exp(y)) </code></pre>
1
2016-09-30T04:45:10Z
[ "python", "tensorflow" ]
colorbar units don't appear in figure (matplotlib)
39,783,537
<p>Im trying to do the following figure, but the units below the colorbar do not appear. The units only appear when I make the width and the height of the figure extremely large.</p> <p>This is the code I use for inserting a customized colorbar:</p> <pre><code>from mpl_toolkits.axes_grid.axes_grid import AxesGrid from mpl_toolkits.axes_grid.anchored_artists import AnchoredText def add_at(ax, t, loc=1): fp = dict(size=16, weight='bold') _at = AnchoredText(t, loc=loc, prop=fp) ax.add_artist(_at) return _at </code></pre> <p>now I make the figure</p> <pre><code>fig = plt.figure(figsize = (12, 5)) axs1 = plt.subplot2grid((2,2), (0,0)) im = m.contourf(x, y, var,levels=np.arange(vmin, vmax, delta)) </code></pre> <p>and finally I add the colorbar </p> <pre><code>cax = fig.add_axes([0.42, 0.05, 0.25, 0.03]) cbar = fig.colorbar(im, cax, orientation='horizontal') cbar.ax.tick_params(labelsize=12) cbar.set_label('units', size=16, weight='bold') </code></pre> <p>finally I save the figure</p> <pre><code>fig.savefig('name.png', dpi=300) </code></pre> <p>But I see this the figure with the colorbar but the units dont appear for lack of space. I tried adjusting the width and height of the figure, but it doesnt work unless I do a huge figure but then the spacing between sublpots is wrong.</p> <p>this is the figure:</p> <p><img src="http://i.stack.imgur.com/4JEQu.png" alt="link"></p>
0
2016-09-30T04:10:01Z
39,784,063
<p><code>set_xticklabels</code> might help. Check this: <a href="http://matplotlib.org/examples/pylab_examples/colorbar_tick_labelling_demo.html" rel="nofollow">http://matplotlib.org/examples/pylab_examples/colorbar_tick_labelling_demo.html</a></p>
0
2016-09-30T05:07:42Z
[ "python", "matplotlib" ]
NetworkX D3 Force Layout Plugin for mpld3
39,783,547
<p>I'm in the process of creating a mpld3 plugin for converting a NetworkX Graph to a Force Layout. I'm having some trouble understanding how the zoom on the axes works in mpld3 and how I can get it to translate to the force layout graph.</p> <pre><code>import matplotlib import matplotlib.pyplot as plt import numpy as np import mpld3 from mpld3 import plugins, utils from networkx.readwrite.json_graph import node_link_data class NetworkXD3ForceLayoutView(plugins.PluginBase): """A simple plugin showing how multiple axes can be linked""" JAVASCRIPT = """ mpld3.register_plugin("networkxd3forcelayoutview", NetworkXD3ForceLayoutViewPlugin); NetworkXD3ForceLayoutViewPlugin.prototype = Object.create(mpld3.Plugin.prototype); NetworkXD3ForceLayoutViewPlugin.prototype.constructor = NetworkXD3ForceLayoutViewPlugin; NetworkXD3ForceLayoutViewPlugin.prototype.requiredProps = ["graph", "charge", "linkDistance", "gravity"]; function NetworkXD3ForceLayoutViewPlugin(fig, props){ mpld3.Plugin.call(this, fig, props); }; var color = d3.scale.category20(); NetworkXD3ForceLayoutViewPlugin.prototype.draw = function(){ var zoom = d3.behavior.zoom(); var height = this.fig.height var width = this.fig.width var graph = this.props.graph var gravity = this.props.gravity.toFixed() var charge = this.props.charge.toFixed() var linkDistance = this.props.linkDistance.toFixed() console.log(graph) var ax = this.fig.axes[0] // axis required for zoomx and zoomy presumably? var g = d3.select('.mpld3-axes').append('g') // This is right? var vis = g.append('svg') .attr('width', this.width) .attr('height', this.height); force = d3.layout.force() .gravity(gravity) .charge(charge) .linkDistance(linkDistance) .nodes(graph.nodes) .links(graph.links) .size([width, height]) .start() var link = vis.selectAll("line.link") .data(graph.links) .enter().append("svg:line") .attr("class", "link") .attr("stroke", "black") .style("stroke-width", function(d) { return Math.sqrt(d.value); }) .attr("x1", function(d) { return d.source.x; }) .attr("y1", function(d) { return d.source.y; }) .attr("x2", function(d) { return d.target.x; }) .attr("y2", function(d) { return d.target.y; }); var node = vis.selectAll("circle.node") .data(graph.nodes) .enter().append("svg:circle") .attr("class", "node") .attr("cx", function(d) { return d.x; }) .attr("cy", function(d) { return d.y; }) .attr("r", 5) .style("fill", function(d) { return d.color; }) .call(force.drag); node.append("svg:title") .text(function(d) { return d.name; }); vis.style("opacity", 1e-6) .transition() .duration(1000) .style("opacity", 1); force.on("tick", function() { link.attr("x1", function(d) { return d.source.x; }) .attr("y1", function(d) { return d.source.y; }) .attr("x2", function(d) { return d.target.x; }) .attr("y2", function(d) { return d.target.y; }); node.attr("cx", function(d) { return d.x; }) .attr("cy", function(d) { return d.y; }); }); zoom.on("zoom", function() { g.attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")"); }) g.call(zoom) }; """ def __init__(self, G, gravity=0.5, link_distance=20, charge=-10): self.dict_ = {"type": "networkxd3forcelayoutview", "graph": node_link_data(G), "gravity": gravity, "charge": charge, "linkDistance": link_distance} fig, ax = plt.subplots(1, 1) # scatter periods and amplitudes np.random.seed(0) import networkx as nx G=nx.Graph() G.add_node(1, color='red') G.add_edge(1,2) plugins.connect(fig, NetworkXD3ForceLayoutView(G)) mpld3.display() </code></pre> <p>The above is a minimum working example that I was able to run in a notebook. I'd added a zoom callback to the group element that contains the graph currently, so the graph will zoom if the mouse if over a node. How do I get it to work when I use the zoom on the custom toolbar. Is this the right approach to creating a force layout plugin? I've also posted <a href="https://github.com/mpld3/mpld3/issues/387" rel="nofollow">here</a> but it might be that SO is a better place for this question.</p>
0
2016-09-30T04:11:07Z
39,822,216
<p>I've posted a working example <a href="http://blog.kdheepak.com/mpld3-networkx-d3js-force-layout.html" rel="nofollow">here</a> for anyone searching for something similar.</p>
0
2016-10-02T22:07:18Z
[ "javascript", "python", "d3.js", "mpld3" ]
Passing pandas DataFrame by reference
39,783,570
<p>My question is regarding immutability of pandas DataFrame when it is passed by reference. Consider the following code:</p> <pre><code>import pandas as pd def foo(df1, df2): df1['B'] = 1 df1 = df1.join(df2['C'], how='inner') return() def main(argv = None): # Create DataFrames. df1 = pd.DataFrame(range(0,10,2), columns=['A']) df2 = pd.DataFrame(range(1,11,2), columns=['C']) foo(df1, df2) # Pass df1 and df2 by reference. print df1 return(0) if __name__ == '__main__': status = main() sys.exit(status) </code></pre> <p>The output is</p> <pre><code> A B 0 0 1 1 2 1 2 4 1 3 6 1 4 8 1 </code></pre> <p>and not </p> <pre><code> A B C 0 0 1 1 1 2 1 3 2 4 1 5 3 6 1 7 4 8 1 9 </code></pre> <p>In fact, if foo is defined as</p> <pre><code>def foo(df1, df2): df1 = df1.join(df2['C'], how='inner') df1['B'] = 1 return() </code></pre> <p>(i.e. the "join" statement before the other statement) then the output is simply</p> <pre><code> A 0 0 1 2 2 4 3 6 4 8 </code></pre> <p>I'm intrigued as to why this is the case. Any insights would be appreciated.</p>
1
2016-09-30T04:13:49Z
39,783,626
<p>The issue is because of this line:</p> <pre><code>df1 = df1.join(df2['C'], how='inner') </code></pre> <p><code>df1.join(df2['C'], how='inner')</code> returns a new dataframe. After this line, <code>df1</code> no longer refers to the same dataframe as the argument, but a new one, because it's been reassigned to the new result. The first dataframe continues to exist, unmodified. This isn't really a pandas issue, just the general way python, and most other languages, work.</p> <p>Some pandas functions have an <code>inplace</code> argument, which would do what you want, however the join operation doesn't. If you need to modify a dataframe, you'll have to return this new one instead and reassign it outside the function.</p>
2
2016-09-30T04:20:10Z
[ "python", "pandas", "dataframe", "pass-by-reference", "immutability" ]
Passing pandas DataFrame by reference
39,783,570
<p>My question is regarding immutability of pandas DataFrame when it is passed by reference. Consider the following code:</p> <pre><code>import pandas as pd def foo(df1, df2): df1['B'] = 1 df1 = df1.join(df2['C'], how='inner') return() def main(argv = None): # Create DataFrames. df1 = pd.DataFrame(range(0,10,2), columns=['A']) df2 = pd.DataFrame(range(1,11,2), columns=['C']) foo(df1, df2) # Pass df1 and df2 by reference. print df1 return(0) if __name__ == '__main__': status = main() sys.exit(status) </code></pre> <p>The output is</p> <pre><code> A B 0 0 1 1 2 1 2 4 1 3 6 1 4 8 1 </code></pre> <p>and not </p> <pre><code> A B C 0 0 1 1 1 2 1 3 2 4 1 5 3 6 1 7 4 8 1 9 </code></pre> <p>In fact, if foo is defined as</p> <pre><code>def foo(df1, df2): df1 = df1.join(df2['C'], how='inner') df1['B'] = 1 return() </code></pre> <p>(i.e. the "join" statement before the other statement) then the output is simply</p> <pre><code> A 0 0 1 2 2 4 3 6 4 8 </code></pre> <p>I'm intrigued as to why this is the case. Any insights would be appreciated.</p>
1
2016-09-30T04:13:49Z
39,783,805
<p>Python doesn't have pass by value vs. pass by reference - there are just <a href="https://docs.python.org/2/reference/executionmodel.html#naming-and-binding" rel="nofollow">bindings from names to objects</a>. </p> <p>If you change your function to</p> <pre><code>def foo(df1, df2): res = df1.join(df2['C'], how='inner') res['B'] = 1 return res </code></pre> <p>Then <code>df1</code>, <code>df2</code>, in the function, are bound to the objects you sent. The result of the <code>join</code>, which is a new object in this case, is bound to the name <code>res</code>. You can manipulate it, and return it, without affecting any of the other objects or bindings. </p> <p>In your calling code, you could just write</p> <pre><code>print foo(df1, df2) </code></pre>
3
2016-09-30T04:40:36Z
[ "python", "pandas", "dataframe", "pass-by-reference", "immutability" ]
Count sub_lists length in python3
39,783,675
<p>My python is 3 ver. I have a list, which contains sub lists, like:</p> <pre><code>L=[[1,2], [3,4], [5,6,7]] </code></pre> <p>I want to calculate length of all sub_list and write down them to a dictionary, like this:</p> <pre><code>D={2:2,3:1} </code></pre> <p>that is, we have 2 lists which have length 2, and 1 list which have the length 3.</p> <p>It can be done by for-loop + check D[key] is exist or not.</p> <p>May be there is some 'pythonic way?'</p>
0
2016-09-30T04:25:32Z
39,783,782
<p>Use <code>defaultdict</code> where you store the length of the list as the key, and just increment each value by 1 every time to get a matching list length:</p> <pre><code>from collections import defaultdict d = defaultdict(int) L = [[1,2], [3,4], [5,6,7]] for li in L: d[len(li)] += 1 print(d) # defaultdict(&lt;class 'int'&gt;, {2: 2, 3: 1}) </code></pre> <p>Or use <code>Counter</code> from <code>collections</code> as well:</p> <pre><code>from collections import Counter c = Counter(len(li) for li in L) print(c) # Counter({2: 2, 3: 1}) </code></pre>
2
2016-09-30T04:36:38Z
[ "python", "python-3.x" ]
Count sub_lists length in python3
39,783,675
<p>My python is 3 ver. I have a list, which contains sub lists, like:</p> <pre><code>L=[[1,2], [3,4], [5,6,7]] </code></pre> <p>I want to calculate length of all sub_list and write down them to a dictionary, like this:</p> <pre><code>D={2:2,3:1} </code></pre> <p>that is, we have 2 lists which have length 2, and 1 list which have the length 3.</p> <p>It can be done by for-loop + check D[key] is exist or not.</p> <p>May be there is some 'pythonic way?'</p>
0
2016-09-30T04:25:32Z
39,783,784
<p>You need to iterate over the list, and check that the length exists as key or not. If it exists, increment the value by 1, else add the value as 1. Below is the sample code.</p> <pre><code>&gt;&gt;&gt; L = [[1,2], [3,4], [5,6,7]] &gt;&gt;&gt; my_len_dict = {} &gt;&gt;&gt; for item in L: ... item_length = len(item) ... if item_length in my_len_dict: ... my_len_dict[item_length] += 1 ... else: ... my_len_dict[item_length] = 1 ... &gt;&gt;&gt; my_len_dict {2: 2, 3: 1} </code></pre>
0
2016-09-30T04:36:53Z
[ "python", "python-3.x" ]
Why is my python app continues to get a 500 Internal Server Error?
39,783,687
<p>I'm trying to get my app.py to link with MySQL database but I keep getting the following errors shown below. The link to my repository is here: <a href="https://github.com/trhubwork/python-mysql-proj.git" rel="nofollow">https://github.com/trhubwork/python-mysql-proj.git</a></p> <p>I'm running python 3.5.1</p> <p>Console Errors:</p> <blockquote> <p>jquery-1.11.2.js:9659 POST [runningonlocalhost]/signUp 500 (INTERNAL SERVER ERROR)send @ jquery-1.11.2.js:9659ajax @ jquery-1.11.2.js:9210(anonymous function) @ signUp.js:4dispatch @ jquery-1.11.2.js:4665elemData.handle @ jquery-1.11.2.js:4333 signUp.js:12 Object {readyState: 4, responseText: "↵", status: 500, statusText: "INTERNAL SERVER ERROR"}</p> </blockquote> <p>Gitbash terminal Errors:</p> <blockquote> <ul> <li>Running on [localhost]:5002/ (Press CTRL+C to quit) 127.0.0.1 - - [29/Sep/2016 22:06:17] "GET / HTTP/1.1" 200 - 127.0.0.1 - - [29/Sep/2016 22:06:20] "GET /showSignUp HTTP/1.1" 200 - [2016-09-29 22:06:22,142] ERROR in app: Exception on /signUp [POST] Traceback (most recent call last): File "C:\Users\TR\AppData\Local\Programs\Python\Python35-32\lib\site-packages\flask\app.py", line 1988, in wsgi_app response = self.full_dispatch_request() File "C:\Users\TR\AppData\Local\Programs\Python\Python35-32\lib\site-packages\flask\app.py", line 1641, in full_dispatch_request rv = self.handle_user_exception(e) File "C:\Users\TR\AppData\Local\Programs\Python\Python35-32\lib\site-packages\flask\app.py", line 1544, in handle_user_exception reraise(exc_type, exc_value, tb) File "C:\Users\TR\AppData\Local\Programs\Python\Python35-32\lib\site-packages\flask_compat.py", line 33, in reraise raise value File "C:\Users\TR\AppData\Local\Programs\Python\Python35-32\lib\site-packages\flask\app.py", line 1639, in full_dispatch_request rv = self.dispatch_request() File "C:\Users\TR\AppData\Local\Programs\Python\Python35-32\lib\site-packages\flask\app.py", line 1625, in dispatch_request return self.view_functionsrule.endpoint File "app.py", line 54, in signUp cursor.close() UnboundLocalError: local variable 'cursor' referenced before assignment 127.0.0.1 - - [29/Sep/2016 22:06:22] "POST /signUp HTTP/1.1" 500 - [2016-09-29 22:09:03,808] ERROR in app: Exception on /signUp [POST] Traceback (most recent call last): File "C:\Users\TR\AppData\Local\Programs\Python\Python35-32\lib\site-packages\flask\app.py", line 1988, in wsgi_app response = self.full_dispatch_request() File "C:\Users\TR\AppData\Local\Programs\Python\Python35-32\lib\site-packages\flask\app.py", line 1641, in full_dispatch_request rv = self.handle_user_exception(e) File "C:\Users\TR\AppData\Local\Programs\Python\Python35-32\lib\site-packages\flask\app.py", line 1544, in handle_user_exception reraise(exc_type, exc_value, tb) File "C:\Users\TR\AppData\Local\Programs\Python\Python35-32\lib\site-packages\flask_compat.py", line 33, in reraise raise value File "C:\Users\TR\AppData\Local\Programs\Python\Python35-32\lib\site-packages\flask\app.py", line 1639, in full_dispatch_request rv = self.dispatch_request() File "C:\Users\TR\AppData\Local\Programs\Python\Python35-32\lib\site-packages\flask\app.py", line 1625, in dispatch_request return self.view_functionsrule.endpoint File "app.py", line 54, in signUp cursor.close() UnboundLocalError: local variable 'cursor' referenced before assignment 127.0.0.1 - - [29/Sep/2016 22:09:03] "POST /signUp HTTP/1.1" 500 -</li> </ul> </blockquote> <p>This is my app.py</p> <pre><code>from flask import Flask, render_template, json, request from flaskext.mysql import MySQL from werkzeug import generate_password_hash, check_password_hash mysql = MySQL() app = Flask(__name__) # MySQL configurations app.config['MYSQL_DATABASE_USER'] = 'jay' app.config['MYSQL_DATABASE_PASSWORD'] = 'jay' app.config['MYSQL_DATABASE_DB'] = 'BucketList' app.config['MYSQL_DATABASE_HOST'] = 'localhost' mysql.init_app(app) @app.route('/') def main(): return render_template('index.html') @app.route('/showSignUp') def showSignUp(): return render_template('signup.html') @app.route('/signUp',methods=['POST','GET']) def signUp(): try: _name = request.form['inputName'] _email = request.form['inputEmail'] _password = request.form['inputPassword'] # validate the received values if _name and _email and _password: # All Good, let's call MySQL conn = mysql.connect() cursor = conn.cursor() _hashed_password = generate_password_hash(_password) cursor.callproc('sp_createUser',(_name,_email,_hashed_password)) data = cursor.fetchall() if len(data) is 0: conn.commit() return json.dumps({'message':'User created successfully !'}) else: return json.dumps({'error':str(data[0])}) else: return json.dumps({'html':'&lt;span&gt;Enter the required fields&lt;/span&gt;'}) except Exception as e: return json.dumps({'error':str(e)}) finally: cursor.close() conn.close() if __name__ == "__main__": app.run(port=5002) enter code here </code></pre> <p>Signup.html</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;title&gt;Python Flask Bucket List App&lt;/title&gt; &lt;link href="http://getbootstrap.com/dist/css/bootstrap.min.css" rel="stylesheet"&gt; &lt;link href="http://getbootstrap.com/examples/jumbotron-narrow/jumbotron-narrow.css" rel="stylesheet"&gt; &lt;link href="../static/css/signup.css" rel="stylesheet"&gt; &lt;script src="../static/js/jquery-1.11.2.js"&gt;&lt;/script&gt; &lt;script src="../static/js/signUp.js"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;div class="container"&gt; &lt;div class="header"&gt; &lt;nav&gt; &lt;ul class="nav nav-pills pull-right"&gt; &lt;li role="presentation" &gt;&lt;a href="showHome"&gt;Home&lt;/a&gt;&lt;/li&gt; &lt;li role="presentation"&gt;&lt;a href="#"&gt;Sign In&lt;/a&gt;&lt;/li&gt; &lt;li role="presentation" class="active"&gt;&lt;a href="#"&gt;Sign Up&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/nav&gt; &lt;h3 class="text-muted"&gt;Python Flask App&lt;/h3&gt; &lt;/div&gt; &lt;div class="jumbotron"&gt; &lt;h1&gt;Bucket List App&lt;/h1&gt; &lt;form class="form-signin"&gt; &lt;label for="inputName" class="sr-only"&gt;Name&lt;/label&gt; &lt;input type="name" name="inputName" id="inputName" class="form-control" placeholder="Name" required autofocus&gt; &lt;label for="inputEmail" class="sr-only"&gt;Email address&lt;/label&gt; &lt;input type="email" name="inputEmail" id="inputEmail" class="form-control" placeholder="Email address" required autofocus&gt; &lt;label for="inputPassword" class="sr-only"&gt;Password&lt;/label&gt; &lt;input type="password" name="inputPassword" id="inputPassword" class="form-control" placeholder="Password" required&gt; &lt;button id="btnSignUp" class="btn btn-lg btn-primary btn-block" type="button"&gt;Sign up&lt;/button&gt; &lt;/form&gt; &lt;/div&gt; &lt;footer class="footer"&gt; &lt;p&gt;&amp;copy; Company 2015&lt;/p&gt; &lt;/footer&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>signUp.js</p> <pre><code>$(function(){ $('#btnSignUp').click(function(){ $.ajax({ url: '/signUp', data: $('form').serialize(), type: 'POST', success: function(response){ console.log(response); }, error: function(error){ console.log(error); } }); }); }); </code></pre>
0
2016-09-30T04:26:40Z
39,787,818
<p>@epascarello is right, if your code doesn't enter that <code>if</code> statement, then you'll never even create the cursor. I think the <code>try</code> and <code>finally</code> blocks are a good idea; just move your cursor up like this:</p> <pre><code>try: conn = mysql.connect() cursor = conn.cursor() _name = request.form['inputName'] _email = request.form['inputEmail'] _password = request.form['inputPassword'] # ... # contents of the if and else statements here # ... except Exception as e: return json.dumps({'error':str(e)}) finally: cursor.close() conn.close() </code></pre>
0
2016-09-30T09:10:12Z
[ "jquery", "python", "python-3.x", "flask" ]
What does a number mean before a for-loop
39,783,916
<p>I'm new to Python. Would greatly appreciate if you could explain how this line works. What does it mean to have a number before a for-loop?</p> <pre><code>adjacency_matrix = [[0 for i in range(max_index + 1)] for j in range(max_index + 1)] </code></pre> <p>I know that </p> <pre><code>max_index = 4 adjacency_matrix = [[0 for i in range(max_index + 1)] for j in range(max_index + 1)] &gt;&gt;&gt;[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]] </code></pre> <p>But I don't understand how it works. </p> <p>Thanks</p>
1
2016-09-30T04:52:44Z
39,783,983
<p>It is a <a href="https://docs.python.org/2/tutorial/datastructures.html#list-comprehensions" rel="nofollow">list comprehension</a>. You can rewrite that as follows:</p> <pre><code>&gt;&gt;&gt; adjacency_matrix = [] &gt;&gt;&gt; for j in range(max_index + 1): ... inner_list = [] ... for i in range(max_index + 1): ... inner_list.append(0) ... adjacency_matrix.append(inner_list) </code></pre>
3
2016-09-30T04:59:59Z
[ "python", "list-comprehension" ]
What does a number mean before a for-loop
39,783,916
<p>I'm new to Python. Would greatly appreciate if you could explain how this line works. What does it mean to have a number before a for-loop?</p> <pre><code>adjacency_matrix = [[0 for i in range(max_index + 1)] for j in range(max_index + 1)] </code></pre> <p>I know that </p> <pre><code>max_index = 4 adjacency_matrix = [[0 for i in range(max_index + 1)] for j in range(max_index + 1)] &gt;&gt;&gt;[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]] </code></pre> <p>But I don't understand how it works. </p> <p>Thanks</p>
1
2016-09-30T04:52:44Z
39,784,081
<p>The <code>0</code> is the value which the list comprehension is adding to the array (list) - same way each list of zeros is getting nested in the parent list. Try changing it to a different integer, float, string, boolean, etc...</p> <pre><code>&gt;&gt;&gt; max_index = 4 &gt;&gt;&gt; adjacency_matrix = adjacency_matrix = [[True for i in range(max_index + 1)] for j in range(max_index + 1)] &gt;&gt;&gt; adjacency_matrix [[True, True, True, True, True], [True, True, True, True, True], [True, True, True, True, True], [True, True, True, True, True], [True, True, True, True, True]] </code></pre> <p>Otherwise, see @ozgur's answer for a translation of the list comprehension into articulated for-loops and a link to the PyDoc for list comps. </p> <p>Essentially, tho, what you are invoking is: </p> <pre><code>[ ADD_THE_FOLLOWING_LISTS: [ADD_THIS_VALUE_TO_EACH_INNER_LIST = 0, True, etc... `for` each_integer `in` the `range`_of (zero through four - not including five)] = [value, value, value, value, value] ...............................`for` each_number `in` the `range`_of (zero through four - not including five)] ] = a (4 + 1) x (4 + 1), or 5x5 grid of values [ [value, value, value, value, value], [value, value, value, value, value], [value, value, value, value, value], [value, value, value, value, value], [value, value, value, value, value] ] </code></pre>
0
2016-09-30T05:10:17Z
[ "python", "list-comprehension" ]
What does a number mean before a for-loop
39,783,916
<p>I'm new to Python. Would greatly appreciate if you could explain how this line works. What does it mean to have a number before a for-loop?</p> <pre><code>adjacency_matrix = [[0 for i in range(max_index + 1)] for j in range(max_index + 1)] </code></pre> <p>I know that </p> <pre><code>max_index = 4 adjacency_matrix = [[0 for i in range(max_index + 1)] for j in range(max_index + 1)] &gt;&gt;&gt;[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]] </code></pre> <p>But I don't understand how it works. </p> <p>Thanks</p>
1
2016-09-30T04:52:44Z
39,784,288
<p>If we use variable in list comprehension to populate a list, the resultant list takes the value of the variable whenever condition met. Since we are using '0' means list get populated by the value '0' whenever condition met.</p>
1
2016-09-30T05:29:04Z
[ "python", "list-comprehension" ]
python-Cannot call a function in script but can in the interactive mode
39,784,042
<p>It's a simple task about kNN, and I'm a newbee of pyhton.</p> <pre><code># coding=utf-8 from numpy import * import operator def createDataSet(): group = array([[112, 110], [128, 162], [83, 206], [142, 267], [188, 184], [218, 268], [234, 108], [256, 146], [ 333, 177], [350, 86], [364, 237], [378, 117], [409, 147], [485, 130], [326, 344], [387, 326], [378, 435], [434, 375]]) labels = [1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3] return group, labels def classify0(inX, dataSet, labels, k): dataSetSize = dataSet.shape[0] tempSet = array(tile(inX, (dataSetSize, 1))) diffMat = tempSet - dataSet sqDiffMat = diffMat**2 sqDistances = sqDiffMat.sum(axis=1) distances = sqDistances**0.5 sortedDistIndices = distances.argsort() classCount = {} for i in range(k): voteLabel = labels[sortedDistIndices[i]] classCount[voteLabel] = classCount.get(voteLabel, 0) + 1 sortedClassCount = sorted(classCount.iteritems(), key=operator.itemgetter(1), reverse=True) return sortedClassCount[0][0] # TRY1 # def with_intput(): # sample = array(raw_input('Enter you data:')) # group, labels = createDataSet() # sampleClass = classify0(sample, group, labels, 3) # print sampleClass # with_intput() # TRY1 # TRY2 # sample = array(raw_input('Enter your sample data:')) # group, labels = createDataSet() # sampleClass = classify0(sample, group, labels, 3) # print sampleClass # TRY2 </code></pre> <p>There is something really strange. I created a function name <strong>classify0()</strong>, but if i call it while writing the codes(uncomment the #TRY1),or use it to make assingment(if uncomment the #TRT2), it will return error when I run this file.</p> <p>Appears likes:</p> <pre><code>TypeError: ufunc 'subtract' did not contain a loop with signature matching types dtype('S11') dtype('S11') dtype('S11') </code></pre> <p>Here is the traceback of TRY1:</p> <pre><code>Traceback (most recent call last): File "C:\Users\zhongzheng\Desktop\ML_Code\temp2.py", line 39, in &lt;module&gt; with_intput() File "C:\Users\zhongzheng\Desktop\ML_Code\temp2.py", line 36, in with_intput sampleClass = classify0(sample, group, labels, 3) File "C:\Users\zhongzheng\Desktop\ML_Code\temp2.py", line 17, in classify0 diffMat = tempSet - dataSet TypeError: ufunc 'subtract' did not contain a loop with signature matching types dtype('S11') dtype('S11') dtype('S11') </code></pre> <p>And the traceback of TRY2:</p> <pre><code>Traceback (most recent call last): File "C:\Users\zhongzheng\Desktop\ML_Code\temp2.py", line 46, in &lt;module&gt; sampleClass = classify0(sample, group, labels, 3) File "C:\Users\zhongzheng\Desktop\ML_Code\temp2.py", line 17, in classify0 diffMat = tempSet - dataSet TypeError: ufunc 'subtract' did not contain a loop with signature matching types dtype('S11') dtype('S11') dtype('S11') </code></pre> <p>But if I save the file without uncommenting either TRT1 or TRY2, save and run the file with only two functions in it, then enter these commands line by line in interactive mode in cmd or ipython:</p> <pre><code>&gt;&gt;&gt;group,labels = createDataSet() &gt;&gt;&gt;sampleClass = classify0(array([111,111]), group, labels, 3) &gt;&gt;&gt;print sampleClass </code></pre> <p>It will work just fine.</p> <p>Cannot figure out why.</p> <p><strong>One more question</strong>, why my sublime3(subliemlinter, pep8linter installed) keeps warnning <code>from numpy import *</code> or <code>import numpy</code> or <code>import numpy as np</code> is wrong.</p> <p>Thanks for your patience.</p>
0
2016-09-30T05:05:30Z
39,785,782
<p>Your raw_input is not taken what you expect as input for the classify0 function.</p> <pre><code>sample = array(raw_input('Enter you data:')) </code></pre> <p>This would give something like ["111 111"]</p> <pre><code>sample = [int(x) for x in raw_input().split()] </code></pre> <p>This would give [111,111]</p> <p>You could also change the delimiter to split on, i.e. use a , if input is comma separated</p>
0
2016-09-30T07:15:23Z
[ "python", "numpy" ]
Indentation error in python and index out of range error
39,784,088
<p>I am getting an indentation error. Can anyone help me to fix it and also getting <code>tuple index out of range error</code> too</p> <p>here is my code</p> <pre><code>def POST(self): form = web.input(name="a", newname="s", number="d") conn = MySQLdb.connect(host= "localhost", user="root", passwd="", db="testdb") x = conn.cursor() x.execute("SELECT * FROM details WHERE name = '%s'" % (form.name)) conn.commit() items = x.fetchall() for row in items: print row[0], row[1],row[2] print("&lt;table border='1'&gt;") print("&lt;tr&gt;") print("&lt;th&gt;name&lt;/th&gt;") print("&lt;th&gt;address&lt;/th&gt;") print("&lt;th&gt;number&lt;/th&gt;") print("&lt;/tr&gt;") print("&lt;tr&gt;") print("&lt;td&gt;{0}&lt;/td&gt;".format(row[0])) print("&lt;td&gt;{1}&lt;/td&gt;".format(row[1])) print("&lt;td&gt;{2}&lt;/td&gt;".format(row[2])) print("&lt;/tr&gt;") print("&lt;/table&gt;") conn.rollback() conn.close() #return render.index(items) if __name__ == "__main__": app.run() </code></pre> <p>am getting error in these lines</p> <pre><code> print("&lt;/tr&gt;") print("&lt;/table&gt;") </code></pre>
0
2016-09-30T05:11:09Z
39,784,178
<p>This is a very basic error.If you are using sublime text.Please select all the rows. In the beginning of each line of def POST, there will be two patterns. One is '_____' and '.......' .The pattern should be similar for whole 'def POST(self):' Please make sure this and error will get removed.</p> <p>Copy and paste this code:</p> <pre><code> def POST(self): form = web.input(name="a", newname="s", number="d") conn = MySQLdb.connect(host= "localhost", user="root", passwd="", db="testdb") x = conn.cursor() x.execute("SELECT * FROM details WHERE name = '%s'" % (form.name)) conn.commit() items = x.fetchall() for row in items: print row[0], row[1],row[2] print("&lt;table border='1'&gt;") print("&lt;tr&gt;") print("&lt;th&gt;name&lt;/th&gt;") print("&lt;th&gt;address&lt;/th&gt;") print("&lt;th&gt;number&lt;/th&gt;") print("&lt;tr&gt;") print("&lt;td&gt;{0}&lt;/td&gt;".format(row[0])) print("&lt;td&gt;{1}&lt;/td&gt;".format(row[1])) print("&lt;td&gt;{2}&lt;/td&gt;".format(row[2])) print("&lt;/tr&gt;") print("&lt;/table&gt;") conn.rollback() conn.close() #return render.index(items) if __name__ == "__main__": app.run() </code></pre> <p>Thanks.</p>
1
2016-09-30T05:19:20Z
[ "python", "python-2.7" ]
Remove all the parentheses and replace all spaces by underscores?
39,784,099
<p>Here is what I did:</p> <pre><code>import re def demicrosoft (fn): fn = re.sub('[()]', '', fn) for ch in [' ']: fn = fn.replace(ch,"_"+ch) return fn print(demicrosoft('a bad file name (really)')) </code></pre> <p><br></p> <pre><code>&gt;&gt;&gt; (executing lines 1 to 12 of "&lt;tmp 2&gt;") a_ bad_ file_ name_ really </code></pre> <p>There are spaces followed with the underscores. How can I fix it? </p>
2
2016-09-30T05:12:16Z
39,784,158
<p>You can just chain a number of <code>replace</code>s for this:</p> <pre><code>a = 'a bad file name (really)' &gt;&gt;&gt; a.replace('(', '').replace(')', '').replace(' ', '_') 'a_bad_file_name_really' </code></pre>
2
2016-09-30T05:17:35Z
[ "python", "string", "replace" ]
Remove all the parentheses and replace all spaces by underscores?
39,784,099
<p>Here is what I did:</p> <pre><code>import re def demicrosoft (fn): fn = re.sub('[()]', '', fn) for ch in [' ']: fn = fn.replace(ch,"_"+ch) return fn print(demicrosoft('a bad file name (really)')) </code></pre> <p><br></p> <pre><code>&gt;&gt;&gt; (executing lines 1 to 12 of "&lt;tmp 2&gt;") a_ bad_ file_ name_ really </code></pre> <p>There are spaces followed with the underscores. How can I fix it? </p>
2
2016-09-30T05:12:16Z
39,784,183
<p>remove <strong>ch</strong> from <strong>"_"+ch</strong> in replace call as follows</p> <pre><code>import re def demicrosoft (fn): fn = re.sub('[()]', '', fn) for ch in [' ']: fn = fn.replace(ch,"_") return fn </code></pre>
1
2016-09-30T05:19:33Z
[ "python", "string", "replace" ]
Remove all the parentheses and replace all spaces by underscores?
39,784,099
<p>Here is what I did:</p> <pre><code>import re def demicrosoft (fn): fn = re.sub('[()]', '', fn) for ch in [' ']: fn = fn.replace(ch,"_"+ch) return fn print(demicrosoft('a bad file name (really)')) </code></pre> <p><br></p> <pre><code>&gt;&gt;&gt; (executing lines 1 to 12 of "&lt;tmp 2&gt;") a_ bad_ file_ name_ really </code></pre> <p>There are spaces followed with the underscores. How can I fix it? </p>
2
2016-09-30T05:12:16Z
39,784,260
<p>You can do this with <code>str.translate()</code>:</p> <pre><code>&gt;&gt;&gt; table = str.maketrans({'(':None, ')':None, ' ':'_'}) &gt;&gt;&gt; 'a bad file name (really)'.translate(table) 'a_bad_file_name_really' </code></pre>
2
2016-09-30T05:26:57Z
[ "python", "string", "replace" ]
How to add external arguments in python script?
39,784,136
<p>I want the user to provide some external arguments while calling a python script from command line, what changes I suppose to make inside my python script to add this functionality?</p>
0
2016-09-30T05:15:24Z
39,784,510
<p>I think this is what you are looking for</p> <p>pass arguments in command line.</p> <pre><code>$ python test.py arg1 arg2 arg3 </code></pre> <p>access it using sys.argv which gives list of arguments that you entered above</p> <pre><code>import sys print 'Number of arguments:', len(sys.argv), 'arguments.' print 'Argument List:', str(sys.argv) </code></pre>
0
2016-09-30T05:47:03Z
[ "python", "command-line-interface" ]
Google Cloud Storage Python list_blob() not printing object list
39,784,244
<p>I am Python and Google Cloud Storage newbie. I am writing a python script to get a file list from Google Cloud Storage bucket using Google Cloud Python Client Library and list_blobs() function from Bucket class is not working as I expected.</p> <p><a href="https://googlecloudplatform.github.io/google-cloud-python/stable/storage-buckets.html" rel="nofollow">https://googlecloudplatform.github.io/google-cloud-python/stable/storage-buckets.html</a></p> <p>Here is my python code:</p> <pre><code>from google.cloud import storage from google.cloud.storage import Blob client = storage.Client.from_service_account_json(service_account_json_key_path, project_id) bucket = client.get_bucket(bucket_id) print(bucket.list_blobs()) </code></pre> <p>If I understood the documentation correctly, print(bucket.list_blobs()) should print something like this: ['testfile.txt', 'testfile2.txt'].</p> <p>However, my script printed this: "google.cloud.storage.bucket._BlobIterator object at 0x7fdfdbcac590"</p> <p>delete_blob() documentation has example code same as mine. <a href="https://googlecloudplatform.github.io/google-cloud-python/stable/storage-buckets.html" rel="nofollow">https://googlecloudplatform.github.io/google-cloud-python/stable/storage-buckets.html</a></p> <p>I am not sure what I am doing wrong here. Any pointers/examples/answers will be greatly appreciated. Thanks!</p>
0
2016-09-30T05:25:11Z
39,784,381
<p>What do you see if you:</p> <pre><code>for blob in bucket.list_blobs(): print(blob) print(blob.name) </code></pre>
0
2016-09-30T05:36:59Z
[ "python", "google-app-engine", "google-cloud-storage", "google-cloud-platform", "google-cloud-python" ]
Google Cloud Storage Python list_blob() not printing object list
39,784,244
<p>I am Python and Google Cloud Storage newbie. I am writing a python script to get a file list from Google Cloud Storage bucket using Google Cloud Python Client Library and list_blobs() function from Bucket class is not working as I expected.</p> <p><a href="https://googlecloudplatform.github.io/google-cloud-python/stable/storage-buckets.html" rel="nofollow">https://googlecloudplatform.github.io/google-cloud-python/stable/storage-buckets.html</a></p> <p>Here is my python code:</p> <pre><code>from google.cloud import storage from google.cloud.storage import Blob client = storage.Client.from_service_account_json(service_account_json_key_path, project_id) bucket = client.get_bucket(bucket_id) print(bucket.list_blobs()) </code></pre> <p>If I understood the documentation correctly, print(bucket.list_blobs()) should print something like this: ['testfile.txt', 'testfile2.txt'].</p> <p>However, my script printed this: "google.cloud.storage.bucket._BlobIterator object at 0x7fdfdbcac590"</p> <p>delete_blob() documentation has example code same as mine. <a href="https://googlecloudplatform.github.io/google-cloud-python/stable/storage-buckets.html" rel="nofollow">https://googlecloudplatform.github.io/google-cloud-python/stable/storage-buckets.html</a></p> <p>I am not sure what I am doing wrong here. Any pointers/examples/answers will be greatly appreciated. Thanks!</p>
0
2016-09-30T05:25:11Z
39,793,896
<p>On <a href="https://webcache.googleusercontent.com/search?q=cache:9FyUQhlI9z8J:https://github.com/GoogleCloudPlatform/python-docs-samples/blob/master/storage/cloud-client/manage_blobs.py%20&amp;cd=3&amp;hl=en&amp;ct=clnk&amp;gl=be" rel="nofollow">this</a> page you can find some example functions. An example list function:</p> <pre><code>def list_blobs(bucket_name): """Lists all the blobs in the bucket.""" storage_client = storage.Client() bucket = storage_client.get_bucket(bucket_name) blobs = bucket.list_blobs() for blob in blobs: print(blob.name) </code></pre> <p>It contains a lot of other examples as well which you might find useful!</p>
1
2016-09-30T14:29:07Z
[ "python", "google-app-engine", "google-cloud-storage", "google-cloud-platform", "google-cloud-python" ]
Gaussian Function in Python 2.7
39,784,326
<p>I need help making a program that calculates the Gaussian function <code>f(x)=1/(sqrt(2*pi)s)*exp[-.5*((x-m)/s)**2]</code> when <code>m=0</code>, <code>s=2</code>, and <code>x=1</code>.</p> <p>Would it be just:</p> <pre><code>def Gaussian(m,s,x): return 1/(sqrt(2*pi)s)*exp[-.5*((x-m)/s)**2] print Gaussian(0,2,1) </code></pre>
-1
2016-09-30T05:31:39Z
39,784,383
<p>I think you are missing <code>from math import sqrt</code>, <code>from math import exp</code> and <code>from math import pi</code> unless you didn't show it in your code.</p>
0
2016-09-30T05:37:07Z
[ "python", "python-2.7" ]
When I will Rerun the file it will get error like following
39,784,388
<p>IndexError: list index out of range.</p> <p>my code is :</p> <pre><code>from openpyxl import load_workbook from common.log import logging class TestData: def get_data(self): wb = load_workbook(filename="demo.xlsx") ws = wb.active ws['A2'] = "ammy" ws['A3'] = "raju" ws['B2'] = 50 ws['B3'] = 60 ws['A4'] = "Total2" ws['B4'] = ("=SUM(B2:B3)") wb.save('demo.xlsx') if __name__=='__main__': print "start" obj = TestData() obj.get_data() print "end" </code></pre>
-1
2016-09-30T05:37:35Z
39,784,613
<p>You need to be more specific, Try adding a try, except block in the get_data method and print the stack trace. </p> <pre><code>import traceback # for exception tracing class TestData: def get_data(self): try: wb = load_workbook(filename="demo.xlsx") ws = wb.active ws['A2'] = "ammy" ws['A3'] = "raju" ws['B2'] = 50 ws['B3'] = 60 ws['A4'] = "Total2" ws['B4'] = ("=SUM(B2:B3)") wb.save('demo.xlsx') excepct: traceback.format_exc() </code></pre> <p>I suspect that when you try to access demo.xlsx via ws['XX'] it is causing the error</p>
-1
2016-09-30T05:55:00Z
[ "python", "openpyxl" ]
When I will Rerun the file it will get error like following
39,784,388
<p>IndexError: list index out of range.</p> <p>my code is :</p> <pre><code>from openpyxl import load_workbook from common.log import logging class TestData: def get_data(self): wb = load_workbook(filename="demo.xlsx") ws = wb.active ws['A2'] = "ammy" ws['A3'] = "raju" ws['B2'] = 50 ws['B3'] = 60 ws['A4'] = "Total2" ws['B4'] = ("=SUM(B2:B3)") wb.save('demo.xlsx') if __name__=='__main__': print "start" obj = TestData() obj.get_data() print "end" </code></pre>
-1
2016-09-30T05:37:35Z
39,789,815
<pre><code>start Traceback (most recent call last): File "/home/amol.pawar/Globeflexresearch/gri/gri-be/scripts/xlsxdata.py", line 41, in &lt;module&gt; obj.get_data() File "/home/amol.pawar/Globeflexresearch/gri/gri-be/scripts/xlsxdata.py", line 23, in get_data wb = load_workbook(filename="demo.xlsx") File "/usr/local/lib/python2.7/dist-packages/openpyxl/reader/excel.py", line 201, in load_workbook apply_stylesheet(archive, wb) # bind styles to workbook File "/usr/local/lib/python2.7/dist-packages/openpyxl/styles/stylesheet.py", line 164, in apply_stylesheet stylesheet = Stylesheet.from_tree(node) File "/usr/local/lib/python2.7/dist-packages/openpyxl/styles/stylesheet.py", line 99, in from_tree return super(Stylesheet, cls).from_tree(node) File "/usr/local/lib/python2.7/dist-packages/openpyxl/descriptors/serialisable.py", line 89, in from_tree return cls(**attrib) File "/usr/local/lib/python2.7/dist-packages/openpyxl/styles/stylesheet.py", line 90, in __init__ self.named_styles = self._merge_named_styles() File "/usr/local/lib/python2.7/dist-packages/openpyxl/styles/stylesheet.py", line 110, in _merge_named_styles xf = self.cellStyleXfs[style.xfId] File "/usr/local/lib/python2.7/dist-packages/openpyxl/styles/cell_style.py", line 182, in __getitem__ return self.xf[idx] IndexError: list index out of range </code></pre>
0
2016-09-30T10:51:26Z
[ "python", "openpyxl" ]
python simple basic program on geeksforgeeks
39,784,402
<p>Can anyone help me with the solution of this ?</p> <p>Given a number N, print all the composite numbers less than or equal to N. The number should be printed in ascending order.</p> <p>Input: The first line contain an Integer T denoting the number of test cases . Then T test cases follow. Each test case consist of an single integer N.</p> <p>Output: Print all the composite Number form 0 to N.</p> <p>Constraints:</p> <pre><code>1 ≤ T ≤ 50 4 ≤ N ≤ 10000 Example: Input: 2 10 6 Output: 4 6 8 9 10 4 6 </code></pre> <p>My solution is as below :</p> <pre><code>def comp(n): for i in range (4,n+1): for j in range(2,i): if i % j == 0 : print(i) break t = int(input("")) while(t &gt;=1 &amp; t &lt;= 50): for k in range(0,t): p = int(input("")) if(p &gt;=4 &amp; p &lt;= 10000): comp(p) </code></pre> <p>but giving <code>EOFError</code> on <code>p = int(input(""))</code></p>
-1
2016-09-30T05:38:31Z
39,785,234
<p>This error occurs when you are providing lesser input values than required. Your program is expecting more input's than you actually provided.</p> <p>if you are using a pipe to send data to stdin of the script then make sure each input is sent in a newline as shown below.</p> <pre><code> time echo -e "2\n'3 4 5 6 7'\n3" | python sample.py </code></pre>
0
2016-09-30T06:42:34Z
[ "python" ]
python simple basic program on geeksforgeeks
39,784,402
<p>Can anyone help me with the solution of this ?</p> <p>Given a number N, print all the composite numbers less than or equal to N. The number should be printed in ascending order.</p> <p>Input: The first line contain an Integer T denoting the number of test cases . Then T test cases follow. Each test case consist of an single integer N.</p> <p>Output: Print all the composite Number form 0 to N.</p> <p>Constraints:</p> <pre><code>1 ≤ T ≤ 50 4 ≤ N ≤ 10000 Example: Input: 2 10 6 Output: 4 6 8 9 10 4 6 </code></pre> <p>My solution is as below :</p> <pre><code>def comp(n): for i in range (4,n+1): for j in range(2,i): if i % j == 0 : print(i) break t = int(input("")) while(t &gt;=1 &amp; t &lt;= 50): for k in range(0,t): p = int(input("")) if(p &gt;=4 &amp; p &lt;= 10000): comp(p) </code></pre> <p>but giving <code>EOFError</code> on <code>p = int(input(""))</code></p>
-1
2016-09-30T05:38:31Z
39,785,316
<p>A simple solution using recursion.</p> <pre><code>def check_prime(n): for i in range(2,int(math.sqrt(n))+1): if(n%i==0): return 0 return 1 def print_composite(n): if(n&lt;5): print(n), return print_composite(n-1) if(check_prime(n)==0): print(n), return </code></pre> <p>Sample outputs from my terminal</p> <pre><code>&gt;&gt;&gt; print_composite(10) 4 6 8 9 10 &gt;&gt;&gt; print_composite(6) 4 6 &gt;&gt;&gt; print_composite(16) 4 6 8 9 10 12 14 15 16 </code></pre>
-2
2016-09-30T06:47:15Z
[ "python" ]
python simple basic program on geeksforgeeks
39,784,402
<p>Can anyone help me with the solution of this ?</p> <p>Given a number N, print all the composite numbers less than or equal to N. The number should be printed in ascending order.</p> <p>Input: The first line contain an Integer T denoting the number of test cases . Then T test cases follow. Each test case consist of an single integer N.</p> <p>Output: Print all the composite Number form 0 to N.</p> <p>Constraints:</p> <pre><code>1 ≤ T ≤ 50 4 ≤ N ≤ 10000 Example: Input: 2 10 6 Output: 4 6 8 9 10 4 6 </code></pre> <p>My solution is as below :</p> <pre><code>def comp(n): for i in range (4,n+1): for j in range(2,i): if i % j == 0 : print(i) break t = int(input("")) while(t &gt;=1 &amp; t &lt;= 50): for k in range(0,t): p = int(input("")) if(p &gt;=4 &amp; p &lt;= 10000): comp(p) </code></pre> <p>but giving <code>EOFError</code> on <code>p = int(input(""))</code></p>
-1
2016-09-30T05:38:31Z
39,785,680
<p>The culprit here is the <code>while</code> loop instead of <code>if</code>. As, the <code>t</code> is a constant value, the <code>while</code> loop will never end and thus, <code>p = int(input(""))</code> will get executed more than the required times. Hence, <code>EOFError</code> on <code>p = int(input(""))</code>.</p>
0
2016-09-30T07:09:17Z
[ "python" ]
How to isolate Anaconda from system python without set the shell path
39,784,418
<p>I want to install Anaconda locally on my home directory ~/.Anaconda3 (Archlinux) and without setting the path in the shell because I like to keep my system python as the default.</p> <p>So I like to launch the Spyder (or other Anaconda's app) as isolated app from system binaries. I mean when I launch for example <code>.Anaconda3/bin/spyder</code> it launches spyder and this app uses Anaconda's binaries but when I use <code>python ThisScript.py</code> in my shell it uses system python installed from packages (e.g. /bin/python).</p> <p>I managed to update the anaconda using <code>.Anaconda3/bin/conda update --all</code> in my shell without setting the Anaconda's binaries path (<code>.Anaconda/bin/</code>) but thsi way run some apps like spyder doesn't work obviously.</p>
2
2016-09-30T05:39:52Z
39,787,575
<p>You could use virtualenv</p> <p>1) create a virtual env using the python version you need for anaconda <code>virtualenv -p /usr/bin/pythonX.X ~/my_virtual_env</code></p> <p>2) <code>virtualenv ~/my_virtual_env/bin/activate</code></p> <p>3) Run anaconda, then <code>deactivate</code></p>
0
2016-09-30T08:58:58Z
[ "python", "linux", "shell", "anaconda", "spyder" ]
How to isolate Anaconda from system python without set the shell path
39,784,418
<p>I want to install Anaconda locally on my home directory ~/.Anaconda3 (Archlinux) and without setting the path in the shell because I like to keep my system python as the default.</p> <p>So I like to launch the Spyder (or other Anaconda's app) as isolated app from system binaries. I mean when I launch for example <code>.Anaconda3/bin/spyder</code> it launches spyder and this app uses Anaconda's binaries but when I use <code>python ThisScript.py</code> in my shell it uses system python installed from packages (e.g. /bin/python).</p> <p>I managed to update the anaconda using <code>.Anaconda3/bin/conda update --all</code> in my shell without setting the Anaconda's binaries path (<code>.Anaconda/bin/</code>) but thsi way run some apps like spyder doesn't work obviously.</p>
2
2016-09-30T05:39:52Z
39,800,213
<p>Currently <a href="https://gist.github.com/esc/4967965" rel="nofollow">this</a> zsh function solves the problem using temporarily change the shell path variable. I just need to:</p> <p>1) anaconda_on</p> <p>2) <code>which python</code> or <code>python --version</code> or <code>spyder</code> ....</p> <p>3) anaconda_off</p> <p>This is neat and solves my problem. But there might be more universal way for this. Any suggestion? There are many cases which is better to isolate anaconda from the system python.</p>
0
2016-09-30T21:15:30Z
[ "python", "linux", "shell", "anaconda", "spyder" ]
How to loop through 3 different arrays by using a single for loop in Python
39,784,438
<p>I have 3 different arrays:</p> <pre><code>a = (x, y, z) b = (p, q) c = (r, s) </code></pre> <p>I need to loop through all this arrays. Presently I am using the below method:</p> <pre><code>for loop_a in a: loop_a = some_value for loop_b in b: loop_b = some_value for loop_c in c: loop_c = some_value </code></pre> <p>How I can do this using a single for loop and iterate through all the arrays. Functionality inside the loop is same for all. I need an efficient way to do this. I checked many other already answered questions, but couldn't find a fitting answer.</p>
-2
2016-09-30T05:41:13Z
39,784,501
<p>There are two ways. The more traditional way is to use an index and a for loop. In this case, it's assumed that all lists are the same length and gets that length from the first item:</p> <pre><code>for i in range(len(a)): a[i] = some_value b[i] = some_value c[i] = some_value </code></pre> <p>Python, however, has a convenience function called <code>zip()</code> that takes multiple lists and iterates them all the same time, returning a tuple.</p> <pre><code>for values in zip(a, b, c): values[0] = some_value # sets value for a values[1] = some_value # sets value for b values[2] = some_value # sets value for c </code></pre> <p>This can be made more readable by unrolling the tuple:</p> <pre><code>for a_item, b_item, c_item in zip(a, b, c): a_item = some_value b_item = some_value c_item = some_value </code></pre> <p>Zipping doesn't need lists to be the same length and will add <code>None</code> for any missing values.</p>
1
2016-09-30T05:46:01Z
[ "python", "arrays", "for-loop" ]
How to loop through 3 different arrays by using a single for loop in Python
39,784,438
<p>I have 3 different arrays:</p> <pre><code>a = (x, y, z) b = (p, q) c = (r, s) </code></pre> <p>I need to loop through all this arrays. Presently I am using the below method:</p> <pre><code>for loop_a in a: loop_a = some_value for loop_b in b: loop_b = some_value for loop_c in c: loop_c = some_value </code></pre> <p>How I can do this using a single for loop and iterate through all the arrays. Functionality inside the loop is same for all. I need an efficient way to do this. I checked many other already answered questions, but couldn't find a fitting answer.</p>
-2
2016-09-30T05:41:13Z
39,784,572
<p>If as you mention, the functionality inside the loop is the same for all three arrays, then why not factoring it into a single function and call such function on your three arrays?</p> <p>For example:</p> <pre class="lang-py prettyprint-override"><code>def my_functionality(array): for loop in array: loop = some_value ... my_functionality(a) my_functionality(b) my_functionality(c) </code></pre>
0
2016-09-30T05:51:54Z
[ "python", "arrays", "for-loop" ]
How to loop through 3 different arrays by using a single for loop in Python
39,784,438
<p>I have 3 different arrays:</p> <pre><code>a = (x, y, z) b = (p, q) c = (r, s) </code></pre> <p>I need to loop through all this arrays. Presently I am using the below method:</p> <pre><code>for loop_a in a: loop_a = some_value for loop_b in b: loop_b = some_value for loop_c in c: loop_c = some_value </code></pre> <p>How I can do this using a single for loop and iterate through all the arrays. Functionality inside the loop is same for all. I need an efficient way to do this. I checked many other already answered questions, but couldn't find a fitting answer.</p>
-2
2016-09-30T05:41:13Z
39,784,575
<p>Why not just this?</p> <pre><code>for array in [a, b, c]: for element in array: ... </code></pre> <p>or</p> <pre><code>def f (x) : ... for e in a: e = f(e) for e in b: e = f(e) for e in c: e = f(e) </code></pre>
0
2016-09-30T05:52:09Z
[ "python", "arrays", "for-loop" ]
How to loop through 3 different arrays by using a single for loop in Python
39,784,438
<p>I have 3 different arrays:</p> <pre><code>a = (x, y, z) b = (p, q) c = (r, s) </code></pre> <p>I need to loop through all this arrays. Presently I am using the below method:</p> <pre><code>for loop_a in a: loop_a = some_value for loop_b in b: loop_b = some_value for loop_c in c: loop_c = some_value </code></pre> <p>How I can do this using a single for loop and iterate through all the arrays. Functionality inside the loop is same for all. I need an efficient way to do this. I checked many other already answered questions, but couldn't find a fitting answer.</p>
-2
2016-09-30T05:41:13Z
39,784,653
<pre><code>def t(): a = [1, 2, 3] b = [4, 5] c = [6, 7] l1 = [a, b, c] someValue = "This should print 4 times" for i in l1: l1[0] = someValue l1[1] = someValue l1[2] = someValue print(someValue) print(l1[0]) print(l1[1]) print(l1[2]) t(); </code></pre> <p>I put the lists in a list and took the index of the new list.</p>
0
2016-09-30T05:57:41Z
[ "python", "arrays", "for-loop" ]
How to loop through 3 different arrays by using a single for loop in Python
39,784,438
<p>I have 3 different arrays:</p> <pre><code>a = (x, y, z) b = (p, q) c = (r, s) </code></pre> <p>I need to loop through all this arrays. Presently I am using the below method:</p> <pre><code>for loop_a in a: loop_a = some_value for loop_b in b: loop_b = some_value for loop_c in c: loop_c = some_value </code></pre> <p>How I can do this using a single for loop and iterate through all the arrays. Functionality inside the loop is same for all. I need an efficient way to do this. I checked many other already answered questions, but couldn't find a fitting answer.</p>
-2
2016-09-30T05:41:13Z
39,784,929
<h2>Problem 1: updating a tuple</h2> <p>You cannot modify a tuple. Tuples are immutable!</p> <pre><code>&gt;&gt;&gt; a = (1, 2, 3) &gt;&gt;&gt; a[0] = 11 Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: 'tuple' object does not support item assignment </code></pre> <p>You can either replace the whole tuple, or not use tuples at all:</p> <p><strong>Option 1:</strong></p> <pre><code>&gt;&gt;&gt; a = (1, 2, 3) &gt;&gt;&gt; a = (11, 2, 3) </code></pre> <p><strong>Option 2:</strong></p> <pre><code>&gt;&gt;&gt; a = [1, 2, 3] &gt;&gt;&gt; a[0] = 11 &gt;&gt;&gt; a [11, 2, 3] </code></pre> <h2>Problem two: updating a list in a loop</h2> <p>Just one list for now. This does not do anything:</p> <pre><code>for loop_a in a: loop_a = some_value </code></pre> <p>Try it:</p> <pre><code>&gt;&gt;&gt; a = [1, 2, 3] &gt;&gt;&gt; &gt;&gt;&gt; for loop_a in a: ... loop_a = 77 ... &gt;&gt;&gt; a [1, 2, 3] &gt;&gt;&gt; loop_a 77 </code></pre> <p>Why? Because <code>for loop_a in a</code> assigns values from <code>a</code> to variable <code>loop_a</code>, then <code>loop_a = some_value</code> assigns some other vaue to <code>loop_a</code>. The only thing ever changed is <code>loop_a</code>.</p> <p>If you want to change <code>a</code>, you have to access <code>a</code>, for example <code>a[1] = 1</code>.</p> <pre><code>for i in range(len(a)): a[i] = some_value </code></pre> <p>This is not very elegant code, but the way the question is written, that is the thing to do for one list.</p> <h2>Problem 3: multiple lists</h2> <p>This is easy.</p> <pre><code>for i in range(number_of_items): a[i] = some_value b[i] = some_value c[i] = some_value </code></pre> <p>You just have to decide how to calculate <code>number_of_items</code>. That depends on what you want to do.</p>
0
2016-09-30T06:21:41Z
[ "python", "arrays", "for-loop" ]
How to loop through 3 different arrays by using a single for loop in Python
39,784,438
<p>I have 3 different arrays:</p> <pre><code>a = (x, y, z) b = (p, q) c = (r, s) </code></pre> <p>I need to loop through all this arrays. Presently I am using the below method:</p> <pre><code>for loop_a in a: loop_a = some_value for loop_b in b: loop_b = some_value for loop_c in c: loop_c = some_value </code></pre> <p>How I can do this using a single for loop and iterate through all the arrays. Functionality inside the loop is same for all. I need an efficient way to do this. I checked many other already answered questions, but couldn't find a fitting answer.</p>
-2
2016-09-30T05:41:13Z
39,785,482
<p>You could also use lambda function (or just normal function) with map function. Map runs the function given to it as first argument for each value of iterable given as second argument and returns iterator.</p> <p><a href="https://docs.python.org/3/library/functions.html#map" rel="nofollow">Python map documentation</a> </p> <pre><code>list1 = range(1,10) list2 = range(1,13, 2) list3 = range(1,15, 3) some_value = 123 lambda_func = lambda x: some_value*x list1 = map(lambda_func, list1) list2 = map(lambda_func, list2) list3 = map(lambda_func, list3) print("list1: " + str(list1)) print("list2: " + str(list2)) print("list3: " + str(list3)) </code></pre>
0
2016-09-30T06:57:54Z
[ "python", "arrays", "for-loop" ]
List field input in django rest frameowrk browsable api - mongoengine
39,784,483
<p>I have created a <code>serializer</code> that takes a list argument <code>tags</code>, but on the <code>django-rest-framework</code> browsable api, It doesn't seem to work.</p> <p>Code:</p> <p><strong>Model</strong></p> <pre class="lang-py prettyprint-override"><code>class SocialFeed(Document): platform = StringField(max_length=20, required=True, choices=('facebook', 'twitter', 'instagram')) tags = ListField(default=None) created_at = DateTimeField(default=datetime.now(), required=True) </code></pre> <p><strong>Serializer</strong></p> <pre class="lang-py prettyprint-override"><code>class SocialFeedCreateSerializer(DocumentSerializer): class Meta: model = SocialFeed fields = [ 'id', 'platform', 'tags' ] </code></pre> <p><strong>View</strong></p> <pre class="lang-py prettyprint-override"><code>class SocialFeedCreateAPIView(CreateAPIView): queryset = SocialFeed.objects.all() serializer_class = SocialFeedCreateSerializer </code></pre> <p>But on the browsable <code>API</code>, It shows a simple input box to enter tags, and I don't know what format should I put the tags in on the browsable <code>API</code> side, and I am not receiving list of tags instead a string.</p> <p>I have tried following inputs:</p> <pre><code>#1 - ['social media', 'digital media', 'digital'] #2 - 'social media', 'digital media', 'digital' #3 - social media, digital media, digital #4 - "social media", "digital media", "digital" </code></pre> <p>But on the <code>MongoDb</code>, when I fetch the document, It shows string instead a list of tags, like this:</p> <pre class="lang-py prettyprint-override"><code>"tags" : [ "['social media','digital media','digital']" ] "tags" : [ "'social media','digital media','digital'" ] "tags" : [ "social media, digital media, digital]" ] "tags" : [ "\"social media\", \"digital media\", \"digital\"" ] </code></pre> <p><strong>Required Output</strong></p> <pre class="lang-py prettyprint-override"><code>"tags" : [ "social media", "digital media", 'digital" ] </code></pre> <p>If anybody has faced the same issue, please guide me.</p>
0
2016-09-30T05:44:36Z
39,788,563
<p>DRF does only support Django's fields. You likely need to make some fields more explicits in the serializer's declaration, like making <code>tags</code> inherit from a <code>serializer.ListField</code>.</p>
0
2016-09-30T09:48:57Z
[ "python", "django", "django-rest-framework", "mongoengine", "browsable" ]
Delete Specific Part Of A String
39,784,709
<p>I want to delete the part after the last <code>'/'</code> of a string in this following way:</p> <pre><code>str = "live/1374385.jpg" formated_str = "live/" </code></pre> <p>or</p> <pre><code>str = "live/examples/myfiles.png" formated_str = "live/examples/" </code></pre> <p><strong>I have tried this so far ( working )</strong></p> <pre><code>import re for i in re.findall('(.*?)/',str): j += i j += '/' </code></pre> <p>Output : </p> <p><code>live/</code> or <code>live/examples/</code></p> <p>I am a beginner to python so just curious is there any other way to do that .</p>
2
2016-09-30T06:03:36Z
39,784,778
<p>Use <a href="https://docs.python.org/2.4/lib/string-methods.html" rel="nofollow"><code>rsplit</code></a>:</p> <pre><code>str = "live/1374385.jpg" print (str.rsplit('/', 1)[0] + '/') live/ str = "live/examples/myfiles.png" print (str.rsplit('/', 1)[0] + '/') live/examples/ </code></pre>
2
2016-09-30T06:09:24Z
[ "python", "string", "substring" ]
Delete Specific Part Of A String
39,784,709
<p>I want to delete the part after the last <code>'/'</code> of a string in this following way:</p> <pre><code>str = "live/1374385.jpg" formated_str = "live/" </code></pre> <p>or</p> <pre><code>str = "live/examples/myfiles.png" formated_str = "live/examples/" </code></pre> <p><strong>I have tried this so far ( working )</strong></p> <pre><code>import re for i in re.findall('(.*?)/',str): j += i j += '/' </code></pre> <p>Output : </p> <p><code>live/</code> or <code>live/examples/</code></p> <p>I am a beginner to python so just curious is there any other way to do that .</p>
2
2016-09-30T06:03:36Z
39,784,814
<p>You can also use <a href="https://docs.python.org/3/library/stdtypes.html#str.rindex" rel="nofollow"><code>.rindex</code></a> string method:</p> <pre><code>s = 'live/examples/myfiles.png' s[:s.rindex('/')+1] </code></pre>
2
2016-09-30T06:12:31Z
[ "python", "string", "substring" ]
Delete Specific Part Of A String
39,784,709
<p>I want to delete the part after the last <code>'/'</code> of a string in this following way:</p> <pre><code>str = "live/1374385.jpg" formated_str = "live/" </code></pre> <p>or</p> <pre><code>str = "live/examples/myfiles.png" formated_str = "live/examples/" </code></pre> <p><strong>I have tried this so far ( working )</strong></p> <pre><code>import re for i in re.findall('(.*?)/',str): j += i j += '/' </code></pre> <p>Output : </p> <p><code>live/</code> or <code>live/examples/</code></p> <p>I am a beginner to python so just curious is there any other way to do that .</p>
2
2016-09-30T06:03:36Z
39,784,839
<pre><code>#!/usr/bin/python def removePart(_str1): return "/".join(_str1.split("/")[:-1])+"/" def main(): print removePart("live/1374385.jpg") print removePart("live/examples/myfiles.png") main() </code></pre>
0
2016-09-30T06:14:29Z
[ "python", "string", "substring" ]
Numpy boolean indexing issue
39,784,911
<p>Here is my code snippet that uses numpy</p> <pre><code>import numpy as np n = 10 arr = np.array(range(n)) print(arr) selection = [i % 2 == 0 for i in range(n)] print(selection) neg_selection = np.invert(selection) print(neg_selection) print(arr[selection]) print(arr[neg_selection]) </code></pre> <p>The above code prints:</p> <pre><code>[0 1 2 3 4 5 6 7 8 9] [True, False, True, False, True, False, True, False, True, False] [False True False True False True False True False True] [1 0 1 0 1 0 1 0 1 0] [1 3 5 7 9] </code></pre> <p>the last two expected prints are:</p> <pre><code>[0 2 4 6 8] [1 3 5 7 9] </code></pre> <p>What is wrong here?</p>
0
2016-09-30T06:19:22Z
39,784,994
<p>looks like numpy has trouble dealing with <code>list</code> of <code>boolean</code>s.</p> <pre><code>n = 10 arr = np.array(range(n)) selection = [i % 2 == 0 for i in range(n)] neg_selection = np.invert(selection) print(type(selection), arr[selection]) print(type(neg_selection), arr[neg_selection]) </code></pre> <p>It produced:</p> <pre><code>&lt;type 'list'&gt; [1 0 1 0 1 0 1 0 1 0] &lt;type 'numpy.ndarray'&gt; [1 3 5 7 9] </code></pre> <p>Noticed that the trouble here is due to <code>&lt;type 'list'&gt;</code>. So, change the selection object to numpy array</p> <pre><code>selection = np.array([i % 2 == 0 for i in range(n)]) </code></pre> <p>Or, even simpler:</p> <pre><code>selection = arr % 2 == 0 </code></pre> <p>Then it worked.</p>
2
2016-09-30T06:25:34Z
[ "python", "numpy" ]
Numpy boolean indexing issue
39,784,911
<p>Here is my code snippet that uses numpy</p> <pre><code>import numpy as np n = 10 arr = np.array(range(n)) print(arr) selection = [i % 2 == 0 for i in range(n)] print(selection) neg_selection = np.invert(selection) print(neg_selection) print(arr[selection]) print(arr[neg_selection]) </code></pre> <p>The above code prints:</p> <pre><code>[0 1 2 3 4 5 6 7 8 9] [True, False, True, False, True, False, True, False, True, False] [False True False True False True False True False True] [1 0 1 0 1 0 1 0 1 0] [1 3 5 7 9] </code></pre> <p>the last two expected prints are:</p> <pre><code>[0 2 4 6 8] [1 3 5 7 9] </code></pre> <p>What is wrong here?</p>
0
2016-09-30T06:19:22Z
39,786,062
<p>Note that you can (should) write:</p> <pre><code>arr = np.arange(n) # elements of arr have the same type as n (int, float, complex, etc) arr = np.arange(n, dtype=int) arr = np.arange(n, dtype=float) </code></pre> <p>depending on what type you want for <code>arr</code>.</p>
0
2016-09-30T07:32:39Z
[ "python", "numpy" ]
Numpy boolean indexing issue
39,784,911
<p>Here is my code snippet that uses numpy</p> <pre><code>import numpy as np n = 10 arr = np.array(range(n)) print(arr) selection = [i % 2 == 0 for i in range(n)] print(selection) neg_selection = np.invert(selection) print(neg_selection) print(arr[selection]) print(arr[neg_selection]) </code></pre> <p>The above code prints:</p> <pre><code>[0 1 2 3 4 5 6 7 8 9] [True, False, True, False, True, False, True, False, True, False] [False True False True False True False True False True] [1 0 1 0 1 0 1 0 1 0] [1 3 5 7 9] </code></pre> <p>the last two expected prints are:</p> <pre><code>[0 2 4 6 8] [1 3 5 7 9] </code></pre> <p>What is wrong here?</p>
0
2016-09-30T06:19:22Z
39,795,865
<pre><code>In [63]: arr=np.arange(10) In [64]: arr Out[64]: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) In [65]: mask = [n%2==0 for n in arr] In [66]: mask Out[66]: [True, False, True, False, True, False, True, False, True, False] </code></pre> <p>Trying to index with this list:</p> <pre><code>In [67]: arr[mask] /usr/local/bin/ipython3:1: FutureWarning: in the future, boolean array-likes will be handled as a boolean array index #!/usr/bin/python3 Out[67]: array([1, 0, 1, 0, 1, 0, 1, 0, 1, 0]) </code></pre> <p>It's treating your list as a list of index integers, not booleans; same as:</p> <pre><code>In [72]: arr[[3,0,2,0,1,0,5,0,2]] Out[72]: array([3, 0, 2, 0, 1, 0, 5, 0, 2]) </code></pre> <p>I wondered why you used <code>np.invert</code>, but then realized that with a list, <code>~</code> doesn't work:</p> <pre><code>In [68]: arr[~mask] ... TypeError: bad operand type for unary ~: 'list' </code></pre> <p><code>invert</code> turns the list into an array and does the <code>not</code></p> <pre><code>In [69]: np.invert(mask) Out[69]: array([False, True, False, True, False, True, False, True, False, True], dtype=bool) In [70]: arr[np.invert(mask)] Out[70]: array([1, 3, 5, 7, 9]) </code></pre> <p>and we can <code>not</code> that array:</p> <pre><code>In [71]: arr[~np.invert(mask)] Out[71]: array([0, 2, 4, 6, 8]) </code></pre> <p>Or if I create the mask <code>array</code> right from the start:</p> <pre><code>In [73]: mask = np.array([n%2==0 for n in arr]) In [74]: arr[mask] Out[74]: array([0, 2, 4, 6, 8]) </code></pre> <p>So basically, don't try to use a boolean list as a mask. Use a boolean array.</p>
1
2016-09-30T16:16:15Z
[ "python", "numpy" ]
subprocess.Popen: 'OSError: [Errno 2] No such file or directory' only on Linux
39,785,140
<blockquote> <p>This is not a duplicate of <a href="http://stackoverflow.com/questions/39777345/subprocess-popen-oserror-errno-13-permission-denied-only-on-linux">subprocess.Popen: &#39;OSError: [Errno 13] Permission denied&#39; only on Linux</a> as that problem occurred due to wrong permissions. That has been fixed and this is an entirely different problem.</p> </blockquote> <p>When my code (given below) executes on Windows (both my laptop and AppVeyor CI), it does what it's supposed to do. But on Linux (VM on TravisCI), it throws me a file not found error.</p> <p>I am executing in <code>/home/travis/build/sayak-brm/espeak4py/</code>.</p> <p><code>ls -l</code> outputs:</p> <pre><code>$ ls -l total 48 -rw-rw-r-- 1 travis travis 500 Sep 29 20:14 appveyor.yml drwxrwxr-x 3 travis travis 4096 Sep 29 20:14 espeak4py -rw-rw-r-- 1 travis travis 32400 Sep 29 20:14 LICENSE.md -rw-rw-r-- 1 travis travis 2298 Sep 29 20:14 README.md -rw-rw-r-- 1 travis travis 0 Sep 29 20:14 requirements.txt -rw-rw-r-- 1 travis travis 759 Sep 29 20:14 test.py $ ls -l espeak4py total 592 -rwxr-xr-x 1 travis travis 276306 Sep 30 06:42 espeak drwxrwxr-x 5 travis travis 4096 Sep 29 20:14 espeak-data -rw-rw-r-- 1 travis travis 319488 Sep 29 20:14 espeak.exe -rw-rw-r-- 1 travis travis 1125 Sep 29 20:14 __init__.py $ ls -l /home/travis/build/sayak-brm/espeak4py/espeak4py total 592 -rwxr-xr-x 1 travis travis 276306 Sep 30 06:42 espeak drwxrwxr-x 5 travis travis 4096 Sep 30 06:42 espeak-data -rw-rw-r-- 1 travis travis 319488 Sep 30 06:42 espeak.exe -rw-rw-r-- 1 travis travis 1216 Sep 30 06:42 __init__.py </code></pre> <p>which shows that the files are where they are supposed to be.</p> <p>The <code>espeak</code> file is a Linux ELF Binary.</p> <hr> <p><strong>Error:</strong></p> <pre><code>$ python3 test.py Testing espeak4py Testing wait4prev Traceback (most recent call last): File "test.py", line 10, in &lt;module&gt; mySpeaker.say('Hello, World!') File "/home/travis/build/sayak-brm/espeak4py/espeak4py/__init__.py", line 38, in say self.prevproc = subprocess.Popen(cmd, executable=self.executable, cwd=os.path.dirname(os.path.abspath(__file__))) File "/opt/python/3.2.6/lib/python3.2/subprocess.py", line 744, in __init__ restore_signals, start_new_session) File "/opt/python/3.2.6/lib/python3.2/subprocess.py", line 1394, in _execute_child raise child_exception_type(errno_num, err_msg) OSError: [Errno 2] No such file or directory: '/home/travis/build/sayak-brm/espeak4py/espeak4py/espeak' </code></pre> <hr> <p><strong>Code:</strong></p> <p><code>espeak4py/__init__.py</code>:</p> <pre><code>#! python3 import subprocess import os import platform class Speaker: """ Speaker class for differentiating different speech properties. """ def __init__(self, voice="en", wpm=120, pitch=80): self.prevproc = None self.voice = voice self.wpm = wpm self.pitch = pitch if platform.system() == 'Windows': self.executable = os.path.dirname(os.path.abspath(__file__)) + "/espeak.exe" else: self.executable = os.path.dirname(os.path.abspath(__file__)) + "/espeak" def generateCommand(self, phrase): cmd = [ self.executable, "--path=.", "-v", self.voice, "-p", self.pitch, "-s", self.wpm, phrase ] cmd = [str(x) for x in cmd] return cmd def say(self, phrase, wait4prev=False): cmd=self.generateCommand(phrase) if wait4prev: try: self.prevproc.wait() except AttributeError: pass else: try: self.prevproc.terminate() except AttributeError: pass self.prevproc = subprocess.Popen(cmd, executable=self.executable, cwd=os.path.dirname(os.path.abspath(__file__))) </code></pre> <p><code>test.py</code>:</p> <pre><code>#! python3 import espeak4py import time print('Testing espeak4py\n') print('Testing wait4prev') mySpeaker = espeak4py.Speaker() mySpeaker.say('Hello, World!') time.sleep(1) mySpeaker.say('Interrupted!') time.sleep(3) mySpeaker.say('Hello, World!') time.sleep(1) mySpeaker.say('Not Interrupted.', wait4prev=True) time.sleep(5) print('Testing pitch') myHighPitchedSpeaker = espeak4py.Speaker(pitch=120) myHighPitchedSpeaker.say('I am a demo of the say function') time.sleep(5) print('Testing wpm') myFastSpeaker = espeak4py.Speaker(wpm=140) myFastSpeaker.say('I am a demo of the say function') time.sleep(5) print('Testing voice') mySpanishSpeaker = espeak4py.Speaker(voice='es') mySpanishSpeaker.say('Hola. Como estas?') print('Testing Completed.') </code></pre> <hr> <p>I don't understand why it works only on one platform and not the other.</p> <p>Travis CI Logs: <a href="https://travis-ci.org/sayak-brm/espeak4py" rel="nofollow">https://travis-ci.org/sayak-brm/espeak4py</a></p> <p>AppVeyor Logs: <a href="https://ci.appveyor.com/project/sayak-brm/espeak4py" rel="nofollow">https://ci.appveyor.com/project/sayak-brm/espeak4py</a></p> <p>GitHub: <a href="https://sayak-brm.github.io/espeak4py" rel="nofollow">https://sayak-brm.github.io/espeak4py</a></p>
0
2016-09-30T06:37:02Z
40,018,953
<p>I've tested your <code>espeak</code> Python wrapper on Linux, and it works for me. Probably it's just an issue with Windows trailing <code>\r</code> characters. You could try the following:</p> <pre><code>sed -i 's/^M//' espeak4py/__init__.py </code></pre> <p>To enter the <code>^M</code>, type <code>Ctrl-V</code> followed by <code>Ctrl-M</code>, and see if running that <code>sed</code> command solves the issue.</p>
0
2016-10-13T10:51:33Z
[ "python", "linux", "python-3.x", "cross-platform", "travis-ci" ]
How to locate this kind of element with Selenium
39,785,200
<p>I'm trying to learn how to make script in python with selenium. Most of the time I was practising with "static element" but now I want to select some elements which have a dynamic id but the problem is that their id don't have a partial static part.</p> <p>However they have another "id", static this time but I don't know how to use it in Python with selenium I have tried two different things but Selenium is unable to find this element</p> <p>This a part of the element:</p> <pre><code>&lt;div class="table-cell show-plus" ng-class="{'show-plus': !user.deleted &amp;amp;&amp;amp; (authentication.user.isManager || user.isMe) &amp;amp;&amp;amp; (!group.isExchange || !ctrl.isPast(day)), 'no-events': !_events.length, 'is-today': day === ctrl.todayString}" ng-repeat="day in ctrl.currentDays" ng-click="ctrl.addShift(user, day, false, group.grouping, group.isExchange, group.key)" lvl-drop-target="true" on-drop="ctrl.dropped(dragEl, dropEl, event, 'week')" data-user-id="30308" data-is-exchange="false" data-shift-date="2016-09-29" id="5aa270ea-180f-2861-c97a-506c76cee386"&gt;&lt;!----&gt;&lt;div data-shift-id="134514" data-is-exchange="false" ng-repeat="event in ::(_events = (user.events[day] | filter:ctrl.filterOutMultiday | orderBy:['sort', 'dtstart'])) track by event.key" lvl-draggable="true" augment-draggable="" class="shift s12B835 published can-be-selected" ng-class="::{ leave: event.type === 'leave', staging: event.status === 'planning', cancelled: event.cancelled, openend: event.isOpenEnded, published: event.status === 'published', unpublished: event.status !== 'published', unavailability: event.type === 'availability', 'can-be-selected': event.canBeSelected }" draggable="true" id="c9d08710-daef-cdf7-9d7b-c4ceb13541a6"&gt;&lt;!----&gt;&lt;div class="shift-selection" ng-click="ctrl.stopEventPropagation($event)" ng-if="::event.canBeSelected"&gt;&lt;div class="checkmark-wrapper"&gt;&lt;label class="checkmark"&gt;&lt;input type="checkbox" ng-model="ctrl.selectedEvents[event.id]" ng-change="ctrl.selectionChanged()" class="ng-pristine ng-untouched ng-valid ng-empty"&gt; &lt;span&gt;&lt;/span&gt;&lt;/label&gt;&lt;/div&gt;&lt;/div&gt;&lt;!----&gt;&lt;div class="shift-details" ng-click="ctrl.openShift(event, group.isExchange, $event)" ng-class="{'right-icon': event.showOfferedShiftIcon || event.showAvailableShiftIcon || event.showTimeoffIcon}"&gt;&lt;div class="ellipsis" title="9:00A - 5:00P • 8H"&gt;9:00A - 5:00P • 8H &lt;img style="margin-top:-2px" ng-show="event.tagId &amp;amp;&amp;amp; event.status !== 'planning'" src="/assets/svg/Icons/16/shift-repeat-white-8afc52.svg" class="ng-hide"&gt; &lt;img style="margin-top:-2px" ng-show="event.tagId &amp;amp;&amp;amp; event.status === 'planning'" src="/assets/svg/Icons/16/shift-repeat-gray-6d0e14.svg" class="ng-hide"&gt;&lt;/div&gt;&lt;div class="ellipsis duration" ng-show="event.position"&gt;Design &lt;span class="show-on-collapsed"&gt;• Carl Fairclough&lt;/span&gt;&lt;/div&gt;&lt;div class="ellipsis duration ng-hide" ng-show="!event.position"&gt;Carl Fairclough&lt;/div&gt;&lt;span class="shift-details-status ng-hide" ng-show="event.showOfferedShiftIcon"&gt;&lt;img src="/assets/svg/Icons/24/shift-offer-white-cce33c.svg"&gt; &lt;/span&gt;&lt;span class="shift-details-status ng-hide" ng-show="event.showAvailableShiftIcon"&gt;&lt;img src="/assets/svg/Icons/24/shift-available-white-c55aba.svg"&gt; &lt;/span&gt;&lt;span class="shift-details-status ng-hide" ng-show="event.showTimeoffIcon"&gt;&lt;img src="/assets/svg/Icons/24/shift-timeoff-white-0cab28.svg"&gt;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;!----&gt;&lt;/div&gt; &lt;div data-shift-id="134514" data-is-exchange="false" ng-repeat="event in ::(_events = (user.events[day] | filter:ctrl.filterOutMultiday | orderBy:['sort', 'dtstart'])) track by event.key" lvl-draggable="true" augment-draggable="" class="shift s12B835 published can-be-selected" ng-class="::{ leave: event.type === 'leave', staging: event.status === 'planning', cancelled: event.cancelled, openend: event.isOpenEnded, published: event.status === 'published', unpublished: event.status !== 'published', unavailability: event.type === 'availability', 'can-be-selected': event.canBeSelected }" draggable="true" id="c9d08710-daef-cdf7-9d7b-c4ceb13541a6"&gt;&lt;!----&gt;&lt;div class="shift-selection" ng-click="ctrl.stopEventPropagation($event)" ng-if="::event.canBeSelected"&gt;&lt;div class="checkmark-wrapper"&gt;&lt;label class="checkmark"&gt;&lt;input type="checkbox" ng-model="ctrl.selectedEvents[event.id]" ng-change="ctrl.selectionChanged()" class="ng-pristine ng-untouched ng-valid ng-empty"&gt; &lt;span&gt;&lt;/span&gt;&lt;/label&gt;&lt;/div&gt;&lt;/div&gt;&lt;!----&gt;&lt;div class="shift-details" ng-click="ctrl.openShift(event, group.isExchange, $event)" ng-class="{'right-icon': event.showOfferedShiftIcon || event.showAvailableShiftIcon || event.showTimeoffIcon}"&gt;&lt;div class="ellipsis" title="9:00A - 5:00P • 8H"&gt;9:00A - 5:00P • 8H &lt;img style="margin-top:-2px" ng-show="event.tagId &amp;amp;&amp;amp; event.status !== 'planning'" src="/assets/svg/Icons/16/shift-repeat-white-8afc52.svg" class="ng-hide"&gt; &lt;img style="margin-top:-2px" ng-show="event.tagId &amp;amp;&amp;amp; event.status === 'planning'" src="/assets/svg/Icons/16/shift-repeat-gray-6d0e14.svg" class="ng-hide"&gt;&lt;/div&gt;&lt;div class="ellipsis duration" ng-show="event.position"&gt;Design &lt;span class="show-on-collapsed"&gt;• Carl Fairclough&lt;/span&gt;&lt;/div&gt;&lt;div class="ellipsis duration ng-hide" ng-show="!event.position"&gt;Carl Fairclough&lt;/div&gt;&lt;span class="shift-details-status ng-hide" ng-show="event.showOfferedShiftIcon"&gt;&lt;img src="/assets/svg/Icons/24/shift-offer-white-cce33c.svg"&gt; &lt;/span&gt;&lt;span class="shift-details-status ng-hide" ng-show="event.showAvailableShiftIcon"&gt;&lt;img src="/assets/svg/Icons/24/shift-available-white-c55aba.svg"&gt; &lt;/span&gt;&lt;span class="shift-details-status ng-hide" ng-show="event.showTimeoffIcon"&gt;&lt;img src="/assets/svg/Icons/24/shift-timeoff-white-0cab28.svg"&gt;&lt;/span&gt;&lt;/div&gt;&lt;/div&gt; </code></pre> <p>The only things for me to pick this element is to use : </p> <pre><code>&gt; data-shift-id="134514" </code></pre> <p>I have tried different ways wwith id and xpath but same result at the end: "Unable to locate this element"</p> <p>Do you have any ideas please? </p>
2
2016-09-30T06:40:34Z
39,785,705
<p>You can build a cssSelector using attribute like this:</p> <pre><code>driver.find_element_by_css_selector("Yourtag[attributeName='Your AttributeValue']"); </code></pre> <p>For your specific case use below code snippet:</p> <pre><code>driver.find_element_by_css_selector("div[data-shift-id='134514']"); </code></pre>
0
2016-09-30T07:10:46Z
[ "python", "selenium" ]
Displaying data on new page in Python
39,785,259
<p>I want to display each row from a database in a <code>&lt;td&gt;</code> in the following index.html page:</p> <pre><code>$def with(items) &lt;h1&gt;&lt;/h1&gt; &lt;br/&gt; &lt;br&gt; &lt;table border="1"&gt; &lt;tr&gt; &lt;th&gt;Name&lt;/th&gt; &lt;th&gt;address&lt;/th&gt; &lt;th&gt;number&lt;/th&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;//want name here&lt;/td&gt; &lt;td&gt;//address here&lt;/td&gt; &lt;td&gt;//number here&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; </code></pre> <p>app.py code:</p> <pre><code>import web import MySQLdb urls = ( '/', 'Index' ) app = web.application(urls, globals()) render = web.template.render('templates/') class Index(object): def GET(self): return render.hello_form() def POST(self): form = web.input(name="a", newname="s", number="d") conn = MySQLdb.connect(host= "localhost", user="root", passwd="", db="testdb") x = conn.cursor() x.execute("SELECT * FROM details WHERE name = '%s'" % (form.name)) conn.commit() items = x.fetchall() for row in items: conn.rollback() conn.close() return render.index(items) if __name__ == "__main__": app.run() </code></pre>
0
2016-09-30T06:43:59Z
39,785,605
<p>items (results fetched) will be an array of tuples. Return the array as it is as you want to display whole data on the html and HTML is only rendered once.</p> <p>app.py code</p> <pre><code>import web import MySQLdb urls = ( '/', 'Index' ) app = web.application(urls, globals()) render = web.template.render('templates/') class Index(object): def GET(self): return render.hello_form() def POST(self): form = web.input(name="a", newname="s", number="d") conn = MySQLdb.connect(host= "localhost", user="root", passwd="", db="testdb") x = conn.cursor() x.execute("SELECT * FROM details WHERE name = '%s'" % (form.name)) items = x.fetchall() conn.close() return render.index(items) // return the array of results as a whole if __name__ == "__main__": app.run() </code></pre> <p>On index.html</p> <pre><code>$def with(items) &lt;h1&gt;&lt;/h1&gt; &lt;br/&gt; &lt;br&gt; &lt;table border="1"&gt; &lt;tr&gt; &lt;th&gt;Name&lt;/th&gt; &lt;th&gt;address&lt;/th&gt; &lt;th&gt;number&lt;/th&gt; &lt;/tr&gt; $for row in items: &lt;tr&gt; &lt;td&gt;$row[0]&lt;/td&gt; &lt;td&gt;$row[1]&lt;/td&gt; &lt;td&gt;$row[2]&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; Iterate over the items and display them </code></pre>
1
2016-09-30T07:04:30Z
[ "python", "python-2.7", "web.py" ]
NameError when reordering for statements in a list comprehension
39,785,299
<p>Hi please bear with me as I'm an amateur programmer. I'm learning list comprehensions and am getting 2 different results by switching variables though they look like they should work the same. </p> <p>An array <code>a</code> equals <code>[[0, 0, 0, 0, 0], [1, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]</code></p> <p>List Comprehension 1 Works: </p> <pre><code>[(i,j) for j in range(len(a[i])) for i in range(len(a))] </code></pre> <p>Returns: </p> <pre><code>[(0, 0), (1, 0), (2, 0), (3, 0), (4, 0), (0, 1), (1, 1), (2, 1), (3, 1), (4, 1), (0, 2), (1, 2), (2, 2), (3, 2), (4, 2), (0, 3), (1, 3), (2, 3), (3, 3), (4, 3), (0, 4), (1, 4), (2, 4), (3, 4), (4, 4)] </code></pre> <p>As expected. </p> <p>But flipping the variables...</p> <pre><code>[(j,i) for i in range(len(a[j])) for j in range(len(a))] </code></pre> <p>Results in a NameError:name 'j' is not defined</p> <p>Can someone please explain to me why it matters whether i or j comes first?</p>
1
2016-09-30T06:45:40Z
39,785,416
<p>When you have a double <code>for</code> loop in a single list comprehension it's equivalent to doing those <code>for</code> loops in the same order using "traditional" <code>for</code> loops. So</p> <pre><code>result = [(j,i) for i in range(len(a[j])) for j in range(len(a))] </code></pre> <p>is (almost exactly) equivalent to</p> <pre><code>result = [] for i in range(len(a[j])): for j in range(len(a)): result.append((j, i)) </code></pre> <p>As you can see, when you do <code>len(a[j])</code> the variable <code>j</code> doesn't exist, which is why you get that <code>NameError</code>.</p> <p>BTW, your first list comp shouldn't work either. I suspect that you've defined <code>i</code> earlier in your code, which is why you don't get a <code>NameError</code>. Here's a slightly improved version of that list comp which assumes that <code>a</code> is a matrix, i.e., all of its sublists are the same length, and that it contains at least one sublist.</p> <pre><code>[(i,j) for j in range(len(a[0])) for i in range(len(a))] </code></pre> <p>We could also do</p> <pre><code>[(j, i) for i in range(len(a)) for j in range(len(a[0]))] </code></pre> <p>Both of those list comps create this list:</p> <pre><code>[(0, 0), (1, 0), (2, 0), (3, 0), (4, 0), (0, 1), (1, 1), (2, 1), (3, 1), (4, 1), (0, 2), (1, 2), (2, 2), (3, 2), (4, 2), (0, 3), (1, 3), (2, 3), (3, 3), (4, 3), (0, 4), (1, 4), (2, 4), (3, 4), (4, 4)] </code></pre>
6
2016-09-30T06:53:32Z
[ "python", "list" ]
NameError when reordering for statements in a list comprehension
39,785,299
<p>Hi please bear with me as I'm an amateur programmer. I'm learning list comprehensions and am getting 2 different results by switching variables though they look like they should work the same. </p> <p>An array <code>a</code> equals <code>[[0, 0, 0, 0, 0], [1, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]</code></p> <p>List Comprehension 1 Works: </p> <pre><code>[(i,j) for j in range(len(a[i])) for i in range(len(a))] </code></pre> <p>Returns: </p> <pre><code>[(0, 0), (1, 0), (2, 0), (3, 0), (4, 0), (0, 1), (1, 1), (2, 1), (3, 1), (4, 1), (0, 2), (1, 2), (2, 2), (3, 2), (4, 2), (0, 3), (1, 3), (2, 3), (3, 3), (4, 3), (0, 4), (1, 4), (2, 4), (3, 4), (4, 4)] </code></pre> <p>As expected. </p> <p>But flipping the variables...</p> <pre><code>[(j,i) for i in range(len(a[j])) for j in range(len(a))] </code></pre> <p>Results in a NameError:name 'j' is not defined</p> <p>Can someone please explain to me why it matters whether i or j comes first?</p>
1
2016-09-30T06:45:40Z
39,785,544
<p>It's not the order of the variables that matters here. In fact, running List Comprehension 1 does not work either, for the same reason as List Comprehension 2. I'm guessing you had defined <code>i</code> earlier in the program, which is why List Comprehension 1 worked for you. The problem is the order of the <code>for</code> loops.</p> <p>I'll try to explain by example. If you were to write it like this, it would run fine:</p> <pre><code>[ [(i,j) for j in range(len(a[i]))] for i in range(len(a))] </code></pre> <p>Note the square brackets I added. In this case, the <code>for</code> loop with <code>i</code> happens first, and only then the <code>for</code> loop with <code>j</code>. (It should be noted, however, that this will return a list of lists of tuples.) Alternately, this would also run fine:</p> <pre><code>[(i,j) for i in range(len(a)) for j in range(len(a[i]))] </code></pre> <p>When both <code>for</code> loops are written together that way (no extra brackets this time), they're read left-to-right.</p>
4
2016-09-30T07:00:59Z
[ "python", "list" ]
Running command from Node.js with sudo
39,785,436
<p>Being new to Node.js, I have this question..</p> <p>I see it mentioned in a few places that node should not be run as root, such as <a href="http://syskall.com/dont-run-node-dot-js-as-root/" rel="nofollow">this</a>. I am just using node to set up a <strong>simple</strong> web service and executing a python script which requires root access. I just don't understand where the danger lies, as in what <strong>could</strong> the hacker do.</p> <p>My node.js file is something like this:-</p> <pre><code>var http = require('http'); var express = require('express'); var app = express(); app.use(express['static'](__dirname)); app.get('/alert', function(req, res) { var addr = req.query.addr; //~ need to check if it is a valid address?? console.log('Received addr -' + addr); var spawn = require('child_process').spawn; var process = spawn('python', ['custom-text-led/custom-text.py', addr]); process.stdout.on('data', function(data) { console.log('Data:' + data); }); }) app.get('*', function(req, res) { res.status(404).send('Unrecognized API call'); }); app.use(function(err, req, res, next) { if (req.xhr) { res.status(500).send('Opps, something went wrong'); } else { next(err); } }); app.listen(3000); console.log('App server running at port 3000'); </code></pre>
0
2016-09-30T06:54:56Z
39,786,027
<p>The hacker could do anything if there is any security issues. You could give the user witch runs the web server the permission to do the task your task is intending to do.</p> <p>In general try to avoid root whenever you can (put the tinfoil hat on).</p>
1
2016-09-30T07:30:36Z
[ "javascript", "python", "node.js", "express", "child-process" ]
Plotting more than two columns in python using Panda from a CSV file
39,785,468
<p>I am very new to python and coding in general. I have a CSV file that has the first row a string of flight attributes (ie. time, speed, heading, battery voltage etc.) I want to be able to plot time vs speed vs battery voltage. Or battery voltage vs speed. I have tried several examples, however, every example I have seen it is either plots everything in the CSV file which I do not want. Or the csv file only has 2 columns.</p> <pre><code>CSV File format: time(ms), ground_speed, battery_voltage(v), airspeed(m/s) 1322,45,12,42 1342,64,11,60 1352,30,11,27 import pandas as pd from pandas import DataFrame, read_csv import numpy as np import matplotlib.pyplot as plt import matplotlib matplotlib.style.use('ggplot') df = pd.DataFrame.from_csv('myflight.csv', index_col=False) df.plot(x='mSec', y='Airspeed(m/s)', color="g") df.plot(x='mSec', y='AS_Cmd(m/s)', color="r") </code></pre> <p>My issue with this it always plots vs the first index which is time. Also, I get two separate graphs. How do I join both airspeed and AS_Cmd into one graph and be able to plot someone else beside time vs something else?</p>
2
2016-09-30T06:57:11Z
39,785,944
<p>As you're new with python you probably should start slower and try to mess around with <code>numpy</code> first. <code>pandas</code> is a library build around <code>numpy</code>, which expects you to be familiar with that.</p> <p>We can simplify your code a bit. I've added some comments to guide you through.</p> <pre><code># You do not need that many import statements, so we just import # numpy and matplotlib using the common alias 'np' and 'plt'. import numpy as np import matplotlib.pyplot as plt matplotlib.style.use('ggplot') # Using numpy we can use the function loadtxt to load your CSV file. # We ignore the first line with the column names and use ',' as a delimiter. data = np.loadtxt('myflight.csv', delimiter=',', skiprows=1) # You can access the columns directly, but let us just define them for clarity. # This uses array slicing/indexing to cut the correct columns into variables. time = data[:,0] ground_speed = data[:,1] voltage = data[:,2] airspeed = data[:,3] # With matplotlib we define a new subplot with a certain size (10x10) fig, ax = plt.subplots(figsize=(10,10)) ax.plot(time, ground_speed, label='Ground speed [m/s]') ax.plot(time, voltage, label='Voltage [V]') # Show the legend plt.legend() </code></pre> <p>This code will get you this graph here:</p> <p><a href="http://i.stack.imgur.com/tilGv.png" rel="nofollow"><img src="http://i.stack.imgur.com/tilGv.png" alt="enter image description here"></a></p> <h2>References</h2> <p>You can find the documentation to the functions used in the <a href="http://docs.scipy.org/doc/numpy/reference/index.html" rel="nofollow">NumPy reference</a>.</p> <ul> <li><a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.loadtxt.html" rel="nofollow">numpy.loadtxt</a></li> <li><a href="http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html" rel="nofollow">Indexing</a></li> </ul> <h2>Update</h2> <p>To clarify on the use of <code>plt.subplots(figsize=(10,10))</code>: You create a new figure with this command, but matplotlib wants to return several values (two in this case). Therefore you need to specify two variables to accept those. <code>fig</code> saves the Figure instance, while <code>ax</code> will save the current <code>subplot</code>. A figure can have an unlimited amount of subplots, so you can do fancy things as shown <a href="http://www.scipy-lectures.org/intro/matplotlib/matplotlib.html#subplots" rel="nofollow">here</a>. In the example above we are only defining one subplot.</p> <p>The <code>figsize</code> attribute defines the size of the Figure in inches, thus the resulting output is 10 x 10 inches. You can play around with the values and look at the outputs.</p>
1
2016-09-30T07:25:34Z
[ "python", "pandas", "plot" ]
Plotting more than two columns in python using Panda from a CSV file
39,785,468
<p>I am very new to python and coding in general. I have a CSV file that has the first row a string of flight attributes (ie. time, speed, heading, battery voltage etc.) I want to be able to plot time vs speed vs battery voltage. Or battery voltage vs speed. I have tried several examples, however, every example I have seen it is either plots everything in the CSV file which I do not want. Or the csv file only has 2 columns.</p> <pre><code>CSV File format: time(ms), ground_speed, battery_voltage(v), airspeed(m/s) 1322,45,12,42 1342,64,11,60 1352,30,11,27 import pandas as pd from pandas import DataFrame, read_csv import numpy as np import matplotlib.pyplot as plt import matplotlib matplotlib.style.use('ggplot') df = pd.DataFrame.from_csv('myflight.csv', index_col=False) df.plot(x='mSec', y='Airspeed(m/s)', color="g") df.plot(x='mSec', y='AS_Cmd(m/s)', color="r") </code></pre> <p>My issue with this it always plots vs the first index which is time. Also, I get two separate graphs. How do I join both airspeed and AS_Cmd into one graph and be able to plot someone else beside time vs something else?</p>
2
2016-09-30T06:57:11Z
39,785,987
<p>To directly solve your problem without going deeper just do this:</p> <pre><code>subp = plt.figure().add_subplot(111) df.plot(x='mSec', y='Airspeed(m/s)', color="g", ax=subp) df.plot(x='mSec', y='AS_Cmd(m/s)', color="r", ax=subp) </code></pre> <p>You need to define a common object which to plot your plots on and give it to your plot commands, otherwise each time you plot a new one is created.</p>
1
2016-09-30T07:28:01Z
[ "python", "pandas", "plot" ]
Plotting more than two columns in python using Panda from a CSV file
39,785,468
<p>I am very new to python and coding in general. I have a CSV file that has the first row a string of flight attributes (ie. time, speed, heading, battery voltage etc.) I want to be able to plot time vs speed vs battery voltage. Or battery voltage vs speed. I have tried several examples, however, every example I have seen it is either plots everything in the CSV file which I do not want. Or the csv file only has 2 columns.</p> <pre><code>CSV File format: time(ms), ground_speed, battery_voltage(v), airspeed(m/s) 1322,45,12,42 1342,64,11,60 1352,30,11,27 import pandas as pd from pandas import DataFrame, read_csv import numpy as np import matplotlib.pyplot as plt import matplotlib matplotlib.style.use('ggplot') df = pd.DataFrame.from_csv('myflight.csv', index_col=False) df.plot(x='mSec', y='Airspeed(m/s)', color="g") df.plot(x='mSec', y='AS_Cmd(m/s)', color="r") </code></pre> <p>My issue with this it always plots vs the first index which is time. Also, I get two separate graphs. How do I join both airspeed and AS_Cmd into one graph and be able to plot someone else beside time vs something else?</p>
2
2016-09-30T06:57:11Z
39,787,634
<p>You can simply set your desired index and plot everything in one shot:</p> <pre><code>import matplotlib matplotlib.style.use('ggplot') df.set_index('time(ms)')[['ground_speed','battery_voltage(v)']].plot(rot=0, figsize=(16,10)) </code></pre> <p><a href="http://i.stack.imgur.com/mKKFH.png" rel="nofollow"><img src="http://i.stack.imgur.com/mKKFH.png" alt="enter image description here"></a></p>
1
2016-09-30T09:01:49Z
[ "python", "pandas", "plot" ]
Draw Line on Webcam Stream -Python
39,785,476
<p>I am attempting to draw a line to the webcam output. However, I am having difficulty with the following code and specifically with "img" portion of the draw line function. I have seen numerous examples of adding an image to another image, so please don't refer me to those examples. This is specifically a question of a line or square on the output of the webcam output.</p> <pre><code>cv2.line(img= vc, pt1= 10, pt2= 50, color =black,thickness = 1, lineType = 8, shift = 0) </code></pre> <p>Below is the full code:</p> <pre><code>import cv2 cv2.namedWindow("preview") vc = cv2.VideoCapture(0) if vc.isOpened(): # try to get the first frame rval, frame = vc.read() else: rval = False while rval: cv2.imshow("preview", frame) rval, frame = vc.read() key = cv2.waitKey(20) if key == 27: # exit on ESC break else: cv2.line(img= vc, pt1= 10, pt2= 50, color =black,thickness = 1, lineType = 8, shift = 0) vc.release() cv2.destroyWindow("preview") </code></pre>
1
2016-09-30T06:57:40Z
39,786,279
<p>You need to draw the line on the <code>frame</code> you get. Try the following:</p> <pre><code>import cv2 cv2.namedWindow("preview") vc = cv2.VideoCapture(0) if vc.isOpened(): # try to get the first frame rval, frame = vc.read() else: rval = False while rval: cv2.imshow("preview", frame) rval, frame = vc.read() key = cv2.waitKey(20) if key == 27: # exit on ESC break else: cv2.line(img=frame, pt1=(10, 10), pt2=(100, 10), color=(255, 0, 0), thickness=5, lineType=8, shift=0) vc.release() cv2.destroyWindow("preview") </code></pre>
2
2016-09-30T07:46:26Z
[ "python", "opencv" ]
"Backlog" of a loop through a list in Python
39,785,543
<p>I have a weird Python beginner's question,.. playing around in my virtual env in the interpreter (python 3.5):</p> <p>I have a list with mixed types: </p> <pre><code>lissi = ["foo", "bar". "boo", "baz", 4, 7] </code></pre> <p>And then "accidentally" try to print out all elements in a <strong>for loop</strong> concatenated to a string:</p> <pre><code>for x in lissi: print("Hallo " + x) </code></pre> <p>This, of course, is not possible bcs. we cannot conc. integers to a String - so the first elements are printed and then there is a TypeError. </p> <p>Then I typed just <code>"x" and enter</code> to see if there is still data stored and yes it is: <strong>x is 4</strong>. </p> <p><code>type(x)</code> is <code>int</code> (tried that to figure out if 7 is also still there).</p> <p>So my question is: What happens "under the hood" in Python in the for loop: Seems as if every successfully processed element is removed, but there is a backlog stored in x which is the first element the TypeError was thrown for? And is there a way to "clear" this data from memory in case of errors? </p> <p>thx</p>
0
2016-09-30T07:00:56Z
39,785,657
<p>I believe the problem is not with the <code>for</code> loop, but with the <code>print()</code> statement.</p> <p>You cannot <code>+</code> a <code>string</code> with an <code>integer</code>, example:</p> <p>This will not work:</p> <pre><code>print("Hallo " + 4) </code></pre> <p>nor will this:</p> <pre><code>print(4 + " Hallo") </code></pre> <p>if it is all integers it will work:</p> <pre><code>print(4 + 1) </code></pre> <p>the error which is shown from <code>print("Hallo " + 4)</code> is "<code>builtins.TypeError: Can't convert 'int' object to str implicitly</code>"</p> <p>The solution is to do the conversion from integer to string explicitely:</p> <pre><code>for x in lissi: print("Hallo " + str(x)) </code></pre> <p>Now, for your question, I do not believe there is something as a "back log". The enumeration of <code>for x in lissi</code> is still valid, and <code>x</code> is still valid, just that while processing the first 4 enumerations (where <code>x</code> is a <code>string</code>) the <code>print()</code> statement will work, then it throws an error on the <code>print()</code> statement, but <code>x</code> is still a valid <code>integer</code>.</p>
-1
2016-09-30T07:08:00Z
[ "python", "python-3.x", "for-loop", "memory" ]
"Backlog" of a loop through a list in Python
39,785,543
<p>I have a weird Python beginner's question,.. playing around in my virtual env in the interpreter (python 3.5):</p> <p>I have a list with mixed types: </p> <pre><code>lissi = ["foo", "bar". "boo", "baz", 4, 7] </code></pre> <p>And then "accidentally" try to print out all elements in a <strong>for loop</strong> concatenated to a string:</p> <pre><code>for x in lissi: print("Hallo " + x) </code></pre> <p>This, of course, is not possible bcs. we cannot conc. integers to a String - so the first elements are printed and then there is a TypeError. </p> <p>Then I typed just <code>"x" and enter</code> to see if there is still data stored and yes it is: <strong>x is 4</strong>. </p> <p><code>type(x)</code> is <code>int</code> (tried that to figure out if 7 is also still there).</p> <p>So my question is: What happens "under the hood" in Python in the for loop: Seems as if every successfully processed element is removed, but there is a backlog stored in x which is the first element the TypeError was thrown for? And is there a way to "clear" this data from memory in case of errors? </p> <p>thx</p>
0
2016-09-30T07:00:56Z
39,785,676
<p>The for loop is part of the scope it is declared in, so the following code will change the value of <code>x</code>:</p> <pre><code>x = 9 for x in xrange(3): # iterate 0, 1, 2 print(x) print(x) # x == 2, x != 9 </code></pre> <p>When the element was <code>"baz"</code>, everything was okay and the print statement worked. Python then continued execution. The next step was <code>x = 4</code>. After that, <code>print "Hallo" + x</code> failed with an error. </p> <p>While running the interpreter, errors are caught and printed, then <em>execution continues</em>. There is no cleanup after an error in the interpreter, so the last value of <code>x</code> is still there when you check the value. This is why you see 4.</p>
2
2016-09-30T07:08:55Z
[ "python", "python-3.x", "for-loop", "memory" ]