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
BeautifulSoup, findAll after findAll?
39,478,865
<p>I'm pretty new to Python and mainly need it for getting information from websites. Here I tried to get the short headlines from the bottom of the website, but cant quite get them.</p> <pre><code>from bfs4 import BeautifulSoup import requests url = "http://some-website" r = requests.get(url) soup = BeautifulSoup(r....
1
2016-09-13T20:58:01Z
39,479,053
<pre><code>from bs4 import BeautifulSoup import requests url = "http://some-website" r = requests.get(url) soup = BeautifulSoup(r.content, "html.parser") for item in soup.findAll('ul', {'class':'list'}) for link in item.findAll('a'): print link.text </code></pre>
-1
2016-09-13T21:10:37Z
[ "python", "beautifulsoup", "python-requests" ]
BeautifulSoup, findAll after findAll?
39,478,865
<p>I'm pretty new to Python and mainly need it for getting information from websites. Here I tried to get the short headlines from the bottom of the website, but cant quite get them.</p> <pre><code>from bfs4 import BeautifulSoup import requests url = "http://some-website" r = requests.get(url) soup = BeautifulSoup(r....
1
2016-09-13T20:58:01Z
39,479,072
<pre><code>from bs4 import BeautifulSoup import requests url = "http://www.n-tv.de/ticker/" r = requests.get(url) soup = BeautifulSoup(r.content, "html.parser") nachrichten = soup.findAll('ul', {'class':'list'}) links = [] for ul in nachrichten: links.extend(ul.findAll('a')) print len(links) </code></pre> <p>Hope ...
0
2016-09-13T21:13:15Z
[ "python", "beautifulsoup", "python-requests" ]
Filter IPs coming from AWS
39,478,870
<p>I have a list of IPs and I want to filter out the IPs that come from AWS. Fortunately, AWS publishes a <a href="https://ip-ranges.amazonaws.com/ip-ranges.json" rel="nofollow">list</a> of their IPs. That list is in a JSON format, so I converted it to a <a href="https://json-csv.com/c/ru5L" rel="nofollow">CSV</a>. I t...
-1
2016-09-13T20:58:21Z
39,479,073
<p>The list you are getting contains IP Ranges using <a href="https://en.wikipedia.org/wiki/Classless_Inter-Domain_Routing" rel="nofollow">CIDR Notation</a>.</p> <p>You could programmatically determine the individual IP addresses from a CIDR Block, if required: <a href="http://stackoverflow.com/questions/1942160/pytho...
2
2016-09-13T21:13:18Z
[ "python", "amazon-web-services", "pandas", "ip" ]
Python newbie clarification about tuples and strings
39,478,939
<p>I just learned that I can check if a substring is inside a string using:</p> <blockquote> <p>substring in string</p> </blockquote> <p>It looks to me that a string is just a special kind of tuple where its elements are chars. So I wonder if there's a straightforward way to search a slice of a tuple inside a tuple...
2
2016-09-13T21:02:23Z
39,478,993
<p>A string is not just a special kind of tuple. They have many similar properties, in particular, both are iterators, but they are distinct types and each defines the behavior of the <code>in</code> operator differently. See the docs on this here: <a href="https://docs.python.org/3/reference/expressions.html#in" rel="...
3
2016-09-13T21:06:58Z
[ "python", "string", "tuples" ]
Python newbie clarification about tuples and strings
39,478,939
<p>I just learned that I can check if a substring is inside a string using:</p> <blockquote> <p>substring in string</p> </blockquote> <p>It looks to me that a string is just a special kind of tuple where its elements are chars. So I wonder if there's a straightforward way to search a slice of a tuple inside a tuple...
2
2016-09-13T21:02:23Z
39,479,059
<p><code>string</code> is not a type of <code>tuple</code>. Infact both belongs to different class. How <code>in</code> statement will be evaluated is based on the <code>__contains__()</code> magic function defined within there respective class.</p> <p>Read <a href="http://stackoverflow.com/questions/14766767/how-do-y...
6
2016-09-13T21:11:03Z
[ "python", "string", "tuples" ]
Python newbie clarification about tuples and strings
39,478,939
<p>I just learned that I can check if a substring is inside a string using:</p> <blockquote> <p>substring in string</p> </blockquote> <p>It looks to me that a string is just a special kind of tuple where its elements are chars. So I wonder if there's a straightforward way to search a slice of a tuple inside a tuple...
2
2016-09-13T21:02:23Z
39,479,085
<p>Try just playing around with tuples and splices. In this case its pretty easy because your splice is essentially indexing. </p> <pre><code>&gt;&gt;&gt; tu = 12 ,23, 34,56 &gt;&gt;&gt; tu (12, 23, 34, 56) #a tuple of ints &gt;&gt;&gt; tu[:1] # a tuple with an int in it (12,) &gt;&gt;&gt; tu[:1] in tu #checks for ...
0
2016-09-13T21:14:28Z
[ "python", "string", "tuples" ]
Python newbie clarification about tuples and strings
39,478,939
<p>I just learned that I can check if a substring is inside a string using:</p> <blockquote> <p>substring in string</p> </blockquote> <p>It looks to me that a string is just a special kind of tuple where its elements are chars. So I wonder if there's a straightforward way to search a slice of a tuple inside a tuple...
2
2016-09-13T21:02:23Z
39,499,092
<p>This is how I accomplished to do my first request, however, it's not straightforward nor pythonic. I had to iterate the Java way. I wasn't able to make it using "for" loops.</p> <pre><code>def tupleInside(tupleSlice): i, j = 0, 0 while j &lt; len(tu): t = tu[j] ts = tupleSlice[i] pri...
1
2016-09-14T20:25:37Z
[ "python", "string", "tuples" ]
Python newbie clarification about tuples and strings
39,478,939
<p>I just learned that I can check if a substring is inside a string using:</p> <blockquote> <p>substring in string</p> </blockquote> <p>It looks to me that a string is just a special kind of tuple where its elements are chars. So I wonder if there's a straightforward way to search a slice of a tuple inside a tuple...
2
2016-09-13T21:02:23Z
39,507,379
<p>Just adding to Cameron Lee's answer so that it accepts <code>inner</code> containing a single integer.</p> <pre><code>def contains(inner, outer): try: inner_len = len(inner) for i, _ in enumerate(outer): outer_substring = outer[i:i+inner_len] if outer_substring == inner: ...
0
2016-09-15T09:21:20Z
[ "python", "string", "tuples" ]
python-docx - deleting first paragraph
39,479,005
<p>When I create a new document with python-docx and add paragraphs, it starts at the very first line. But if I use an empty document (I need it because of the user defined styles) and add paragraphes the document would always start with an empty line. Is there any workaround?</p>
0
2016-09-13T21:07:31Z
39,483,410
<p>You can call <code>document._body.clear_content()</code> before adding the first paragraph.</p> <pre><code>document = Document('my-document.docx') document._body.clear_content() # start adding new paragraphs and whatever ... </code></pre> <p>That will leave the document with no paragraphs, so when you add new ones...
0
2016-09-14T05:58:43Z
[ "python", "python-docx" ]
Python: make sure to send 1024 bytes at a time
39,479,036
<p>perl_server.pl </p> <pre><code>$client_socket = $socket-&gt;accept(); if (defined $client_socket) { $client_socket-&gt;autoflush(1); $client_socket-&gt;setsockopt(SOL_SOCKET, SO_RCVTIMEO, pack('l!l!', 30, 0)) or die "setsockopt: $!"; } while (1) { my $line = ""; $client_socket-&gt;rec...
0
2016-09-13T21:09:12Z
39,479,067
<pre><code>PACKET_SIZE = 1024 line = random_line() sock.send(line+"\x00"*max(PACKET_SIZE-len(line),0)) </code></pre> <p>is one way you could do it </p> <p>another way (if <code>'\x00'</code> is <strong>not</strong> your terminal char)</p> <pre><code>'{val:{terminal}&lt;{size}}'.format(val=line,size=PACKET_SIZE,termi...
3
2016-09-13T21:12:37Z
[ "python", "python-2.7", "sockets" ]
Python: make sure to send 1024 bytes at a time
39,479,036
<p>perl_server.pl </p> <pre><code>$client_socket = $socket-&gt;accept(); if (defined $client_socket) { $client_socket-&gt;autoflush(1); $client_socket-&gt;setsockopt(SOL_SOCKET, SO_RCVTIMEO, pack('l!l!', 30, 0)) or die "setsockopt: $!"; } while (1) { my $line = ""; $client_socket-&gt;rec...
0
2016-09-13T21:09:12Z
39,482,520
<p>Maybe a combination of using stride, length, and padding. <code>max</code> isn't needed as you are sure the slice is smaller than your packet size.</p> <pre><code>M = 32 for length in (M - 1, M, M + 1): payload = '1' * length for i in range(0, len(payload), M): packet = payload[i : i + M] ...
1
2016-09-14T04:31:52Z
[ "python", "python-2.7", "sockets" ]
why isn't my image being uploaded with the django form I created?
39,479,069
<p>I am using Python 2.7, Django 1.9.</p> <p>I'm trying to get an image from the user with this model/form pair:</p> <p>models.py</p> <pre><code>from PIL import Image class UserProfile(models.Model): user = models.OneToOneField(User) website = models.URLField(blank=True, null=True) location = models.Ch...
0
2016-09-13T21:12:58Z
39,479,960
<p>I upgraded to the latest version of Pillow and it works now.</p>
0
2016-09-13T22:33:49Z
[ "python", "django", "forms", "python-imaging-library", "pillow" ]
why isn't my image being uploaded with the django form I created?
39,479,069
<p>I am using Python 2.7, Django 1.9.</p> <p>I'm trying to get an image from the user with this model/form pair:</p> <p>models.py</p> <pre><code>from PIL import Image class UserProfile(models.Model): user = models.OneToOneField(User) website = models.URLField(blank=True, null=True) location = models.Ch...
0
2016-09-13T21:12:58Z
39,482,596
<p>Are you using the correct dependencies for processing images?</p>
0
2016-09-14T04:41:55Z
[ "python", "django", "forms", "python-imaging-library", "pillow" ]
Finding the longest alphabetical substring in a longer string
39,479,125
<p>I need a code to find the longest alphabetical substring in a string (s). This is the code I'm using:</p> <pre><code>letter = s[0] best = '' for n in range(1, len(s)): if len(letter) &gt; len(best): best = letter if s[n] &gt;= s[n-1]: letter += s[n] else: ...
0
2016-09-13T21:18:06Z
39,479,241
<p>You should move this check</p> <pre><code>if len(letter) &gt; len(best): best = letter </code></pre> <p>after the rest of the loop</p>
3
2016-09-13T21:26:41Z
[ "python", "string", "alphabetical" ]
Finding the longest alphabetical substring in a longer string
39,479,125
<p>I need a code to find the longest alphabetical substring in a string (s). This is the code I'm using:</p> <pre><code>letter = s[0] best = '' for n in range(1, len(s)): if len(letter) &gt; len(best): best = letter if s[n] &gt;= s[n-1]: letter += s[n] else: ...
0
2016-09-13T21:18:06Z
39,479,247
<p>The logic is almost okay except that if <code>letter</code> grows on the last loop iteration (when <code>n == len(s) - 1</code>), <code>best</code> is not changed that last time. You may insert another <code>best = letter</code> part after the loop, or re-think carefully the program structure so you won't repeat you...
1
2016-09-13T21:26:58Z
[ "python", "string", "alphabetical" ]
Finding the longest alphabetical substring in a longer string
39,479,125
<p>I need a code to find the longest alphabetical substring in a string (s). This is the code I'm using:</p> <pre><code>letter = s[0] best = '' for n in range(1, len(s)): if len(letter) &gt; len(best): best = letter if s[n] &gt;= s[n-1]: letter += s[n] else: ...
0
2016-09-13T21:18:06Z
39,479,422
<p>Your routine was almost ok, here's a little comparison between yours, the fixed one and another possible solution to your problem:</p> <pre><code>def buggy(s): letter = s[0] best = '' for n in range(1, len(s)): if len(letter) &gt; len(best): best = letter if s[n] &gt;= s[n - ...
1
2016-09-13T21:40:59Z
[ "python", "string", "alphabetical" ]
Filling a diagonal matrix based on selectors
39,479,167
<p>I have two lists:</p> <pre><code>[(1, 0), (2, 0), (2, 1), (3, 0), (3, 1), (3, 2)] [False, False, True, False, False, False] </code></pre> <p>The first list represent the row_number, column_number of the matrix. The second list represent the element value. How can I create an efficient loop(or other algorithm) so ...
0
2016-09-13T21:21:07Z
39,479,319
<p>This is actually pretty easy if you use <a href="https://docs.python.org/3.6/library/itertools.html#itertools.compress" rel="nofollow"><code>itertools.compress</code></a>:</p> <pre><code>from itertools import compress d = [(1, 0), (2, 0), (2, 1), (3, 0), (3, 1), (3, 2)] sel = [False, False, True, False, False, ...
1
2016-09-13T21:31:19Z
[ "python", "python-3.x" ]
Filling a diagonal matrix based on selectors
39,479,167
<p>I have two lists:</p> <pre><code>[(1, 0), (2, 0), (2, 1), (3, 0), (3, 1), (3, 2)] [False, False, True, False, False, False] </code></pre> <p>The first list represent the row_number, column_number of the matrix. The second list represent the element value. How can I create an efficient loop(or other algorithm) so ...
0
2016-09-13T21:21:07Z
39,479,362
<p>I would suggest using the <code>sparse</code> library from the <code>scipy</code> module for efficient sparse matrix manipulation. Here is how you would create the desired matrix:</p> <pre><code>from scipy import sparse coo = [(1, 0), (2, 0), (2, 1), (3, 0), (3, 1), (3, 2)] data = [False, False, True, False, False,...
1
2016-09-13T21:34:50Z
[ "python", "python-3.x" ]
Filling a diagonal matrix based on selectors
39,479,167
<p>I have two lists:</p> <pre><code>[(1, 0), (2, 0), (2, 1), (3, 0), (3, 1), (3, 2)] [False, False, True, False, False, False] </code></pre> <p>The first list represent the row_number, column_number of the matrix. The second list represent the element value. How can I create an efficient loop(or other algorithm) so ...
0
2016-09-13T21:21:07Z
39,479,598
<p>Does this have to actually be a numpy-like matrix? Seems to me you could do something like:</p> <pre><code>coords = [(1, 0), (2, 0), (2, 1), (3, 0), (3, 1), (3, 2)] values = [False, False, True, False, False, False] DEFAULT_VALUE = 0 height, width = max(coords)[0], max(coords, key=lambda x_y:x_y[1])[1] matrix = [...
0
2016-09-13T21:56:38Z
[ "python", "python-3.x" ]
pandas - Changing the format of a data frame
39,479,185
<p>I have a data frame which is of the format:</p> <pre><code>level_0 level_1 counts 0 back not_share 1183 1 back share 1154 2 back total 2337 3 front not_share 697 4 front share 1073 5 front total 1770 6 left not_share 4819 7 left share 5097 8 left total 991...
3
2016-09-13T21:22:48Z
39,479,224
<p>you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.pivot_table.html" rel="nofollow">pivot_table()</a> method:</p> <pre><code>In [101]: df.pivot_table(index='level_0', columns='level_1', values='counts', aggfunc='sum') Out[101]: level_1 not_share share total level_0 back 11...
3
2016-09-13T21:25:21Z
[ "python", "pandas", "dataframe", "pivot" ]
pandas - Changing the format of a data frame
39,479,185
<p>I have a data frame which is of the format:</p> <pre><code>level_0 level_1 counts 0 back not_share 1183 1 back share 1154 2 back total 2337 3 front not_share 697 4 front share 1073 5 front total 1770 6 left not_share 4819 7 left share 5097 8 left total 991...
3
2016-09-13T21:22:48Z
39,479,250
<p>Use <code>groupby</code> and <code>sum</code></p> <pre><code>df.groupby(['level_0', 'level_1']).counts.sum().unstack() </code></pre> <p><a href="http://i.stack.imgur.com/IeXuV.png"><img src="http://i.stack.imgur.com/IeXuV.png" alt="enter image description here"></a></p>
5
2016-09-13T21:27:03Z
[ "python", "pandas", "dataframe", "pivot" ]
Can't import passlib into python3
39,479,207
<p>Trying to import passlib into python3 and it fails:</p> <pre><code>$ pip freeze | grep lib passlib==1.6.5 $ python3 Python 3.4.2 (default, Oct 8 2014, 10:45:20) &gt;&gt;&gt; import passlib Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ImportError: No module named 'passlib' ...
1
2016-09-13T21:23:55Z
39,479,313
<p><code>pip</code> will install a library for python 2. If you want to install it for python 3 too, you must do so separately:</p> <pre><code>$ python3 -m pip install passlib </code></pre>
1
2016-09-13T21:31:04Z
[ "python", "python-3.x", "pip", "passlib" ]
Add multiple of a matrix without build a new one
39,479,228
<p>Say I have two matrices <code>B</code> and <code>M</code> and I want to execute the following statement:</p> <pre><code>B += 3*M </code></pre> <p>I execute this instruction repeatedly so I don't want to build each time the matrix <code>3*M</code> (<code>3</code> may change, it is just to make cleat that I only do ...
2
2016-09-13T21:25:40Z
39,479,306
<p>You can use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.tensordot.html"><code>np.tensordot</code></a> -</p> <pre><code>np.tensordot(As,Ms,axes=(0,0)) </code></pre> <p>Or <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.einsum.html"><code>np.einsum</code></a> -</p> <pre><co...
5
2016-09-13T21:30:56Z
[ "python", "numpy", "matrix" ]
Add multiple of a matrix without build a new one
39,479,228
<p>Say I have two matrices <code>B</code> and <code>M</code> and I want to execute the following statement:</p> <pre><code>B += 3*M </code></pre> <p>I execute this instruction repeatedly so I don't want to build each time the matrix <code>3*M</code> (<code>3</code> may change, it is just to make cleat that I only do ...
2
2016-09-13T21:25:40Z
39,482,794
<p>Another way you could do this, particularly if you favour readability, is to make use of <a href="http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html" rel="nofollow">broadcasting</a>.</p> <p>So you could make a 3D array from the 1D and 2D arrays and then sum over the appropriate axis:</p> <pre><code>&gt;...
1
2016-09-14T05:02:38Z
[ "python", "numpy", "matrix" ]
Parse JSON output from API file into CSV
39,479,263
<p>I am currently trying to convert a JSON output from an API request to a CSV format so i can store the results into our database. Here is my current code for reference:</p> <pre><code>import pyodbc import csv #import urllib2 import json import collections import requests #import pprint #import functools print ("Con...
0
2016-09-13T21:28:02Z
39,480,315
<p>You are saving request's <code>result.text</code> with json. <code>result.text</code> is a string so upon rereading it through json you get the same one long string instead of a <code>list</code>. Try to write <code>result.text</code> as is:</p> <pre><code>output = 'output.json' with open(output,'w') as of: of...
0
2016-09-13T23:15:11Z
[ "python", "json", "csv" ]
Parse JSON output from API file into CSV
39,479,263
<p>I am currently trying to convert a JSON output from an API request to a CSV format so i can store the results into our database. Here is my current code for reference:</p> <pre><code>import pyodbc import csv #import urllib2 import json import collections import requests #import pprint #import functools print ("Con...
0
2016-09-13T21:28:02Z
39,481,419
<p>Consider pandas's <a href="http://pandas.pydata.org/pandas-docs/version/0.17.0/generated/pandas.io.json.json_normalize.html" rel="nofollow"><code>json_normalize()</code></a> method to flatten nested items into tabular df structure:</p> <pre><code>import pandas as pd from pandas.io.json import json_normalize import ...
0
2016-09-14T01:59:40Z
[ "python", "json", "csv" ]
Cost/Number Rollup In Tree-like structure - Python
39,479,335
<p>I have a database table where each row has:</p> <pre><code>name, child1, child1_quantity, child2, child2_quantity, child3, child3_quantity, price </code></pre> <p>This table will be brought into python as a list of dictionaries or dictionary of dictionaries (doesn't matter). It will look something like this:</p> ...
0
2016-09-13T21:32:34Z
39,479,775
<pre><code>def find_price(self, name): if self.dictionary[name]["price"]: return self.dictionary[name]["price"] else: #assuming this is in a class...otherwise use global instead of self return self.find_price(dictionary[name]["child1"])*dictionary[name]["child1_quantity"] + find_price(se...
1
2016-09-13T22:14:33Z
[ "python", "recursion", "conditional", "rollup" ]
Detecting how many strings are present in a given variable?
39,479,392
<p>I'm trying to make a function that when you input a table, for example 'Fish, Carrot, Beef, Fish' it detects how many times 'Fish' was inputted, in this case 2. But when I try to do this it returns 'None' instead of 2.</p> <pre><code>def word_count(x): count = 0 for item in x: if item == 'Fish': ...
0
2016-09-13T21:38:19Z
39,479,429
<p><strong>Issue with your code</strong>: Your function is <code>return</code>ing value within the <code>if</code> statement. So, when there is no <code>Fish</code> in your <code>x</code> list, it will return <code>None</code> (<em>which is default value returned by a function in Python</em>). Try below code and it wil...
1
2016-09-13T21:41:26Z
[ "python" ]
Detecting how many strings are present in a given variable?
39,479,392
<p>I'm trying to make a function that when you input a table, for example 'Fish, Carrot, Beef, Fish' it detects how many times 'Fish' was inputted, in this case 2. But when I try to do this it returns 'None' instead of 2.</p> <pre><code>def word_count(x): count = 0 for item in x: if item == 'Fish': ...
0
2016-09-13T21:38:19Z
39,479,448
<p>It's almost correct, except:</p> <p><code>x</code>, according to your logic should be a list of strings, so you should enclose it in <code>[]</code> when calling the function. Then you can iterate over it.</p> <p>You should return from the function when you've got your answer, i.e. iterated over the list.</p> <p>...
1
2016-09-13T21:42:29Z
[ "python" ]
How do I check if a function is called in a mock method?
39,479,445
<p>AuthUser is a class which contains the delete method. I want to test if the mock delete method calls a function, given the arguments for the method.</p> <pre><code>@mock.patch.object(AuthUser, 'delete') @mock.patch('oscadmin.common.oscp.deactivate_user') def test_delete(self, deactivate_user_mock, delete_mock): ...
0
2016-09-13T21:42:20Z
39,479,530
<pre><code>delete_mock.method_expected_to_be_called.assert_called_once_with(args, kwargs) </code></pre>
0
2016-09-13T21:50:11Z
[ "python", "django", "python-2.7", "unit-testing", "django-models" ]
Generate http error from python3 requests
39,479,522
<p>I have a simple long poll thing using <code>python3</code> and the <code>requests</code> package. It currently looks something like:</p> <pre><code>def longpoll(): session = requests.Session() while True: try: fetched = session.get(MyURL) input = base64.b64decode(fetched.con...
0
2016-09-13T21:49:03Z
39,496,369
<p>Since You have control over the server you may want to reverse the 2nd call</p> <p>Here is an example using bottle to recive the 2nd poll</p> <pre><code>def longpoll(): session = requests.Session() while True: #I'm guessing that the server does not care that we call him a lot of times ... try: ...
0
2016-09-14T17:26:24Z
[ "python", "python-3.x", "python-requests", "http-error" ]
How to replace a list of special characters in a csv in python
39,479,563
<p>I have some csv files that may or may not contain characters like “”à that are undesirable, so I want to write a simple script that will feed in a csv and feed out a csv (or its contents) with those characters replaced with more standard characters, so in the example: </p> <pre><code>bad_chars = '“”à' goo...
0
2016-09-13T21:52:27Z
39,479,662
<p>As you stamped your question with the <code>pandas</code> tag - here is a pandas solution:</p> <pre><code>import pandas as pd (pd.read_csv('/path/to/file.csv') .replace(r'RegEx_search_for_str', r'RegEx_replace_with_str', regex=True) .to_csv('/path/to/fixed.csv', index=False) ) </code></pre>
1
2016-09-13T22:02:11Z
[ "python", "regex", "csv", "pandas" ]
Python pairwise comparison of elements in a array or list
39,479,578
<p>Let me elaborate my question using a simple example.I have a=[a1,a2,a3,a4], with all ai being a numerical value. </p> <p>What I want to get is pairwise comparisons within 'a', such as I(a1>=a2), I(a1>=a3), I(a1>=a4), ,,,,I(a4>=a1), I(a4>=a2), I(a4>=a3), where I is a indicator function. So I used the following code...
2
2016-09-13T21:54:23Z
39,479,607
<p>Perhaps you want:</p> <pre><code> [x &gt;= y for i,x in enumerate(a) for j,y in enumerate(a) if i != j] </code></pre> <p>This will not compare any item against itself, but compare each of the others against each other.</p>
4
2016-09-13T21:57:42Z
[ "python", "arrays", "numpy", "comparison", "rank" ]
Python pairwise comparison of elements in a array or list
39,479,578
<p>Let me elaborate my question using a simple example.I have a=[a1,a2,a3,a4], with all ai being a numerical value. </p> <p>What I want to get is pairwise comparisons within 'a', such as I(a1>=a2), I(a1>=a3), I(a1>=a4), ,,,,I(a4>=a1), I(a4>=a2), I(a4>=a3), where I is a indicator function. So I used the following code...
2
2016-09-13T21:54:23Z
39,479,618
<p>You may achieve that by using:</p> <pre><code>[x &gt;= y for i,x in enumerate(a) for j,y in enumerate(a) if i != j] </code></pre> <p><strong><em>Issue with your code</em></strong>:</p> <p>You are iterating in over list twice. If you convert your <code>comprehension</code> to <code>loop</code>, it will work like:<...
1
2016-09-13T21:58:40Z
[ "python", "arrays", "numpy", "comparison", "rank" ]
Python pairwise comparison of elements in a array or list
39,479,578
<p>Let me elaborate my question using a simple example.I have a=[a1,a2,a3,a4], with all ai being a numerical value. </p> <p>What I want to get is pairwise comparisons within 'a', such as I(a1>=a2), I(a1>=a3), I(a1>=a4), ,,,,I(a4>=a1), I(a4>=a2), I(a4>=a3), where I is a indicator function. So I used the following code...
2
2016-09-13T21:54:23Z
39,479,623
<p>You could use <a href="http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html" rel="nofollow"><code>NumPy broadcasting</code></a> -</p> <pre><code># Get the mask of comparisons in a vectorized manner using broadcasting mask = a[:,None] &gt;= a # Select the elements other than diagonal ones out = mask[~np.ey...
2
2016-09-13T21:58:54Z
[ "python", "arrays", "numpy", "comparison", "rank" ]
Python pairwise comparison of elements in a array or list
39,479,578
<p>Let me elaborate my question using a simple example.I have a=[a1,a2,a3,a4], with all ai being a numerical value. </p> <p>What I want to get is pairwise comparisons within 'a', such as I(a1>=a2), I(a1>=a3), I(a1>=a4), ,,,,I(a4>=a1), I(a4>=a2), I(a4>=a3), where I is a indicator function. So I used the following code...
2
2016-09-13T21:54:23Z
39,482,510
<p>Why are you worried about the <code>a1&gt;=a1</code> comparison. It may be pridictable, but skipping it might not be worth the extra work.</p> <p>Make a list of 100 numbers</p> <pre><code>In [17]: a=list(range(100)) </code></pre> <p>Compare them with the simple double loop; producing a 10000 values (100*100)</p>...
1
2016-09-14T04:30:45Z
[ "python", "arrays", "numpy", "comparison", "rank" ]
Cplex gives two diffirent results?
39,479,632
<p>I use Python API in Cplex to solve a Linear programing problem. When using Cplex, I had the result below:</p> <p><a href="http://i.stack.imgur.com/1BqQ2.png" rel="nofollow"><img src="http://i.stack.imgur.com/1BqQ2.png" alt="The result is solved directly by Python API"></a></p> <p>But then I saved my LP prolem as a...
2
2016-09-13T21:59:47Z
39,481,267
<p>If I understand correctly, you are solving the second time using the LP file you exported in the first run. You can loose precision when writing to LP format. Try with <a href="https://www.ibm.com/support/knowledgecenter/SSSA5P_12.6.3/ilog.odms.cplex.help/CPLEX/FileFormats/topics/SAV.html" rel="nofollow">SAV</a> for...
2
2016-09-14T01:37:12Z
[ "python", "mathematical-optimization", "cplex" ]
Cplex gives two diffirent results?
39,479,632
<p>I use Python API in Cplex to solve a Linear programing problem. When using Cplex, I had the result below:</p> <p><a href="http://i.stack.imgur.com/1BqQ2.png" rel="nofollow"><img src="http://i.stack.imgur.com/1BqQ2.png" alt="The result is solved directly by Python API"></a></p> <p>But then I saved my LP prolem as a...
2
2016-09-13T21:59:47Z
39,486,455
<p>Just to add to rkersh's comment. CPLEX when run in deterministic mode should give identical answers every time. However, if you write the model out as an LP file you will lose some precision in some of the numbers and this will perturb the problem even if only slightly, and that will often lead to different answers....
0
2016-09-14T09:02:08Z
[ "python", "mathematical-optimization", "cplex" ]
What is wrong with my sorting algorithm?
39,479,850
<p>I am a beginner programmer and I've been trying to create my own sorting algorithm in Python, I don't understand why it outputs only some of the numbers that were present in the input. I put debug prints everywhere to understand the problem but still got nothing. The code should find and move to the final array the ...
-2
2016-09-13T22:23:21Z
39,479,914
<p>Consider what happens when 5 is the maximum (and there are two 5s in the input.) One 5 gets added to output, the rest of the 5s are never added to tempArray.</p>
0
2016-09-13T22:29:50Z
[ "python", "algorithm", "sorting" ]
What is wrong with my sorting algorithm?
39,479,850
<p>I am a beginner programmer and I've been trying to create my own sorting algorithm in Python, I don't understand why it outputs only some of the numbers that were present in the input. I put debug prints everywhere to understand the problem but still got nothing. The code should find and move to the final array the ...
-2
2016-09-13T22:23:21Z
39,479,923
<p>The problem is here:</p> <pre><code>for x in array: temp = array.pop() </code></pre> <p>You're modifying the same list that you're iterating over. That's going to cause trouble.</p>
4
2016-09-13T22:30:33Z
[ "python", "algorithm", "sorting" ]
What is wrong with my sorting algorithm?
39,479,850
<p>I am a beginner programmer and I've been trying to create my own sorting algorithm in Python, I don't understand why it outputs only some of the numbers that were present in the input. I put debug prints everywhere to understand the problem but still got nothing. The code should find and move to the final array the ...
-2
2016-09-13T22:23:21Z
39,480,007
<p>To diagnose, put some debug prints in the loop, such as <code>print(output, array)</code> at the end of the outer loop. And maybe more in the inner loop. After seeing the problem (removing two things from array each inner iteration, this works.</p> <pre><code>array = [3, 6, 25, 4, 5, 24, 7, 15, 5, 2, 0, 8, 1] #j...
0
2016-09-13T22:37:16Z
[ "python", "algorithm", "sorting" ]
Elif statements not printing
39,479,885
<p>I'm doing a basic rock paper scissors code for school, but my elif statements aren't running.</p> <pre><code>def player1(x): while x != 'rock' and x != 'paper' and x != 'scissors': print("This is not a valid object selection") x = input("Player 1? ") def player2(x): while x != 'rock' and x ...
-1
2016-09-13T22:27:04Z
39,479,926
<p>Assigning to x inside <code>player1</code> isn't doing anything. As soon as the function returns, the value assigned to x is dropped. That means you are discarding your input! Then you are comparing the <em>function</em> <code>player1</code> to a <em>string</em> that might or might not match your input.</p> <p>Sugg...
1
2016-09-13T22:30:55Z
[ "python" ]
Elif statements not printing
39,479,885
<p>I'm doing a basic rock paper scissors code for school, but my elif statements aren't running.</p> <pre><code>def player1(x): while x != 'rock' and x != 'paper' and x != 'scissors': print("This is not a valid object selection") x = input("Player 1? ") def player2(x): while x != 'rock' and x ...
-1
2016-09-13T22:27:04Z
39,479,933
<p>Your comparisons:</p> <pre><code>elif player1 == "rock" and player2 == "rock": # etc </code></pre> <p>will always fail, since both player1 and player2 are functions.</p> <p>Instead, you need to return from your functions and assign those to variables. Let's cut out the validation for a minute and reduce this a li...
0
2016-09-13T22:31:32Z
[ "python" ]
Django Queryset: filtering by related item manager
39,479,907
<p>I have model for pages that consist of a number of content blocks.</p> <pre><code>class Page(models.Model): ... class Block(models.Model): page = models.ForeignKey(Page) ... </code></pre> <p>The <code>Block</code> has a handful of other properties that determine whether it is considered to be "active"...
0
2016-09-13T22:28:37Z
39,480,161
<p>As per what I know, there is no way to achieve it using single <code>queryset</code>, since you want to use the <code>active()</code> available within your manager. But you may achieve the result by adding the <a href="http://stackoverflow.com/questions/2642613/what-is-related-name-used-for-in-django">related name</...
0
2016-09-13T22:55:37Z
[ "python", "django", "django-queryset" ]
Django Queryset: filtering by related item manager
39,479,907
<p>I have model for pages that consist of a number of content blocks.</p> <pre><code>class Page(models.Model): ... class Block(models.Model): page = models.ForeignKey(Page) ... </code></pre> <p>The <code>Block</code> has a handful of other properties that determine whether it is considered to be "active"...
0
2016-09-13T22:28:37Z
39,483,258
<p>Why not just add a boolean field on the model, something like <code>is_active</code>, and update it on <code>save()</code> or <code>set_active()</code>? Then you'll be able to query your Model by that field.</p>
0
2016-09-14T05:47:50Z
[ "python", "django", "django-queryset" ]
How do I subtract the previous row from the current row in a pandas dataframe and apply it to every row; without using a loop?
39,479,919
<p>I am using Python3.5 and I am working with pandas. I have loaded stock data from yahoo finance and have saved the files to csv. My DataFrames load this data from the csv. This is a copy of the ten rows of the csv file that is my DataFrame</p> <pre><code> Date Open High Low Close Volume A...
2
2016-09-13T22:30:16Z
39,480,011
<p>you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.pct_change.html" rel="nofollow">pct_change()</a> or/and <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.diff.html" rel="nofollow">diff()</a> methods</p> <p>Demo:</p> <pre><code>In [138]: df.Clos...
2
2016-09-13T22:37:35Z
[ "python", "pandas", "indexing", "dataframe" ]
Optimize Or Pipes (|) in Regex
39,480,021
<p>I am running a multi-pipe Regex on text blocks that are about 3,000 characters long. I have 6 different and the matches are always in the same order relative to one another and complicating it is I always want to prioritize the last one firsst</p> <pre><code>Pattern1|Pattern2|Pattern3|Pattern4|Pattern5|Pattern6 </c...
1
2016-09-13T22:39:23Z
39,489,976
<p>The main point about optimizing alternation groups is <strong>the alternative branches should not match at the same location</strong>.</p> <p>Consider a string that has many similar substrings to those in your pattern above:</p> <pre><code>Pattern Pattern Pattern Pattern Pattern Pattern Pattern Pattern Pattern P...
0
2016-09-14T12:03:15Z
[ "python", "regex" ]
Python folder structure with children to JSON
39,480,031
<p>I have a script that turns any given folder structure into a JSON, JSTree compatible structure. However child folders are all grouped under one level of child. So folders within folders are marked as just one level under the root. How could I maintain the root-child-child relationship within JSON? </p> <pre><c...
0
2016-09-13T22:40:16Z
39,480,349
<p>You have only a one level hierarchy because in <code>all_dirs_with_dubdirs</code> you walk through the directory tree and append every valid directory to a flat list <code>result</code> which you then store in the only <code>"children"</code> key.</p> <p>What you want to do is to create a structure like</p> <pre><...
0
2016-09-13T23:19:44Z
[ "python", "json", "jstree" ]
Python folder structure with children to JSON
39,480,031
<p>I have a script that turns any given folder structure into a JSON, JSTree compatible structure. However child folders are all grouped under one level of child. So folders within folders are marked as just one level under the root. How could I maintain the root-child-child relationship within JSON? </p> <pre><c...
0
2016-09-13T22:40:16Z
39,480,395
<p>You can get the immediate children of the CWD with:</p> <pre><code>next(os.walk('.'))[1] </code></pre> <p>With that expression you could write a recursive traversal function like this:</p> <pre><code>def dir_to_json(dir): subdirs = next(os.walk('dir'))[1] if not subdirs: return # Something in your...
0
2016-09-13T23:26:31Z
[ "python", "json", "jstree" ]
Pandas python: Create function to merge two dataframes based on defined list of columns
39,480,038
<p>In the script that I am writing, I want to frequently repeat the same piece of code, where I create a "numerator" dataframe with one group by, and then a "denominator" dataframe with a different group by. I then merge the two together so that I have the numerator and denominator in one place. I am trying to create a...
0
2016-09-13T22:40:58Z
39,480,095
<p>You are not capturing the return value from <code>calcfractions</code>. in <code>team_pr</code>, change to <code>merged_df = self.calcfractions(df1, numlist, denomlist)</code> then <code>print(merged_df.head(2))</code> to see what you get.</p> <p>This is assuming these are methods of a class. If they are just funct...
0
2016-09-13T22:47:14Z
[ "python", "pandas" ]
Pandas python: Create function to merge two dataframes based on defined list of columns
39,480,038
<p>In the script that I am writing, I want to frequently repeat the same piece of code, where I create a "numerator" dataframe with one group by, and then a "denominator" dataframe with a different group by. I then merge the two together so that I have the numerator and denominator in one place. I am trying to create a...
0
2016-09-13T22:40:58Z
39,482,056
<p>So, after concocting my own dataframe with bogus values and trying to work through this, I have found that I run into a <code>ValueError: setting an array element with a sequence</code>. This is due to the fact that you are appending a list to a list and trying to use that as a column index in your df:</p> <pre><co...
1
2016-09-14T03:26:57Z
[ "python", "pandas" ]
button-press-event and Gtk.Frame
39,480,064
<p>In a window I have a <code>Gtk.Frame</code> with an image inside it. Now I need show a message when the <code>Gtk.Frame</code> is clicked. Here is my code.</p> <p>Glade XML:</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;!-- Generated with glade 3.18.3 --&gt; &lt;interface&gt; &lt;requires lib="...
0
2016-09-13T22:43:59Z
39,505,344
<p>There's two requirements for button-press-event to work on a widget:</p> <ul> <li>widget must have it's own GdkWindow</li> <li>widget must have GDK_BUTTON_PRESS_MASK in its event mask</li> </ul> <p>Widgets that are not normally used for input do not have a GdkWindow so this won't work with GtkFrame. </p> <p>My fi...
2
2016-09-15T07:30:37Z
[ "python", "gtk" ]
'WSGIRequest' object has no attribute 'session' while upgrading from django 1.3 to 1.9
39,480,179
<p>Similar to this question <a href="http://stackoverflow.com/questions/11783404/wsgirequest-object-has-no-attribute-session">&#39;WSGIRequest&#39; object has no attribute &#39;session&#39;</a></p> <p>But my MIDDLEWARE classes are in the correct order.</p> <pre class="lang-py prettyprint-override"><code>INSTALLED_APP...
1
2016-09-13T22:57:05Z
39,480,337
<p><code>MIDDLEWARE</code> is a new setting in 1.10 that will replace the old <code>MIDDLEWARE_CLASSES</code>.</p> <p>Since you're currently on 1.9, Django doesn't recognize the <code>MIDDLEWARE</code> setting. You should use the <code>MIDDLEWARE_CLASSES</code> setting instead:</p> <pre><code>MIDDLEWARE_CLASSES = [ ...
4
2016-09-13T23:18:05Z
[ "python", "django", "django-middleware" ]
Sony QX1 error: "Not available now"
39,480,188
<p>I have recently worked on a web app with Sony QX1. Basically, the web app should be able to change the mode of camera, start/stop shooting, take picture, playback, and etc. For the server side, I am using flask (a template of python)</p> <p>Everything works fine (I can change the exposure mode, or get the exposure ...
0
2016-09-13T22:57:48Z
39,648,793
<p>Yes there are two camera modes. Contents Transfer and Remote Shooting. This is set using the setCameraFunction command. To change camera settings, take pictures you need to be in Remote Shooting mode. To transfer files and delete files you need to be in Contents Transfer mode.</p>
0
2016-09-22T21:00:31Z
[ "python", "flask", "sony", "sony-camera-api" ]
Spark HiveContext: Tables with multiple files on HDFS
39,480,213
<p>I have a Hive table X which has multiple files on HDFS. Table X location on HDFS is /data/hive/X. Files:</p> <pre><code>/data/hive/X/f1 /data/hive/X/f2 /data/hive/X/f3 ... </code></pre> <p>Now, I run the below commands:</p> <pre><code>df=hiveContext.sql("SELECT count(*) from X") df.show() </code></pre> <p>What h...
0
2016-09-13T23:00:21Z
39,483,376
<p>Spark will contact Hive metastore to find out (a) Location of data (b) How to read the data. At low level, Spark will get Input Splits based on Input Formats used in hive to store the data. Once Splits are decided, Spark will read data 1 split/partition. In Spark, one physical node can run one or more executors. Ea...
1
2016-09-14T05:55:30Z
[ "python", "apache-spark", "dataframe", "hdfs" ]
Django: How to get latest value from db
39,480,271
<p>So I want to get the latest result for a list of values from the database.</p> <p>Example:</p> <pre><code>Task col1 col2 1 1 2 12 3 32 4 1 5 24 1 25 2 62 3 7 2 81 1 9 -&gt; last occurence for '1' in 'col1' 4 10 -&gt; last occurence for '4' in 'col1' 3 121 5 12 -&gt; last o...
0
2016-09-13T23:10:04Z
39,480,469
<p>You may achieve this result from within the QuerySet. Your ORM query will be:</p> <pre><code>Task.objects.filter(col1__in=z).values('col1').annotate(latest_record=Max('col2')) # where z = [1, 4, 5] </code></pre>
0
2016-09-13T23:36:41Z
[ "python", "django", "django-models" ]
Using integers to access a key, value pairs in a dictionary?
39,480,299
<p>Question: how can i use integer to use as Keys for a dictionary?</p> <p>Explanation: I have a dictionary</p> <pre><code>example = {} </code></pre> <p>I am populating it with key, value pairs of</p> <pre><code>A: something B: something C: something 1: something 2: something 3: something 4: something 5: something ...
0
2016-09-13T23:12:58Z
39,480,321
<p>Convert the number to a string before trying to access the dictionary:</p> <pre><code>for i in range(1,6): if self.compare(image1, example[str(i)]) &gt; 0.8: return True </code></pre> <p>Or create the dictionary using integer keys instead of strings for the keys that are numbers.</p>
2
2016-09-13T23:15:54Z
[ "python", "loops", "dictionary", "key", "key-value" ]
Using integers to access a key, value pairs in a dictionary?
39,480,299
<p>Question: how can i use integer to use as Keys for a dictionary?</p> <p>Explanation: I have a dictionary</p> <pre><code>example = {} </code></pre> <p>I am populating it with key, value pairs of</p> <pre><code>A: something B: something C: something 1: something 2: something 3: something 4: something 5: something ...
0
2016-09-13T23:12:58Z
39,480,540
<p>You just need to convert the integer to a string to match your dictionary key format.</p> <p>If you don't mind returning False if none of the comparisons exceed your threshold of 0.8, you could do this:</p> <pre><code>return any(self.compare(image1, example[str(i)]) &gt; 0.8 for i in range(1, 6)) </code></pre>
1
2016-09-13T23:46:18Z
[ "python", "loops", "dictionary", "key", "key-value" ]
tensorflow InvalidArgumentError: You must feed a value for placeholder tensor with dtype float
39,480,314
<p>I am new to tensorflow and want to train a logistic model for classification.</p> <pre><code># Set model weights W = tf.Variable(tf.zeros([30, 16])) b = tf.Variable(tf.zeros([16])) train_X, train_Y, X, Y = input('train.csv') #construct model pred = model(X, W, b) # Minimize error using cross entropy cost = tf.redu...
0
2016-09-13T23:14:48Z
39,480,394
<p>Show the code for model() - I bet it defines two placeholders: X is placeholder_56, so where is placeholder_54 coming from?</p> <p>Then pass the model x,y into the feed_dict, delete your x, y global placeholders, all will work :)</p>
0
2016-09-13T23:26:22Z
[ "python", "types", "tensorflow" ]
tensorflow InvalidArgumentError: You must feed a value for placeholder tensor with dtype float
39,480,314
<p>I am new to tensorflow and want to train a logistic model for classification.</p> <pre><code># Set model weights W = tf.Variable(tf.zeros([30, 16])) b = tf.Variable(tf.zeros([16])) train_X, train_Y, X, Y = input('train.csv') #construct model pred = model(X, W, b) # Minimize error using cross entropy cost = tf.redu...
0
2016-09-13T23:14:48Z
39,480,419
<p>From your error message, the name of the missing placeholder&mdash;<code>'Placeholder_54'</code>&mdash;is suspicious, because that suggests that at least 54 placeholders have been created in the current interpreter session. </p> <p>There aren't enough details to say for sure, but I have some suspicions. Are you ru...
0
2016-09-13T23:30:03Z
[ "python", "types", "tensorflow" ]
Chrome webdriver in selenium wont connect to proxy
39,480,393
<p>I've bound port 3003 on my local machine to a remote server</p> <p><code>ssh user@remoteserver -D 3003</code></p> <p>And in my python script</p> <pre><code>from selenium import webdriver chrome_options = webdriver.ChromeOptions() chrome_options.add_argument("--proxy-server=http://127.0.0.1:3003") driver = webdri...
0
2016-09-13T23:26:09Z
39,480,432
<p>per @Shawn Spitz's comment on <a href="http://stackoverflow.com/questions/27730306/setting-a-proxy-for-chrome-driver-in-selenium">Setting a proxy for Chrome Driver in Selenium</a> one needs to use socks5// for this because its a socks proxy. I had http, so chrome_options.add_argument("--proxy-server=socks5://127...
0
2016-09-13T23:31:50Z
[ "python", "selenium", "ssh-tunnel", "chrome-web-driver" ]
Lazy loading on column_property in SQLAlchemy
39,480,514
<p>Say I have the following models:</p> <pre><code>class Department(Base): __tablename__ = 'departments' id = Column(Integer, primary_key=True) class Employee(Base): __tablename__ = 'employees' id = Column(Integer, primary_key=True) department_id = Column(None, ForeignKey(Department.id), nullable=...
4
2016-09-13T23:42:07Z
39,552,066
<p>The loading strategies that you tried are for relationships. The loading of a <code>column_property</code> is altered in the same way as normal columns, see <a href="http://docs.sqlalchemy.org/en/latest/orm/loading_columns.html#deferred-column-loading" rel="nofollow">Deferred Column Loading</a>.</p> <p>You can defe...
3
2016-09-17T21:49:36Z
[ "python", "sqlalchemy" ]
Redefining print function not working within a function
39,480,619
<p>I am writing a python script in python 3.x in which I need to redefine the <code>print</code> function. When I do it in my interpreter, it works fine. But when I create a function using the same code, it gives out error.</p> <p>Here is my code:</p> <pre><code>list = ["print('Wow!')\n", "print('Great!')\n", "print(...
1
2016-09-13T23:57:41Z
39,480,691
<p>The interpreter doesn't recognize <strong>print</strong> as the built-in function unless you specifically tell it so. Instead of declaring it global, just remove it (thanks to Padraic Cunningham): the local <strong>print</strong> will take on your desired definition, and the global is never affected.</p> <p>You al...
2
2016-09-14T00:10:25Z
[ "python", "function", "printing", "exec" ]
Redefining print function not working within a function
39,480,619
<p>I am writing a python script in python 3.x in which I need to redefine the <code>print</code> function. When I do it in my interpreter, it works fine. But when I create a function using the same code, it gives out error.</p> <p>Here is my code:</p> <pre><code>list = ["print('Wow!')\n", "print('Great!')\n", "print(...
1
2016-09-13T23:57:41Z
39,480,713
<p>All you need is <em>nonlocal</em> and to forget all the other variables you have created bar <code>catstr</code>:</p> <pre><code>def execute(lst): def print(s): nonlocal catstr catstr += s catstr = "" for item in lst: s = item exec(s) return catstr </code></pre> <p>T...
2
2016-09-14T00:14:19Z
[ "python", "function", "printing", "exec" ]
Redefining print function not working within a function
39,480,619
<p>I am writing a python script in python 3.x in which I need to redefine the <code>print</code> function. When I do it in my interpreter, it works fine. But when I create a function using the same code, it gives out error.</p> <p>Here is my code:</p> <pre><code>list = ["print('Wow!')\n", "print('Great!')\n", "print(...
1
2016-09-13T23:57:41Z
39,480,862
<p>Your issue has been already addressed by Prune and Padraic Cunningham answers, here's another alternative way to achieve (i guess) what you want:</p> <pre><code>import io from contextlib import redirect_stdout g_list = ["print('Wow!')\n", "print('Great!')\n", "print('Epic!')\n"] def execute(lst): with io.Str...
1
2016-09-14T00:33:42Z
[ "python", "function", "printing", "exec" ]
How do I return a list of tuples with each unique string and its count given a list of strings?
39,480,706
<p>Not sure where to start... item() gives a dictionary and I don't want that.</p> <p>I would say I need to loop through the list....</p> <p>Please someone give me some hints so I can get started!</p> <p>EDIT:</p> <pre><code>count_of_names(names) counts_of_names(['John', John', 'Catherine', 'John', 'Christophe...
0
2016-09-14T00:13:16Z
39,480,745
<p>You may use <a href="https://docs.python.org/2/library/collections.html#collections.Counter" rel="nofollow"><code>collections.Counter()</code></a> to achieve this. Example:</p> <pre><code>&gt;&gt;&gt; x = [1,2,3,4,1,1,2,3] &gt;&gt;&gt; my_list = Counter(x).items() &gt;&gt;&gt; my_list [(1, 3), (2, 2), (3, 2), (4, 1...
0
2016-09-14T00:18:37Z
[ "python", "python-3.x" ]
How do I return a list of tuples with each unique string and its count given a list of strings?
39,480,706
<p>Not sure where to start... item() gives a dictionary and I don't want that.</p> <p>I would say I need to loop through the list....</p> <p>Please someone give me some hints so I can get started!</p> <p>EDIT:</p> <pre><code>count_of_names(names) counts_of_names(['John', John', 'Catherine', 'John', 'Christophe...
0
2016-09-14T00:13:16Z
39,480,911
<p>This is a hard way to do it:</p> <pre><code>x = [1,3,2,5,6,6,3,2] x_tuple = [] y = set(x) for i in y: x_tuple.append((i,x.count(i))) print(x_tuple) </code></pre>
0
2016-09-14T00:40:01Z
[ "python", "python-3.x" ]
How do I return a list of tuples with each unique string and its count given a list of strings?
39,480,706
<p>Not sure where to start... item() gives a dictionary and I don't want that.</p> <p>I would say I need to loop through the list....</p> <p>Please someone give me some hints so I can get started!</p> <p>EDIT:</p> <pre><code>count_of_names(names) counts_of_names(['John', John', 'Catherine', 'John', 'Christophe...
0
2016-09-14T00:13:16Z
39,481,108
<p>Use <code>set</code> and list comprehension:</p> <pre><code>def counts_of_names(names): return [(name, names.count(name)) for name in set(names)] </code></pre>
0
2016-09-14T01:11:16Z
[ "python", "python-3.x" ]
python recursion pass by reference or by value?
39,480,782
<p>I am working the this problem on leetcode:</p> <pre><code>Given a set of distinct integers, nums, return all possible subsets. input =[1,2,3] output =[[],[3],[2],[2,3],[1],[1,3],[1,2],[1,2,3]] </code></pre> <p>I have the c++ solution, which is accepted, and then i coded exactly the same python solution.</p> <pre>...
2
2016-09-14T00:24:02Z
39,480,861
<p>The problem is here:</p> <pre><code>solutions.append(path) </code></pre> <p>in C++, <code>vector::push_back</code> makes a copy of <code>path</code> (internally). But in Python, everything is a reference. So you build up your <code>solutions</code> as a list of many references to the same <code>path</code>, which ...
4
2016-09-14T00:33:35Z
[ "python", "c++", "recursion", "subset" ]
Remove a tuple from a list if the tuple contains a certain element
39,480,870
<p>I have a list of tuples (num, id):</p> <pre><code>l = [(1000, 1), (2000, 2), (5000, 3)] </code></pre> <p>The second element of each tuple contains the identifier. Say that I want to remove the tuple with the id of <code>2</code>, how do I do that?</p> <p>I.e. I want the new list to be: <code>l = [(1000,1), (5000,...
0
2016-09-14T00:35:10Z
39,480,891
<p>You can use a list comprehension with a filter to achieve this.</p> <pre><code>l = [(1000, 1), (2000, 2), (5000, 3)] m = [(val, key) for (val, key) in l if key != 2] </code></pre>
6
2016-09-14T00:37:46Z
[ "python" ]
Remove a tuple from a list if the tuple contains a certain element
39,480,870
<p>I have a list of tuples (num, id):</p> <pre><code>l = [(1000, 1), (2000, 2), (5000, 3)] </code></pre> <p>The second element of each tuple contains the identifier. Say that I want to remove the tuple with the id of <code>2</code>, how do I do that?</p> <p>I.e. I want the new list to be: <code>l = [(1000,1), (5000,...
0
2016-09-14T00:35:10Z
39,480,895
<p>That's because the value <strong>2</strong> is not in the list. Instead, something like the below: form a list of the second elements in your tuples, then remove the element at that position.</p> <pre><code>del_pos = [x[1] for x in l].index(2) l.pop(del_pos) </code></pre> <p>Note that this removes only the first ...
2
2016-09-14T00:38:04Z
[ "python" ]
Remove a tuple from a list if the tuple contains a certain element
39,480,870
<p>I have a list of tuples (num, id):</p> <pre><code>l = [(1000, 1), (2000, 2), (5000, 3)] </code></pre> <p>The second element of each tuple contains the identifier. Say that I want to remove the tuple with the id of <code>2</code>, how do I do that?</p> <p>I.e. I want the new list to be: <code>l = [(1000,1), (5000,...
0
2016-09-14T00:35:10Z
39,480,908
<p>You may do it with:</p> <pre><code>&gt;&gt;&gt; l = [(1000, 1), (2000, 2), (5000, 3)] &gt;&gt;&gt; for i in list(l): ... if i[1] == 2: ... l.remove(i) </code></pre> <p>In case you want to remove only first occurence, add <code>break</code> below <code>remove</code> line</p>
0
2016-09-14T00:39:42Z
[ "python" ]
Remove a tuple from a list if the tuple contains a certain element
39,480,870
<p>I have a list of tuples (num, id):</p> <pre><code>l = [(1000, 1), (2000, 2), (5000, 3)] </code></pre> <p>The second element of each tuple contains the identifier. Say that I want to remove the tuple with the id of <code>2</code>, how do I do that?</p> <p>I.e. I want the new list to be: <code>l = [(1000,1), (5000,...
0
2016-09-14T00:35:10Z
39,480,909
<p>Or using filter:</p> <pre><code>l = [(1000, 1), (2000, 2), (5000, 3)] print(list(filter(lambda x: x[1] != 2, l))) </code></pre> <p>output:</p> <pre><code>[(1000, 1), (5000, 3)] </code></pre>
2
2016-09-14T00:39:48Z
[ "python" ]
Remove a tuple from a list if the tuple contains a certain element
39,480,870
<p>I have a list of tuples (num, id):</p> <pre><code>l = [(1000, 1), (2000, 2), (5000, 3)] </code></pre> <p>The second element of each tuple contains the identifier. Say that I want to remove the tuple with the id of <code>2</code>, how do I do that?</p> <p>I.e. I want the new list to be: <code>l = [(1000,1), (5000,...
0
2016-09-14T00:35:10Z
39,480,930
<p>Simple list comprehension:</p> <pre><code>[x for x in l if x[1] != 2] </code></pre>
0
2016-09-14T00:43:06Z
[ "python" ]
Why db.session.remove() must be called?
39,480,914
<p>I'm following a tutorial to learn flask web developing, and here is its unit testing file:</p> <pre><code>import unittest from flask import current_app from app import create_app, db class BasicsTestCase(unittest.TestCase): def setUp(self): self.app = create_app('testing') self.app_context = se...
-1
2016-09-14T00:40:42Z
39,493,325
<p>I haven't understand why <code>db.session.remove()</code> is necessary until I inspected the whole project:</p> <p>This is because in <code>config.py</code>, <code>SQLALCHEMY_COMMENT_ON_TEARDOWN</code> is set to <code>True</code>. As a result, changes made to <code>db.session</code> would be auto-commited if <code>...
1
2016-09-14T14:41:21Z
[ "python", "session", "flask", "sqlalchemy", "flask-sqlalchemy" ]
Why db.session.remove() must be called?
39,480,914
<p>I'm following a tutorial to learn flask web developing, and here is its unit testing file:</p> <pre><code>import unittest from flask import current_app from app import create_app, db class BasicsTestCase(unittest.TestCase): def setUp(self): self.app = create_app('testing') self.app_context = se...
-1
2016-09-14T00:40:42Z
40,024,715
<blockquote> <p>Using the above flow, the process of integrating the <code>Session</code> with the web application has exactly two requirements:</p> <ul> <li>......</li> <li>Ensure that <code>scoped_session.remove()</code> is called when the web request ends, usually by integrating with the web framework’s...
3
2016-10-13T15:08:15Z
[ "python", "session", "flask", "sqlalchemy", "flask-sqlalchemy" ]
I'm using FileReader API to read multiple files and breaking into parts
39,480,960
<p>I want to load multiple large large files. to do this I pinched the code from </p> <blockquote> <p><a href="http://stackoverflow.com/questions/14438187/javascript-filereader-parsing-long-file-in-chunks">javascript FileReader - parsing long file in chunks</a></p> </blockquote> <p>Each chunk is given a part number...
0
2016-09-14T00:49:16Z
39,499,427
<p>I don't know python but isn't there a streaming solution to handle large file uploads? Perhaps like this: <a href="http://stackoverflow.com/questions/2502596/python-http-post-a-large-file-with-streaming">Python: HTTP Post a large file with streaming</a> ?</p> <p>In that case splitting the hole file into chunks and ...
0
2016-09-14T20:49:06Z
[ "javascript", "python" ]
WiringPi and Flask Sudo Conflict
39,480,992
<p>I am running my application in a virtualenv using Python3.4.</p> <p>WiringPi requires sudo privilege to access the hardware pins. Flask, on the other hand, resides in my virtualEnv folder, so I can't access it using <code>sudo flask</code>.</p> <p>I've tried making it run on startup by placing some commands in <co...
0
2016-09-14T00:54:34Z
39,521,293
<p>Turns out I just had to make sure that "root" had the proper libraries installed too. Root and User have different directories for their Python binaries.</p>
0
2016-09-15T22:31:57Z
[ "python", "flask", "raspberry-pi", "virtualenv", "wiringpi" ]
How to use a user function to fillna() in pandas
39,480,997
<p>This is a fragment of the dataframe I have:</p> <pre><code>Title | Age ------+-------- Mr. | 30 Mr. | NaN Mr. | 32 Mrs. | 28 Mrs. | 16 Mr. | 34 Mrs. | NaN </code></pre> <p>Edit: I added the last row, to clarify the question</p> <p>I want to impute the NaNs (second and last row), for the second row...
0
2016-09-14T00:55:44Z
39,481,105
<p><a href="http://pandas.pydata.org/pandas-docs/stable/groupby.html#transformation" rel="nofollow">Transform</a> keeps the same shape as the original series in the dataframe.</p> <pre><code>df['Age'] = df.groupby('Title').transform(lambda group: group.fillna(group.mean())) &gt;&gt;&gt; df Title Age 0 Mr. 30 1...
2
2016-09-14T01:10:57Z
[ "python", "pandas" ]
How to use a user function to fillna() in pandas
39,480,997
<p>This is a fragment of the dataframe I have:</p> <pre><code>Title | Age ------+-------- Mr. | 30 Mr. | NaN Mr. | 32 Mrs. | 28 Mrs. | 16 Mr. | 34 Mrs. | NaN </code></pre> <p>Edit: I added the last row, to clarify the question</p> <p>I want to impute the NaNs (second and last row), for the second row...
0
2016-09-14T00:55:44Z
39,481,179
<p>You can also do it this way:</p> <pre><code>df['Age'] = df['Age'].fillna(df.loc[df['Title'] == 'Mr.', 'Age'].mean()) </code></pre> <p><code>df</code> output:</p> <pre><code> Age Title 0 30.0 Mr. 1 32.0 Mr. 2 32.0 Mr. 3 28.0 Mrs. 4 16.0 Mrs. 5 34.0 Mr. </code></pre>
0
2016-09-14T01:23:36Z
[ "python", "pandas" ]
referencing a table which is defined after the definition of the first table in web2py
39,481,139
<pre><code> db.define_table("devices", Field('user_id','reference users'),# THIS PRODUCES AN ERROR Field('energyConsumed','integer'), Field('device_password','password'), Field('date_of_measure','date') ); db.define_table("users", Field('devi...
0
2016-09-14T01:16:00Z
39,484,198
<p>You can not reference to table which is not defined. So you have to use alternative syntax.</p> <p>Use <code>IS_IN_DB</code> validator for this.</p> <pre><code>IS_IN_DB(db, 'users.id') </code></pre> <p>This is already answered here:</p> <p><a href="http://stackoverflow.com/a/38948788/4065350">http://stackoverflo...
1
2016-09-14T06:54:25Z
[ "python", "web2py" ]
Python TypeError Math
39,481,169
<p>I used this code:</p> <pre><code>import pywapi import string weather_com_result = pywapi.get_weather_from_weather_com('33020') temp_f = 'temperature' * 9/5 + 32 print (weather_com_result['current_conditions']['text'].lower() + weather_com_result['current_conditions'][temp_f]) </code></pre> <p>And then when I run...
-3
2016-09-14T01:21:38Z
39,481,188
<p>You are trying to do arithmetic operations between a string and a number. <code>'temperature' * 9/5</code></p> <p>You need to get your temperature as a number first. I see you are using <code>pywapi</code> lib. So, you can get the current temperature looking up like this <code>weather_com_result['current_condition...
1
2016-09-14T01:24:59Z
[ "python" ]
django- 404 message but no runserver error
39,481,216
<p>Hi im trying to learn Django (doing the first parts of the turtorial >>docs.djangoproject.com/en/1.10/intro/tutorial02/) Im having a hard time getting my server to run, in a way that i can veiw and edit it on a website-like interface This is what is supposed to come up when I go on <a href="http://127.0.0.1:8000" re...
-3
2016-09-14T01:29:37Z
39,481,234
<p>Maybe your server python process is hang. Close your console, open it again and try to rerun your server. </p> <p>If after trying that you are still getting <code>port already in use</code> message. Try to kill the process by yourself. </p> <pre><code>ps aux | grep -i manage </code></pre> <p>You will get somethin...
2
2016-09-14T01:32:18Z
[ "python", "django", "database", "server" ]
django- 404 message but no runserver error
39,481,216
<p>Hi im trying to learn Django (doing the first parts of the turtorial >>docs.djangoproject.com/en/1.10/intro/tutorial02/) Im having a hard time getting my server to run, in a way that i can veiw and edit it on a website-like interface This is what is supposed to come up when I go on <a href="http://127.0.0.1:8000" re...
-3
2016-09-14T01:29:37Z
39,490,713
<p>Just some extra info</p> <p>If 8000 port is already in use, you can use other ports to run your Python-Django server by specifying the port like <code>python manage.py runserver 9000</code> as Django uses the 8000 port by <strong>default</strong> if you don't specify any.</p> <p>Though your original problem must h...
0
2016-09-14T12:41:17Z
[ "python", "django", "database", "server" ]
django- 404 message but no runserver error
39,481,216
<p>Hi im trying to learn Django (doing the first parts of the turtorial >>docs.djangoproject.com/en/1.10/intro/tutorial02/) Im having a hard time getting my server to run, in a way that i can veiw and edit it on a website-like interface This is what is supposed to come up when I go on <a href="http://127.0.0.1:8000" re...
-3
2016-09-14T01:29:37Z
39,491,398
<p>It looks like you typed CTRL + Z (probably by mistake), which suspends the foreground process. Use <code>fg</code> to bring the dev server process back to the foreground again. </p> <p>See: <a href="http://superuser.com/q/476873/596978">http://superuser.com/q/476873/596978</a>). </p>
0
2016-09-14T13:13:00Z
[ "python", "django", "database", "server" ]
Convert datetime back to Windows 64-bit FILETIME
39,481,221
<p>I would like to create network timestamps in NT format.</p> <p>I've been able to convert them to readable time with this function:</p> <pre><code>NetworkStamp = "\xc0\x65\x31\x50\xde\x09\xd2\x01" def GetTime(NetworkStamp): Ftime = int(struct.unpack('&lt;Q',NetworkStamp)[0]) Epoch = divmod(Ftime - 11644473...
0
2016-09-14T01:30:32Z
39,492,696
<p>If you understand how to perform the conversion in one direction, doing it in reverse is basically using the inverse of each method in reverse order. Just look at the documentation for the modules/classes you're using:</p> <ol> <li><code>strftime</code> has <a href="https://docs.python.org/3/library/datetime.html#d...
1
2016-09-14T14:14:40Z
[ "python", "python-2.x", "filetime" ]
Convert datetime back to Windows 64-bit FILETIME
39,481,221
<p>I would like to create network timestamps in NT format.</p> <p>I've been able to convert them to readable time with this function:</p> <pre><code>NetworkStamp = "\xc0\x65\x31\x50\xde\x09\xd2\x01" def GetTime(NetworkStamp): Ftime = int(struct.unpack('&lt;Q',NetworkStamp)[0]) Epoch = divmod(Ftime - 11644473...
0
2016-09-14T01:30:32Z
39,493,333
<p>&nbsp;&nbsp;&nbsp;&nbsp;Your code that converts the Window's <code>FILETIME</code> value into a <code>datetime.datetime</code> isn't as accurate as it could be—it's truncating any fractional seconds there might have been (because it ignores the remainder of the <code>divmod()</code> result). This isn't noticeable ...
0
2016-09-14T14:41:47Z
[ "python", "python-2.x", "filetime" ]
following the celery tutorial and I get this error No module named 'src'
39,481,222
<p>I am following the celery tutorial and I get this error No module named 'src'. I dont understand what the issue is.</p> <p>this is my directory structure</p> <pre><code>venv/ src/ __init__.py celery.py manage.py tasks.py </code></pre> <p>my celery.py </p> <pre><code> from __future__ import absol...
0
2016-09-14T01:30:39Z
39,481,938
<p>Your PYTHONPATH has to have the src directory inside of it. If you do <code>cd src</code> it sees your module as <code>celery</code> instead of <code>src.celery</code>.</p> <p>To fix it you can...</p> <p>A. run your code one directory up</p> <pre><code>cd .. &amp;&amp; celery worker -A src.tasks -l info </code>...
0
2016-09-14T03:12:23Z
[ "python", "django", "redis", "task", "celery" ]
Writing to a Shapefile
39,481,237
<p>I'm having trouble writing/reading a Shapefile in python. I have an array of points that I would like to write to a polygon using pyshp. The relevant parts of the code are:</p> <pre><code>dividedRects = [(7598325.0, 731579.0, 7698325.0, 631579.0), (7598325.0, 631579.0, 7698325.0, 611641.0), (7698325.0, 731579.0, 7...
0
2016-09-14T01:32:36Z
39,481,494
<p>I do not know about <code>pyshp</code> library, but I'll try to help anyways. </p> <p>The two <code>w.field()</code> commands occur in the <code>for</code> loop. This may cause the two columns "ID" and "Events" to be defined multiple times. When you write only one record (polygon), it works fine (i.e. the <code>w...
1
2016-09-14T02:09:55Z
[ "python", "shapefile" ]
Scrapy - NameError: global name 'base_search_url' is not defined
39,481,437
<p>I am trying to call a local variable from inside a Scrapy spider class but then I got <code>NameError: global name 'base_search_url' is not defined</code>.</p> <pre><code>class MySpider(scrapy.Spider): name = "mine" allowed_domains = ["www.example.com"] base_url = "https://www.example.com" start_d...
0
2016-09-14T02:02:32Z
39,481,570
<p>Solved! I end up solving it by using <code>__init__()</code> function.</p> <pre><code>def __init__(self): self.start_urls = (self.base_search_url.format(city_code, self.start_date, self.today) for city_code in self.city_codes) </code></pre>
0
2016-09-14T02:20:39Z
[ "python", "python-2.7", "scrapy", "scrapy-spider", "local-variables" ]
Scrapy - NameError: global name 'base_search_url' is not defined
39,481,437
<p>I am trying to call a local variable from inside a Scrapy spider class but then I got <code>NameError: global name 'base_search_url' is not defined</code>.</p> <pre><code>class MySpider(scrapy.Spider): name = "mine" allowed_domains = ["www.example.com"] base_url = "https://www.example.com" start_d...
0
2016-09-14T02:02:32Z
39,509,053
<p>From the <a href="http://doc.scrapy.org/en/latest/topics/spiders.html#scrapy.spiders.Spider.start_urls" rel="nofollow">docs</a>: </p> <blockquote> <p>start_urls: a list of URLs where the Spider will begin to crawl from. The first pages downloaded will be those listed here. The subsequent URLs will be generate...
0
2016-09-15T10:41:30Z
[ "python", "python-2.7", "scrapy", "scrapy-spider", "local-variables" ]
Acquire the data from a row in a Pandas
39,481,516
<p>Instructions given by Professor: 1. Using the list of countries by continent from World Atlas data, load in the countries.csv file into a pandas DataFrame and name this data set as countries. 2. Using the data available on Gapminder, load in the Income per person (GDP/capita, PPP$ inflation-adjusted) as a pandas Dat...
0
2016-09-14T02:13:48Z
39,482,049
<p>Pandas uses three types of indexing.</p> <p>If you are looking to use integer indexing, you will need to use <code>.iloc</code></p> <pre><code>df_1 Out[5]: consId fan-cnt 0 1155696024483 34.0 1 1155699007557 34.0 2 1155694005571 34.0 3 1155691016680 12.0 4 1155697016945 34.0 d...
1
2016-09-14T03:26:25Z
[ "python", "pandas", "matplotlib", "dataframe", "data-science" ]
Acquire the data from a row in a Pandas
39,481,516
<p>Instructions given by Professor: 1. Using the list of countries by continent from World Atlas data, load in the countries.csv file into a pandas DataFrame and name this data set as countries. 2. Using the data available on Gapminder, load in the Income per person (GDP/capita, PPP$ inflation-adjusted) as a pandas Dat...
0
2016-09-14T02:13:48Z
39,543,763
<p>To answer your first question, a bar graph with a year sector would be best. You'll have to keep countries on y axis and per capita income on y. And a dropdown perhaps to select a particular year for which the graph will change.</p>
0
2016-09-17T06:53:28Z
[ "python", "pandas", "matplotlib", "dataframe", "data-science" ]
Number duplicates sequentially in Pandas DataFrame
39,481,609
<p>I have a Pandas DataFrame that has a column that is basically a foreign key, as below:</p> <pre><code>Index | f_key | values 0 | 1 | red 1 | 2 | blue 2 | 1 | green 3 | 2 | yellow 4 | 3 | orange 5 | 1 | violet...
3
2016-09-14T02:25:38Z
39,481,775
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/version/0.15.0/generated/pandas.core.groupby.GroupBy.cumcount.html" rel="nofollow">cumcount()</a></p> <pre><code>df['dup_number'] = df.groupby(['f_key']).cumcount()+1 f_key values dup_number 0 1 red 1 1 2 blue...
1
2016-09-14T02:51:22Z
[ "python", "pandas", "dataframe", "duplicates", "foreign-keys" ]
Number duplicates sequentially in Pandas DataFrame
39,481,609
<p>I have a Pandas DataFrame that has a column that is basically a foreign key, as below:</p> <pre><code>Index | f_key | values 0 | 1 | red 1 | 2 | blue 2 | 1 | green 3 | 2 | yellow 4 | 3 | orange 5 | 1 | violet...
3
2016-09-14T02:25:38Z
39,481,879
<p>Below is a similar solution as one listed in <a href="http://stackoverflow.com/questions/17775935/sql-like-window-functions-in-pandas-row-numbering-in-python-pandas-dataframe">this question</a>. Here is a modified version of one of the answers that would apply here:</p> <pre><code>import pandas as pd df = pd.DataFr...
2
2016-09-14T03:03:14Z
[ "python", "pandas", "dataframe", "duplicates", "foreign-keys" ]
click on button to send adb commmand python
39,481,620
<p>I would like to build a program to send adb commannd to mobile when i click the buttton, i tried with the following code but the command is not send to device,I'm new in Python. Please can someone help me to solve this problem</p> <pre><code>from Tkinter import * import os import subprocess root = Tk() root.title(...
0
2016-09-14T02:27:29Z
39,505,903
<p>In this line:</p> <pre><code>b = Button(root, text="Enter", width=30, height=2, command = lambda:(button)) </code></pre> <p>the button function is not being called by command when you click (replace button with a print statement to test). Remove the lambda and replace it with just command = button.</p>
0
2016-09-15T08:00:27Z
[ "android", "python" ]
when inserting data to sqlite using button argument 'command'
39,481,651
<p>hello when ever i try to insert data to sqlite there is an error shows up and the button is Disappears from the frame the issue are in this two piece of function <code>def fitcher(insertFun):</code> and <code>def insertFun(self)</code> </p> <pre><code>from tkinter import * from tkinter import ttk import sqlite3 cl...
-1
2016-09-14T02:32:12Z
39,522,867
<p>you are missing a lot of things here as far as i see first you need this function </p> <pre><code>new.wait_window() return (new.varb..etc) </code></pre> <p>and you need to add this </p> <pre><code>new.conn.commit() new.conn.close() </code></pre> <p>this function you have to change the indentation take it out of...
1
2016-09-16T02:17:18Z
[ "python", "sqlite", "tkinter" ]
PyCharm throwing an error when I try to use macports python
39,481,676
<p>I'm trying to get Theano installed so I can start playing with some cool ML stuff, but I'm running into a problem with PyCharm. I'm following the instructions <a href="http://deeplearning.net/software/theano/install.html" rel="nofollow">here</a> to get all the prereqs installed so I can run Theano smoothly, so I've ...
0
2016-09-14T02:35:56Z
39,949,718
<p>Fixed it! The problem was with my ipython (5.1), which wasn't compatible with pycharm. I uninstalled it and reverted back to 4.2, which cleared up the errors with using the console, but left the one about the ipython.utils.traitlets package. To fix this, I just disabled pycharm's use of ipython. Everything seems to ...
0
2016-10-09T23:55:52Z
[ "python", "python-2.7", "pycharm", "theano", "macports" ]
Counting inversion in python: int object not iterable error
39,481,682
<p>Hi I am new to python and I am having trouble on the counting inversion problem using mergesort. The error said ""int" object is not iterable. However, I don't think I am iterating any number at this stage. Since I am stucked here, I am not sure if there are more bugs in this code.. Can anyone help me figuring out w...
0
2016-09-14T02:36:58Z
39,482,125
<p>Well, I'm not versed in the Merge Sort algorithm but in <code>get_number_of_inversions()</code> you have two exits:</p> <p>First:</p> <pre><code>number_of_inversions = 0 if right - left &lt;= 1: return number_of_inversions </code></pre> <p>And:</p> <pre><code>return tot_inversions, sorted_list </code></pre>...
1
2016-09-14T03:37:08Z
[ "python", "mergesort", "inversion" ]
boto error to launch ec2 instance
39,481,770
<p>i am using ansible to create an ec2 isntance . during the playbook run, i am getting the error as:</p> <pre><code>TASK [create a single ec2 instance] ******************************************** An exception occurred during task execution. To see the full traceback, use -vvv. The error was: NameError: name 'botocor...
0
2016-09-14T02:50:55Z
39,482,023
<p>You need to install boto3 (<code>pip install boto3</code>)</p>
0
2016-09-14T03:22:56Z
[ "python", "python-2.7", "python-3.x", "ansible", "ansible-playbook" ]