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 |
|---|---|---|---|---|---|---|---|---|---|
Django paginator with many pages | 39,088,813 | <p>I have implemented a paginator with the generic ListView. My problem is that for list with many pages it displays all the page numbers instead of for example five pages before and after the current page. Is there an easy way to fix this?</p>
<p>in the views.py:</p>
<pre><code>class CarList(LoginRequiredMixin, ListView):
model = Car
paginate_by = 20
</code></pre>
<p>in the html:</p>
<pre><code>{% if is_paginated %}
<ul class="pagination pagination-centered">
{% if page_obj.has_previous %}
<li><a href="/car?ordering={{ current_order }}&page=1"><<</a></li>
<li><a href="/car?ordering={{ current_order }}&page={{ page_obj.previous_page_number }}"><</a></li>
{% endif %}
{% for i in paginator.page_range %}
<li {% if page_obj.number == i %} class="active" {% endif %}><a href="/car?ordering={{ current_order }}&page={{i}}">{{i}}</a></li>
{% endfor %}
{% if page_obj.has_next %}
<li><a href="/car?ordering={{ current_order }}&page={{ page_obj.next_page_number }}">></a></li>
<li><a href="/car?ordering={{ current_order }}&page={{ page_obj.paginator.num_pages }}">>></a></li>
{% endif %}
</ul>
{% endif %}
</code></pre>
| 1 | 2016-08-22T21:13:06Z | 39,090,909 | <p>The algorithm for that is not too complicated, and can be further simplified if we assume that if there are more than 11 pages (current, 5 before, 5 after) we are always going to show 11 links. Now we have 4 cases:</p>
<ol>
<li>Number of pages < 11: show all pages;</li>
<li>Current page <= 6: show first 11 pages;</li>
<li>Current page > 6 and < (number of pages - 6): show current page, 5 before and 5 after;</li>
<li>Current page >= (number of pages -6): show the last 11 pages.</li>
</ol>
<p>With the above in mind, let's modify your view, create a variable to hold the numbers of pages to show and put it in the context:</p>
<pre><code>class CarList(LoginRequiredMixin, ListView):
model = Car
paginate_by = 20
def get_context_data(self, **kwargs):
context = super(CarList, self).get_context_data(**kwargs)
if not context.get('is_paginated', False):
return context
paginator = context.get('paginator')
num_pages = paginator.num_pages
current_page = context.get('page_obj')
page_no = current_page.number
if num_pages <= 11 or page_no <= 6: # case 1 and 2
pages = [x for x in range(1, min(num_pages + 1, 12))]
elif page_no > num_pages - 6: # case 4
pages = [x for x in range(num_pages - 10, num_pages + 1)]
else: # case 3
pages = [x for x in range(page_no - 5, page_no + 6)]
context.update({'pages': pages})
return context
</code></pre>
<p>Now you can simply use the new variable in your template to create page links:</p>
<pre><code> (...)
{% for i in pages %}
<li {% if page_obj.number == i %} class="active" {% endif %}><a href="/car?ordering={{ current_order }}&page={{i}}">{{i}}</a></li>
{% endfor %}
(...)
</code></pre>
| 2 | 2016-08-23T01:16:05Z | [
"python",
"django",
"python-3.x",
"pagination",
"django-views"
] |
python random shuffle while loop | 39,088,844 | <p>I'm trying to fill lists with permutations of the same initial list. I don't understand why the following is not working.</p>
<pre><code>parts = [[],[]]
while len(parts[-1]) < 2:
newval = random.choice([[1,2,3,4],[5,6,7,8]])
for part in parts:
random.shuffle(newval)
part.append(newval)
</code></pre>
<p>Expected result would be something like:
<code>[[[6,7,8,5],[1,3,4,2]],[[5,8,6,7],[4,2,3,1]]]</code></p>
| 3 | 2016-08-22T21:16:06Z | 39,088,944 | <p><code>random.shuffle</code> works in-place and consequently modifies <code>newval</code>. You have to make a copy when appending to <code>part</code> otherwise the same list (or list reference) is shuffled and stored in <code>part</code>.</p>
<pre><code>import random
parts = [[],[]]
while len(parts[-1]) < 2:
newval = random.choice([[1,2,3,4],[5,6,7,8]])
for part in parts:
random.shuffle(newval)
part.append(newval[:])
print(parts)
</code></pre>
<p>possible outputs:</p>
<pre><code>[[[3, 1, 2, 4], [5, 7, 6, 8]], [[1, 2, 4, 3], [6, 7, 5, 8]]]
[[[1, 3, 2, 4], [4, 2, 1, 3]], [[2, 4, 3, 1], [4, 3, 2, 1]]]
[[[7, 5, 6, 8], [3, 2, 4, 1]], [[8, 5, 6, 7], [1, 4, 3, 2]]]
</code></pre>
| 6 | 2016-08-22T21:22:34Z | [
"python",
"list",
"random",
"while-loop"
] |
python random shuffle while loop | 39,088,844 | <p>I'm trying to fill lists with permutations of the same initial list. I don't understand why the following is not working.</p>
<pre><code>parts = [[],[]]
while len(parts[-1]) < 2:
newval = random.choice([[1,2,3,4],[5,6,7,8]])
for part in parts:
random.shuffle(newval)
part.append(newval)
</code></pre>
<p>Expected result would be something like:
<code>[[[6,7,8,5],[1,3,4,2]],[[5,8,6,7],[4,2,3,1]]]</code></p>
| 3 | 2016-08-22T21:16:06Z | 39,088,986 | <p>Because in Python everything is reference. When you append the value to the array, in fact you add the reference to the place in memory where the value is stored.</p>
<p>Say, you have assigned the list to the first element. When on the next iteration you re-shuffle this list, you change the value in the memory. Thus, the value you will when accessing the element you appended on previous step is also changed.</p>
<p>To fix this, try appending <code>copy.copy(newval)</code> instead of just <code>newval</code> (do not forget to <code>import copy</code>)</p>
<p>Here is your code changed accordingly:</p>
<pre><code>import copy
parts = [[],[]]
while len(parts[-1]) < 2:
newval = random.choice([[1,2,3,4],[5,6,7,8]])
for part in parts:
random.shuffle(newval)
part.append(copy.copy(newval))
</code></pre>
| 3 | 2016-08-22T21:26:01Z | [
"python",
"list",
"random",
"while-loop"
] |
Python: faster alternatives to searching if an item is "in" a list | 39,088,867 | <p>I have a list of ~30 floats. I want to see if a specific float is in my list. For example:</p>
<pre><code>1 >> # For the example below my list has integers, not floats
2 >> list_a = range(30)
3 >> 5.5 in list_a
False
4 >> 1 in list_a
True
</code></pre>
<p>The bottleneck in my code is line 3. I search if an item is in my list numerous times, and I require a faster alternative. This bottleneck takes over 99% of my time.</p>
<p>I was able to speed up my code by making <code>list_a</code> a set instead of a list. Are there any other ways to significantly speed up this line?</p>
| 0 | 2016-08-22T21:17:24Z | 39,088,907 | <p>The best possible time to check if an element is in list if the list is not sorted is O(n) because the element may be anywhere and you need to look at each item and check if it is what you are looking for</p>
<p>If the array was sorted, you could've used binary search to have O(log n) look up time. You also can use hash maps to have average O(1) lookup time (or you can use built-in set, which is basically a dictionary that accomplishes the same task).</p>
<p>That does not make much sense for a list of length 30, though.</p>
| 2 | 2016-08-22T21:20:13Z | [
"python",
"list",
"optimization",
"set"
] |
Python: faster alternatives to searching if an item is "in" a list | 39,088,867 | <p>I have a list of ~30 floats. I want to see if a specific float is in my list. For example:</p>
<pre><code>1 >> # For the example below my list has integers, not floats
2 >> list_a = range(30)
3 >> 5.5 in list_a
False
4 >> 1 in list_a
True
</code></pre>
<p>The bottleneck in my code is line 3. I search if an item is in my list numerous times, and I require a faster alternative. This bottleneck takes over 99% of my time.</p>
<p>I was able to speed up my code by making <code>list_a</code> a set instead of a list. Are there any other ways to significantly speed up this line?</p>
| 0 | 2016-08-22T21:17:24Z | 39,089,167 | <p>In my experience, Python indeed slows down when we search something in a long list.</p>
<p>To complement the suggestion above, my suggestion will be subsetting the list, of course only if the list can be subset and the query can be easily assigned to the correct subset. </p>
<p>Example is searching for a word in an English dictionary, first subsetting the dictionary into 26 "ABCD" sections based on each word's initials. If the query is "apple", you only need to search the "A" section. The advantage of this is that you have greatly limited the search space and hence the speed boost.</p>
<p>For numerical list, either subset it based on range, or on the first digit.</p>
<p>Hope this helps.</p>
| 0 | 2016-08-22T21:41:02Z | [
"python",
"list",
"optimization",
"set"
] |
Python sort multiple lists by date and print list names | 39,089,005 | <p>Working in Python 3.5.2 I have four lists of dates, each in ascending order, where the lists are not of equal length. Each list of dates is generated by a lookup into a longer list of dates. A sample date value and data type is shown below:</p>
<pre><code>In: print (date, type(date))
Out: 725722.0 <class 'numpy.float64'>
</code></pre>
<p>I build each list of dates using a respective loop. To see the values I convert to strings and print each list. So I could sort with data type as numpy float64 or convert to string. Relevant values of actual data in each list (based on specific filter settings) are shown below:</p>
<pre><code>a = [12-17-1987, 11-22-1989, 03-05-1990, 11-12-1990]
b = [12-16-1987, 03-02-1990, 11-12-1990]
c = [10-09-1986, 12-16-1987, 03-05-1990, 11-12-1990]
d = [10-16-1985, 08-20-1986, 10-15-1986, 12-16-1987, 03-02-1990]
</code></pre>
<p>I need to sort dates from all four lists in ascending order by mm-dd-yyyy, print each date, and beside each date print the name of the respective list, as shown in the example below: </p>
<pre><code># Desired Printout
10-16-1985 d
08-20-1986 d
10-09-1986 c
10-15-1986 d
12-16-1987 b
12-16-1987 c
12-16-1987 d
12-17-1987 a
11-22-1989 a
03-02-1990 b
03-02-1990 d
03-05-1990 a
03-05-1990 c
11-12-1990 a
11-12-1990 b
11-12-1990 c
</code></pre>
<p>This will give me visual confirmation of a sequence of events in four different sets of data. I would try to create a dictionary and sort by date for print to screen or disk but I have noticed similar answers using map or lambda functions that may provide a more elegant solution. If I am storing this information on disk what is the best data structure and solution?</p>
| 0 | 2016-08-22T21:27:25Z | 39,089,077 | <p>You honestly don't need anything that fancy. Just do a min on the first item in every list. Then check if the value that is the min is in any of the lists and do a list.pop() and a print then. That's a simple way to do it that is efficient and makes sense. I could provide you the code but this should be clear enough.</p>
| -2 | 2016-08-22T21:33:37Z | [
"python",
"list",
"sorting"
] |
Python sort multiple lists by date and print list names | 39,089,005 | <p>Working in Python 3.5.2 I have four lists of dates, each in ascending order, where the lists are not of equal length. Each list of dates is generated by a lookup into a longer list of dates. A sample date value and data type is shown below:</p>
<pre><code>In: print (date, type(date))
Out: 725722.0 <class 'numpy.float64'>
</code></pre>
<p>I build each list of dates using a respective loop. To see the values I convert to strings and print each list. So I could sort with data type as numpy float64 or convert to string. Relevant values of actual data in each list (based on specific filter settings) are shown below:</p>
<pre><code>a = [12-17-1987, 11-22-1989, 03-05-1990, 11-12-1990]
b = [12-16-1987, 03-02-1990, 11-12-1990]
c = [10-09-1986, 12-16-1987, 03-05-1990, 11-12-1990]
d = [10-16-1985, 08-20-1986, 10-15-1986, 12-16-1987, 03-02-1990]
</code></pre>
<p>I need to sort dates from all four lists in ascending order by mm-dd-yyyy, print each date, and beside each date print the name of the respective list, as shown in the example below: </p>
<pre><code># Desired Printout
10-16-1985 d
08-20-1986 d
10-09-1986 c
10-15-1986 d
12-16-1987 b
12-16-1987 c
12-16-1987 d
12-17-1987 a
11-22-1989 a
03-02-1990 b
03-02-1990 d
03-05-1990 a
03-05-1990 c
11-12-1990 a
11-12-1990 b
11-12-1990 c
</code></pre>
<p>This will give me visual confirmation of a sequence of events in four different sets of data. I would try to create a dictionary and sort by date for print to screen or disk but I have noticed similar answers using map or lambda functions that may provide a more elegant solution. If I am storing this information on disk what is the best data structure and solution?</p>
| 0 | 2016-08-22T21:27:25Z | 39,089,161 | <pre><code># Create the list of all dates, combining the four lists you have. Keep
# the information about which list value comes from
all_dates = [(x, 'a') for x in a] + [(x, 'b') for x in b] + [(x, 'c') for x in c] + [(x, 'd') for x in d]
# Sort with key a simple date parser. The way it works is:
# 1. It takes a date 11-12-2012 and splits it by '-' so that we get ['11', '12', '2012']
# 2. Reverses the list ([::-1]) so that the year is the most significant (['2012', '12', '11'])
# 3. Applies int to each so that they are compared as numbers ([2012, 12, 11]). Note that Python can automatically compare things like that
all_dates.sort(key = lambda x: list(map(int, x[0].split('-')[::-1])))
# Print the result
for date in all_dates:
print ' '.join(date)
</code></pre>
| -1 | 2016-08-22T21:40:21Z | [
"python",
"list",
"sorting"
] |
Python sort multiple lists by date and print list names | 39,089,005 | <p>Working in Python 3.5.2 I have four lists of dates, each in ascending order, where the lists are not of equal length. Each list of dates is generated by a lookup into a longer list of dates. A sample date value and data type is shown below:</p>
<pre><code>In: print (date, type(date))
Out: 725722.0 <class 'numpy.float64'>
</code></pre>
<p>I build each list of dates using a respective loop. To see the values I convert to strings and print each list. So I could sort with data type as numpy float64 or convert to string. Relevant values of actual data in each list (based on specific filter settings) are shown below:</p>
<pre><code>a = [12-17-1987, 11-22-1989, 03-05-1990, 11-12-1990]
b = [12-16-1987, 03-02-1990, 11-12-1990]
c = [10-09-1986, 12-16-1987, 03-05-1990, 11-12-1990]
d = [10-16-1985, 08-20-1986, 10-15-1986, 12-16-1987, 03-02-1990]
</code></pre>
<p>I need to sort dates from all four lists in ascending order by mm-dd-yyyy, print each date, and beside each date print the name of the respective list, as shown in the example below: </p>
<pre><code># Desired Printout
10-16-1985 d
08-20-1986 d
10-09-1986 c
10-15-1986 d
12-16-1987 b
12-16-1987 c
12-16-1987 d
12-17-1987 a
11-22-1989 a
03-02-1990 b
03-02-1990 d
03-05-1990 a
03-05-1990 c
11-12-1990 a
11-12-1990 b
11-12-1990 c
</code></pre>
<p>This will give me visual confirmation of a sequence of events in four different sets of data. I would try to create a dictionary and sort by date for print to screen or disk but I have noticed similar answers using map or lambda functions that may provide a more elegant solution. If I am storing this information on disk what is the best data structure and solution?</p>
| 0 | 2016-08-22T21:27:25Z | 39,089,346 | <p>Assuming your dates are all formatted as <code>mm-dd-yyyy</code> (unlike your example), this should do the trick:</p>
<pre><code>import itertools
lists = dict(a=['7-1-1987', '1-1-1990'],
b=['7-2-1987', '1-5-1990'],
c=['7-1-1987', '1-3-1990'],
d=['1-10-1985', '7-10-1986'])
for d, v in sorted(itertools.chain(*([(e, n) for e in v] for n, v in lists.items()))):
print d, v
</code></pre>
<p>If the dates aren't formatted properly, then you'd have to add a custom sorting key to the <code>sorted</code> function to parse the date into a properly comparable objects.</p>
| 0 | 2016-08-22T21:57:07Z | [
"python",
"list",
"sorting"
] |
Python sort multiple lists by date and print list names | 39,089,005 | <p>Working in Python 3.5.2 I have four lists of dates, each in ascending order, where the lists are not of equal length. Each list of dates is generated by a lookup into a longer list of dates. A sample date value and data type is shown below:</p>
<pre><code>In: print (date, type(date))
Out: 725722.0 <class 'numpy.float64'>
</code></pre>
<p>I build each list of dates using a respective loop. To see the values I convert to strings and print each list. So I could sort with data type as numpy float64 or convert to string. Relevant values of actual data in each list (based on specific filter settings) are shown below:</p>
<pre><code>a = [12-17-1987, 11-22-1989, 03-05-1990, 11-12-1990]
b = [12-16-1987, 03-02-1990, 11-12-1990]
c = [10-09-1986, 12-16-1987, 03-05-1990, 11-12-1990]
d = [10-16-1985, 08-20-1986, 10-15-1986, 12-16-1987, 03-02-1990]
</code></pre>
<p>I need to sort dates from all four lists in ascending order by mm-dd-yyyy, print each date, and beside each date print the name of the respective list, as shown in the example below: </p>
<pre><code># Desired Printout
10-16-1985 d
08-20-1986 d
10-09-1986 c
10-15-1986 d
12-16-1987 b
12-16-1987 c
12-16-1987 d
12-17-1987 a
11-22-1989 a
03-02-1990 b
03-02-1990 d
03-05-1990 a
03-05-1990 c
11-12-1990 a
11-12-1990 b
11-12-1990 c
</code></pre>
<p>This will give me visual confirmation of a sequence of events in four different sets of data. I would try to create a dictionary and sort by date for print to screen or disk but I have noticed similar answers using map or lambda functions that may provide a more elegant solution. If I am storing this information on disk what is the best data structure and solution?</p>
| 0 | 2016-08-22T21:27:25Z | 39,089,492 | <p>I have a couple comments on this one:</p>
<ol>
<li><p>"Best" is ambiguous. It could mean minimized algorithmic complexity, minimized runtime, minimized memory usage, simplest to implement or read, least amount of code, etc.</p></li>
<li><p>Unless you have thousands of entries, it might not be worth optimizing your data structure or algorithm. The community's accepted best practice is to profile and optimize what's slow about your entire program.</p></li>
</ol>
<p>A simple implementation could be nothing more than joining the lists and sorting them with the <code>sorted</code> built-in. For example, here are a few options you might consider for sorting:</p>
<pre><code>import datetime
a = ['7-1-1987', '1-1-1990']
b = ['7-2-1987', '1-5-1990']
c = ['7-1-1987', '1-3-1990']
d = ['1-10-1985', '7-10-1986']
# hold on to list name
a = [(i, 'a') for i in a] # [(date, list_name), ...]
b = [(i, 'b') for i in b]
c = [(i, 'c') for i in c]
d = [(i, 'd') for i in d]
dates = a + b + c + d # combine into one flat list
for i in dates: print(i)
</code></pre>
<p>Output</p>
<pre><code>('7-1-1987', 'a')
('1-1-1990', 'a')
('7-2-1987', 'b')
('1-5-1990', 'b')
('7-1-1987', 'c')
('1-3-1990', 'c')
('1-10-1985', 'd')
('7-10-1986', 'd')
</code></pre>
<p><strong>Approach 1</strong> - Parse each date string to a datetime object, sort them in place, and output a list of datetime objects.</p>
<pre><code>dates_1 = [(datetime.datetime.strptime(d, '%m-%d-%Y').date(), l) for d, l in dates]
dates_1.sort()
for i in dates_1: print(i)
</code></pre>
<p>Output</p>
<pre><code>(datetime.date(1985, 1, 10), 'd')
(datetime.date(1986, 7, 10), 'd')
(datetime.date(1987, 7, 1), 'a')
(datetime.date(1987, 7, 1), 'c')
(datetime.date(1987, 7, 2), 'b')
(datetime.date(1990, 1, 1), 'a')
(datetime.date(1990, 1, 3), 'c')
(datetime.date(1990, 1, 5), 'b')
</code></pre>
<p><strong>Approach 2</strong> - Sort the dates using a lambda function that parses them on the fly, and output a (new) list of strings.</p>
<pre><code>dates_2 = sorted(dates, key=lambda d: (datetime.datetime.strptime(d[0], '%m-%d-%Y').date(), d[1]))
for i in dates_2: print(i)
</code></pre>
<p>Output</p>
<pre><code>('1-10-1985', 'd')
('7-10-1986', 'd')
('7-1-1987', 'a')
('7-1-1987', 'c')
('7-2-1987', 'b')
('1-1-1990', 'a')
('1-3-1990', 'c')
('1-5-1990', 'b')
</code></pre>
<p><strong>Approach 3</strong> - Use heapq.merge to sort more efficiently. Credit to @friendlydog for the suggestion.</p>
<pre><code>import datetime
import heapq
a = ['7-1-1987', '1-1-1990']
b = ['7-2-1987', '1-5-1990']
c = ['7-1-1987', '1-3-1990']
d = ['1-10-1985', '7-10-1986']
def strs_to_dates(date_strs, list_name):
"""
Convert a list of date strings to a generator of (date, str) tuples.
"""
return ((datetime.datetime.strptime(date, '%m-%d-%Y').date(), list_name) for date in date_strs)
a = strs_to_dates(a, 'a')
b = strs_to_dates(b, 'b')
c = strs_to_dates(c, 'c')
d = strs_to_dates(d, 'd')
dates_3 = heapq.merge(a, b, c, d)
for i in dates_3: print(i)
</code></pre>
<p>Output</p>
<pre><code>(datetime.date(1985, 1, 10), 'd')
(datetime.date(1986, 7, 10), 'd')
(datetime.date(1987, 7, 1), 'a')
(datetime.date(1987, 7, 1), 'c')
(datetime.date(1987, 7, 2), 'b')
(datetime.date(1990, 1, 1), 'a')
(datetime.date(1990, 1, 3), 'c')
(datetime.date(1990, 1, 5), 'b')
</code></pre>
<p>Notes:</p>
<ol>
<li>I assumed the format of your input strings is 'day-month-year'.</li>
<li>I assumed when the same date is in multiple lists, that you'd want to secondarily sort alphanumerically by list name.</li>
<li>I left formatting the output list as an exercise for the reader.</li>
<li>Both examples working under Python 2 / 3.</li>
</ol>
<p>In this example, the <code>key</code> argument is a lambda. Without that it would sort the strings alphabetically. This lets us override that and sort by year > month > day.</p>
<p>A more elaborate implementation could take advantage of the guarantee that the lists are pre-sorted. Wikipedia has a list of <a href="https://en.wikipedia.org/wiki/Merge_algorithm" rel="nofollow">merge algorithms</a> to consider.</p>
| 3 | 2016-08-22T22:09:55Z | [
"python",
"list",
"sorting"
] |
Can you spawn a child process written in a different language than a Python or PHP server, like you would with Node.js? | 39,089,057 | <p>What are the Python (Tornado/Flask/etc) or Apache/PHP ways of spawning a child process to run a script written in a different programming language than Python or PHP, and communicate with the server over standard input and output?</p>
<p>I'm looking for the Python/PHP equivalent to Node.js "child_process" library. I'm a Node.js programmer trying to justify using it on our company's infrastructure, and one major perk for our industry (research science) is that I would be able to use scripts written in Python and R seamlessly with a Node.js server. Before I claim that we NEED Node.js to have this benefit I want to make sure you can't do the same with a Python or PHP based server.</p>
<p>I'm not quite sure how to search for this</p>
| 1 | 2016-08-22T21:31:34Z | 39,089,091 | <p>The language of the spawning process isn't relevant to the language of the spawned process. This is not a feature of Node.JS, PHP, or Python, this is a feature of the operating system.</p>
<p>In python, for example, one uses calls from the <code>subprocess</code> module. Here is an example of a Python script calling a C program:</p>
<pre><code>files = subprocess.check_output(['/bin/ls', '/tmp'])
</code></pre>
| 1 | 2016-08-22T21:34:48Z | [
"javascript",
"php",
"python",
"node.js",
"child-process"
] |
Calling exists() in sqlalchemy with multiple values in python | 39,089,153 | <p>I am trying to find out if there is any nicer way I can check if a table
of users contains a group of names instead of checking them one at a time</p>
<p>This is what I am using to currently check the User table one at a time which gives me True or False if the user exists in the table:</p>
<pre><code>ret = session.query(exists().where(Users.name == 'Jack')).scalar()
</code></pre>
<p>So is there a way to do this:</p>
<pre><code>ret = session.query(exists().where(Users.name == 'Jack', 'Bob', 'Sandy')).scalar()
</code></pre>
<p>Rather than this:</p>
<pre><code>ret1 = session.query(exists().where(Users.name == 'Jack')).scalar()
ret2 = session.query(exists().where(Users.name == 'Bob')).scalar()
ret3 = session.query(exists().where(Users.name == 'Sandy')).scalar()
</code></pre>
| 1 | 2016-08-22T21:39:45Z | 39,089,332 | <p>You are correct to use the <code>exists()</code> expression, but combine it with a subquery that leverages the <code>in_()</code> expression.
</p>
<pre><code>q = session.query(Users).filter(Users.name.in_(['Jack', 'Bob', 'Sandy']))
# Below will return True or False
at_least_one_user_exists = session.query(q.exists()).scalar()
</code></pre>
<p>This translates to the following SQL:</p>
<pre><code>SELECT EXISTS (
SELECT 1 FROM users WHERE users.name IN ('Jack', 'Bob', 'Sandy')
) AS anon_1
</code></pre>
<p>...only the SQLAlchemy described above query will return <code>True</code> or <code>False</code></p>
| 1 | 2016-08-22T21:55:56Z | [
"python",
"mysql",
"sqlalchemy"
] |
How to not let text overlap each other in pygame? | 39,089,185 | <p>i have two text examples, but they just appear on top of each other. how do i make it so that the second one replaces the first?</p>
<pre><code>if player_x_coor <= -2750:
text = font.render("text 1", True, WHITE)
screen.blit(text, [100, 150])
if player_x_coor <= -6310:
text = font.render("text 2", True, WHITE)
screen.blit(text, [100, 150])
</code></pre>
<p>as you can see, I tried to replace the first text with the second text by assigning <code>text = font.render("text 2", ...)</code></p>
<p>but the first test still shows so that the second overlaps with it.</p>
| 1 | 2016-08-22T21:42:57Z | 39,089,370 | <p>You need to erase the first text before writing another.</p>
<p>See this similar questions <a href="http://stackoverflow.com/questions/20655828/new-text-rendered-over-older-text-in-pygame">here</a> and <a href="http://stackoverflow.com/questions/6795644/what-is-the-correct-sequence-for-bliting-surfaces-to-the-screen-in-pygame">here</a>. </p>
<p>I think there are many ways to do what you want. The best way could be: </p>
<ul>
<li>copy the current surface (without text) in a cache</li>
<li>render the text</li>
<li>blit the text in your cached surface</li>
</ul>
| -1 | 2016-08-22T21:59:31Z | [
"python",
"text",
"pygame"
] |
How to not let text overlap each other in pygame? | 39,089,185 | <p>i have two text examples, but they just appear on top of each other. how do i make it so that the second one replaces the first?</p>
<pre><code>if player_x_coor <= -2750:
text = font.render("text 1", True, WHITE)
screen.blit(text, [100, 150])
if player_x_coor <= -6310:
text = font.render("text 2", True, WHITE)
screen.blit(text, [100, 150])
</code></pre>
<p>as you can see, I tried to replace the first text with the second text by assigning <code>text = font.render("text 2", ...)</code></p>
<p>but the first test still shows so that the second overlaps with it.</p>
| 1 | 2016-08-22T21:42:57Z | 39,093,644 | <p>When you draw onto the screen, everything that is already there doesn't clear on its own. You have to blank the screen using some color, let's say black. Once the screen is clear of previous frame, you can redraw each object from bottom to top.</p>
<p>It is possible, if say you have a simple square underneath the text you're trying to replace, to just draw that square (instead of redrawing whole screen), and then draw new text. But this becomes more complicated if you're not dealing with a small number of trival shapes.</p>
<p>In general, a game loop is used to redraw the frame <code>x</code> times a second. The pattern is as follows:</p>
<pre><code>def game_loop():
BLACK = (0, 0, 0)
while True:
# Do this loop, at maximum, 50 times a second
clock.tick(50)
# Clear screen
screen.fill(BLACK)
# Draw background
# characters
# user interface
# Get user input
</code></pre>
| 2 | 2016-08-23T06:16:09Z | [
"python",
"text",
"pygame"
] |
TypeError: __init__() got an unexpected keyword argument 'size | 39,089,253 | <p>How do i fix this unexpected keyword argument 'size'? </p>
<hr>
<pre><code> Traceback (most recent call last):
File "H:\Documents\Astro game\astro games6.py", line 73, in <module>
main()
File "H:\Documents\Astro game\astro games6.py", line 61, in main
new_asteroid = Asteroid(x = x, y = y,size = size)
TypeError: __init__() got an unexpected keyword argument 'size'
</code></pre>
<hr>
<p>The full code: </p>
<pre><code>import random
from superwires import games
games.init(screen_width = 640, screen_height = 480, fps = 50)
class Asteroid(games.Sprite):
""" An asteroid wich floats across the screen"""
SMALL = 1
MEDIUM = 2
LARGE = 3
images = {SMALL : games.load_image("asteroid_small.bmp"),
MEDIUM : games.load_image("asteroid_med.bmp"),
LARGE : games.load_image("asteroid_big.bmp")}
speed = 2
def _init_(self, x, y, size):
"""Initialize asteroid sprite"""
super(Asteroid, self)._init_(
image = Asteroid.images[size],
x = x, y = y,
dx = random.choice([1, -1]) *Asteroid.SPEED* random.random()/size,
dy = random.choice([1, -1]) *Asteroid.SPEED* random.random()/size)
self.size = size
def update (self):
""" Warp around screen"""
if self.top>games.screen.height:
self.bottom = 0
if self.bottom < 0:
self.top=games.screen.height
if self.left > games.screen.width:
self.right = 0
if self.left < 0:
self.left = games.screen.width
class Ship(games.Sprite):
"""The player's ship"""
image = games.load_image("ship.bmp")
ROTATION_STEP = 3
def update(self):
if games.keyboard.is_pressed(games.K_LEFT):
self.angle -= Ship.ROTATION_STEP
if games.keyboard.is_pressed(games.K_RIGHT):
self.angle += Ship.ROTATION_STEP
def main():
nebula_image = games.load_image("nebula.jpg")
games.screen.background = nebula_image
for i in range(8):
x = random.randrange(games.screen.width)
y = random.randrange(games.screen.height)
size = random.choice([Asteroid.SMALL, Asteroid.MEDIUM, Asteroid.LARGE])
new_asteroid = Asteroid(x = x, y = y,size = size)
games.screen.add(new_asteroid)
the_ship = Ship(image = Ship.image,
x = games.screen.width/2,
y = games.screen.height/2)
games.screen.add(the_ship)
games.screen.mainloop()
main()
</code></pre>
<hr>
<p>I have tried removing the size argument but it caused more errors in the code. We also tried changing the size tag to something else to see if that helps and it didn't work either. So I'm stuff for what I need to do to make this code work. I am working on it for a class project in school. English is not my first language so I have had a classmate write this up.</p>
<p>Thank you.</p>
| -3 | 2016-08-22T21:49:30Z | 39,089,340 | <p>Remove the <code>size</code> argument in your code.</p>
<p><em>note: a Python module name shouldn't have a space: you won't be able to import it in another module.</em></p>
| -2 | 2016-08-22T21:56:52Z | [
"python"
] |
TypeError: __init__() got an unexpected keyword argument 'size | 39,089,253 | <p>How do i fix this unexpected keyword argument 'size'? </p>
<hr>
<pre><code> Traceback (most recent call last):
File "H:\Documents\Astro game\astro games6.py", line 73, in <module>
main()
File "H:\Documents\Astro game\astro games6.py", line 61, in main
new_asteroid = Asteroid(x = x, y = y,size = size)
TypeError: __init__() got an unexpected keyword argument 'size'
</code></pre>
<hr>
<p>The full code: </p>
<pre><code>import random
from superwires import games
games.init(screen_width = 640, screen_height = 480, fps = 50)
class Asteroid(games.Sprite):
""" An asteroid wich floats across the screen"""
SMALL = 1
MEDIUM = 2
LARGE = 3
images = {SMALL : games.load_image("asteroid_small.bmp"),
MEDIUM : games.load_image("asteroid_med.bmp"),
LARGE : games.load_image("asteroid_big.bmp")}
speed = 2
def _init_(self, x, y, size):
"""Initialize asteroid sprite"""
super(Asteroid, self)._init_(
image = Asteroid.images[size],
x = x, y = y,
dx = random.choice([1, -1]) *Asteroid.SPEED* random.random()/size,
dy = random.choice([1, -1]) *Asteroid.SPEED* random.random()/size)
self.size = size
def update (self):
""" Warp around screen"""
if self.top>games.screen.height:
self.bottom = 0
if self.bottom < 0:
self.top=games.screen.height
if self.left > games.screen.width:
self.right = 0
if self.left < 0:
self.left = games.screen.width
class Ship(games.Sprite):
"""The player's ship"""
image = games.load_image("ship.bmp")
ROTATION_STEP = 3
def update(self):
if games.keyboard.is_pressed(games.K_LEFT):
self.angle -= Ship.ROTATION_STEP
if games.keyboard.is_pressed(games.K_RIGHT):
self.angle += Ship.ROTATION_STEP
def main():
nebula_image = games.load_image("nebula.jpg")
games.screen.background = nebula_image
for i in range(8):
x = random.randrange(games.screen.width)
y = random.randrange(games.screen.height)
size = random.choice([Asteroid.SMALL, Asteroid.MEDIUM, Asteroid.LARGE])
new_asteroid = Asteroid(x = x, y = y,size = size)
games.screen.add(new_asteroid)
the_ship = Ship(image = Ship.image,
x = games.screen.width/2,
y = games.screen.height/2)
games.screen.add(the_ship)
games.screen.mainloop()
main()
</code></pre>
<hr>
<p>I have tried removing the size argument but it caused more errors in the code. We also tried changing the size tag to something else to see if that helps and it didn't work either. So I'm stuff for what I need to do to make this code work. I am working on it for a class project in school. English is not my first language so I have had a classmate write this up.</p>
<p>Thank you.</p>
| -3 | 2016-08-22T21:49:30Z | 39,089,593 | <p>Your Asteroid class defines <code>_init_</code> instead of <code>__init__</code>. You need two underscores on either side for Python magic methods.</p>
| 0 | 2016-08-22T22:21:01Z | [
"python"
] |
Passing DTS variable inside python script in ssis | 39,089,336 | <p>I am trying to using a python script using the "Execute Task" tool in ssis.However, i am not sure if i will be able to use one of the runtime variable inside the python script. Eg:</p>
<pre><code>#inputval.py
inputval = dts.value("test").toString()
print(inputval)
</code></pre>
<p>Is there any chance ? . Thanks in advance for the help. </p>
| 0 | 2016-08-22T21:56:28Z | 39,089,627 | <p>Yes you can reference the value but not in that manner.</p>
<p>Python won't have access to the Variables collection so you'll have to use a different method for communication. The <a href="https://msdn.microsoft.com/en-us/library/ms141166.aspx" rel="nofollow">Execute Package Task</a> supports either a Variable for Standard Input or for Arguments. Either one should work</p>
<p>Within your python script, you'll need to work with the <code>sys.argv</code> collection (code approximate based on 2.7 recollections with 3.0 print flair)</p>
<pre><code>for inputval in sys.argv:
print (inputval)
</code></pre>
<p>or skipping the first element, we'd have something like</p>
<pre><code># we can skip the first element since that is name of script
for inputval in sys.argv[1:]
print (inputval)
</code></pre>
| 1 | 2016-08-22T22:24:58Z | [
"python",
"ssis",
"ssis-2008"
] |
Return to a function if file was not detected. (Python) | 39,089,355 | <p>So I made a retrieve if a file was found with this code:</p>
<pre><code>try:
with open('Kappa.txt') as file:
passexcept IOError as e:
print "Unable to open/detect file."
</code></pre>
<p>That works fine. So before that function the user can enter a path where this txt file is located on his computer. If Kappa.txt was not found in the directory which the user typed in, the retrieve above should return to the Path-entering function so the user can enter another Path but how? </p>
<p>The Path-entering function looks like that:</p>
<pre><code>Path = raw_input("blalblablablablablalb")
</code></pre>
| 0 | 2016-08-22T21:58:19Z | 39,089,427 | <p>There is not much point in doing try - except here. You can easily check if file exists and proceed only if that is the case.</p>
<pre><code>import os
file_name = raw_input("File name: ")
# Until the file user enters is existing, keep asking
while not os.path.isfile(file_name):
file_name = raw_input("File name: ")
# At this point you are guaranteed to have a valid path
with open(file_name, 'r') as f:
...
</code></pre>
<hr>
<p>If for some reason it is very important for you to do it as try-except, <strong>nut this is much worse code, really</strong>:</p>
<pre><code>filename = raw_input("File name: ")
file_succesfully_opened = False
while not file_succesfully_opened:
try:
file_succesfully_opened = True
with open(filename, 'r') as f:
...
except IOError as e:
filename = raw_input("File name: ")
</code></pre>
| 0 | 2016-08-22T22:03:08Z | [
"python"
] |
Return to a function if file was not detected. (Python) | 39,089,355 | <p>So I made a retrieve if a file was found with this code:</p>
<pre><code>try:
with open('Kappa.txt') as file:
passexcept IOError as e:
print "Unable to open/detect file."
</code></pre>
<p>That works fine. So before that function the user can enter a path where this txt file is located on his computer. If Kappa.txt was not found in the directory which the user typed in, the retrieve above should return to the Path-entering function so the user can enter another Path but how? </p>
<p>The Path-entering function looks like that:</p>
<pre><code>Path = raw_input("blalblablablablablalb")
</code></pre>
| 0 | 2016-08-22T21:58:19Z | 39,089,457 | <p>Do an infinite loop:</p>
<pre><code>while True:
try:
filename = raw_input("File: ")
with io.open(filename, encoding='utf8') as fd:
content = fd.read()
break
except IOError:
print("retry!")
</code></pre>
| 0 | 2016-08-22T22:06:14Z | [
"python"
] |
Linear regression in theano | 39,089,357 | <p>What is the significance of <code>T.mean</code> in <a href="https://github.com/Newmu/Theano-Tutorials/blob/master/1_linear_regression.py" rel="nofollow">this example</a>? I think <code>T.mean</code> would have made sense if the implementation were vectorized. Here the inputs <code>x</code> and <code>y</code> to <code>train(x, y)</code> are scalars, and <code>cost</code> only finds squared error of a single input, and iterates over the data. </p>
<pre><code>cost = T.mean(T.sqr(y - Y))
gradient = T.grad(cost=cost, wrt=w)
updates = [[w, w - gradient * 0.01]]
train = theano.function(inputs=[X, Y], outputs=cost, updates=updates, allow_input_downcast=True)
for i in range(100):
for x, y in zip(trX, trY):
train(x, y)
print w.get_value()
</code></pre>
<p>Removing <code>T.mean</code> had no impact on the output pattern.</p>
| 1 | 2016-08-22T21:58:21Z | 39,089,694 | <p>You are right, <code>T.mean</code> has no significance here. The cost function operates on a single training sample at once, so the "mean squared error" is really just the squared error of the sample.</p>
<p>This example implements linear regression via <a href="https://en.wikipedia.org/wiki/Stochastic_gradient_descent" rel="nofollow">stochastic gradient descent</a>, an algorithm for online optimization. SGD iterates over samples one-by-one, as is the case in this example. However, in more complex scenarios, the dataset is often <a href="https://en.wikipedia.org/wiki/Stochastic_gradient_descent#Iterative_method" rel="nofollow">processed in mini-batches</a>, which gives better performance and convergence properties.</p>
<p>I think that <code>T.mean</code> was left in the example as an artifact of mini-batch gradient descent, or to make it more explicit that the cost function is MSE.</p>
| 1 | 2016-08-22T22:31:17Z | [
"python",
"theano"
] |
Replacing keywords in parentheses with user input | 39,089,397 | <p>So, I'm making a little Python 3 applet for madlibs. So far, I have it so that it reads a text file, pulls a random story from it, and splits that story into a list for search through it. That all works great. I have the stories formatted so that, where words are needed, it uses (noun), (adverb), (name), et cetera. However, I have some issues with replacing those strings. Here is an example:</p>
<pre><code>>>> for i in range(0,len(poss)):
... if '(' in poss[i]: poss[i] = input('{0}: '.format(poss[i].replace('(','').replace(')','')))
...
noun: monster
name.: Strange
name: Strange
adjective: yellow
noun!: eatery
place.
: Times Square
>>> poss = ' '.join(poss)
>>> print(poss)
Back to the Future
Marty was an innocent, young monster and made friends with the local scientist,
Doc Strange Doc Strange was a bit off, but he was one yellow genius. One day,
he told Marty that he had an invented a eatery Of course, Marty had to see it
in action. Late that night, they met at Times Square
</code></pre>
<p>It searches for the '(' character in each object, and then replaces the whole object with the word. It doesn't preserve the punctuation that might be involved. Also, you can see that the punctuation/newline characters are left over and shown when <code>input()</code> is called. How can I effectively replace just the substrings contained within the parenthesis?</p>
<p>For reference, here is the original text that was pulled from the file:</p>
<pre><code> Back to the Future
Marty was an innocent, young (noun) and made friends with the local scientist,
Doc (name). Doc (name) was a bit off, but he was one (adjective) genius. One day,
he told Marty that he had an invented a (noun)! Of course, Marty had to see it
in action. Late that night, they met at (place).
</code></pre>
<p>and my intended result is:</p>
<pre><code> Back to the Future
Marty was an innocent, young monster and made friends with the local scientist,
Doc Strange. Doc Strange was a bit off, but he was one yellow genius. One day,
he told Marty that he had an invented a eatery! Of course, Marty had to see it
in action. Late that night, they met at Times Square.
</code></pre>
| 0 | 2016-08-22T22:01:05Z | 39,089,558 | <p>To address the problems with your approach I'd need to see the full code, but I have another suggestion.</p>
<p>You can actually use the regular expressions here, which allows making the substitution in a one-liner (almost).</p>
<pre><code>In [1]: import re
In [2]: story = ''' Back to the Future
...:
...: Marty was an innocent, young (noun) and made friends with the local scientist,
...: Doc (name). Doc (name) was a bit off, but he was one (adjective) genius. One day,
...: he told Marty that he had an invented a (noun)! Of course, Marty had to see it
...: in action. Late that night, they met at (place).'''
In [3]: def replace(match):
...: return input('{}: '.format(match.group()))
...:
In [4]: print(re.sub('\((noun|name|adjective|place)\)', replace, story))
(noun): monster
(name): Strange
(name): Strange
(adjective): yellow
(noun): eatery
(place): Times Square
Back to the Future
Marty was an innocent, young monster and made friends with the local scientist,
Doc Strange. Doc Strange was a bit off, but he was one yellow genius. One day,
he told Marty that he had an invented a eatery! Of course, Marty had to see it
in action. Late that night, they met at Times Square.
</code></pre>
<p><a href="https://docs.python.org/3/library/re.html#re.sub" rel="nofollow"><code>re.sub()</code></a> accepts a callable as replacement, which we use to call <code>input()</code> with the prompt extracted from the match.</p>
<p><strong>Edit:</strong> to match any phrase in brackets, you can just change the pattern, e.g.:</p>
<pre><code>print(re.sub('\(([^()]*)\)', replace, story))
</code></pre>
| 2 | 2016-08-22T22:17:45Z | [
"python"
] |
Replacing keywords in parentheses with user input | 39,089,397 | <p>So, I'm making a little Python 3 applet for madlibs. So far, I have it so that it reads a text file, pulls a random story from it, and splits that story into a list for search through it. That all works great. I have the stories formatted so that, where words are needed, it uses (noun), (adverb), (name), et cetera. However, I have some issues with replacing those strings. Here is an example:</p>
<pre><code>>>> for i in range(0,len(poss)):
... if '(' in poss[i]: poss[i] = input('{0}: '.format(poss[i].replace('(','').replace(')','')))
...
noun: monster
name.: Strange
name: Strange
adjective: yellow
noun!: eatery
place.
: Times Square
>>> poss = ' '.join(poss)
>>> print(poss)
Back to the Future
Marty was an innocent, young monster and made friends with the local scientist,
Doc Strange Doc Strange was a bit off, but he was one yellow genius. One day,
he told Marty that he had an invented a eatery Of course, Marty had to see it
in action. Late that night, they met at Times Square
</code></pre>
<p>It searches for the '(' character in each object, and then replaces the whole object with the word. It doesn't preserve the punctuation that might be involved. Also, you can see that the punctuation/newline characters are left over and shown when <code>input()</code> is called. How can I effectively replace just the substrings contained within the parenthesis?</p>
<p>For reference, here is the original text that was pulled from the file:</p>
<pre><code> Back to the Future
Marty was an innocent, young (noun) and made friends with the local scientist,
Doc (name). Doc (name) was a bit off, but he was one (adjective) genius. One day,
he told Marty that he had an invented a (noun)! Of course, Marty had to see it
in action. Late that night, they met at (place).
</code></pre>
<p>and my intended result is:</p>
<pre><code> Back to the Future
Marty was an innocent, young monster and made friends with the local scientist,
Doc Strange. Doc Strange was a bit off, but he was one yellow genius. One day,
he told Marty that he had an invented a eatery! Of course, Marty had to see it
in action. Late that night, they met at Times Square.
</code></pre>
| 0 | 2016-08-22T22:01:05Z | 39,089,622 | <pre><code>text = """Marty was an innocent, young (noun) and made friends with the local scientist,
Doc (name). Doc (name) was a bit off, but he was one (adjective) genius. One day,
he told Marty that he had an invented a (noun)! Of course, Marty had to see it
in action. Late that night, they met at (place)."""
match = ['monster', 'Strange', 'Strange', 'yellow', 'eatery', 'Times Square']
splitted = text.split()
for i, item in enumerate(splitted):
if '(' in item:
matched = match.pop(0)
if not item.endswith(')'):
matched = '{}{}'.format(matched, item[:-1])
splitted[i] = matched
print ' '.join(splitted)
</code></pre>
| 0 | 2016-08-22T22:24:24Z | [
"python"
] |
Replacing keywords in parentheses with user input | 39,089,397 | <p>So, I'm making a little Python 3 applet for madlibs. So far, I have it so that it reads a text file, pulls a random story from it, and splits that story into a list for search through it. That all works great. I have the stories formatted so that, where words are needed, it uses (noun), (adverb), (name), et cetera. However, I have some issues with replacing those strings. Here is an example:</p>
<pre><code>>>> for i in range(0,len(poss)):
... if '(' in poss[i]: poss[i] = input('{0}: '.format(poss[i].replace('(','').replace(')','')))
...
noun: monster
name.: Strange
name: Strange
adjective: yellow
noun!: eatery
place.
: Times Square
>>> poss = ' '.join(poss)
>>> print(poss)
Back to the Future
Marty was an innocent, young monster and made friends with the local scientist,
Doc Strange Doc Strange was a bit off, but he was one yellow genius. One day,
he told Marty that he had an invented a eatery Of course, Marty had to see it
in action. Late that night, they met at Times Square
</code></pre>
<p>It searches for the '(' character in each object, and then replaces the whole object with the word. It doesn't preserve the punctuation that might be involved. Also, you can see that the punctuation/newline characters are left over and shown when <code>input()</code> is called. How can I effectively replace just the substrings contained within the parenthesis?</p>
<p>For reference, here is the original text that was pulled from the file:</p>
<pre><code> Back to the Future
Marty was an innocent, young (noun) and made friends with the local scientist,
Doc (name). Doc (name) was a bit off, but he was one (adjective) genius. One day,
he told Marty that he had an invented a (noun)! Of course, Marty had to see it
in action. Late that night, they met at (place).
</code></pre>
<p>and my intended result is:</p>
<pre><code> Back to the Future
Marty was an innocent, young monster and made friends with the local scientist,
Doc Strange. Doc Strange was a bit off, but he was one yellow genius. One day,
he told Marty that he had an invented a eatery! Of course, Marty had to see it
in action. Late that night, they met at Times Square.
</code></pre>
| 0 | 2016-08-22T22:01:05Z | 39,110,649 | <p>Okay, to solve my issue of only wanting to ask for each identical item once, I had to rewrite a little bit. I'm still using the regex provided by @Lex, so thanks to him for that. However, I am no longer using his <code>re.sub()</code> method.</p>
<pre><code>import re
l1 = re.findall('\(([^()]*)\)',story)
l2 = []
for i in l1:
if i not in l2:
l2.append(i)
for i in l2:
substr = '({})'.format(i)
word = input('{}: '.format(i))
story = story.replace(substr,word)
print(story)
</code></pre>
<p>The <code>findall()</code> function finds all instances matching the regex of "between parenthesis" and builds an initial list. Then, I iterate through that list and put each unique token into a new list to eliminate duplicates. I iterate through the new list of tokens and replace each match with the prompted input. This is exactly what I had wanted for my applet as it eliminates duplicate prompts.</p>
| 0 | 2016-08-23T21:04:42Z | [
"python"
] |
Finding the Parity Outlier in a list of odd/even integers | 39,089,459 | <p>I'm trying to find and return the single even integer in a list of odd integers or the sole odd integer in a list of even integers. My code works, however, if the length of the list for odd integers is even, it returns the first number in the list instead of the even integer. Any help is appreciated. Code below:</p>
<pre><code> even = [2, 4, 6, 8, 10, 12, 14, 2091] #2091 is the outlier and len(x) = 8
odd = [1, 3, 5, 7, 9, 11, 13, 4720] #4720 is the outlier and len(x) = 8
def find_outlier(x):
# Determine if list is even and length of list is odd
if sum(x) % 2 != 0 and len(x) % 2 != 0:
for x in x:
if x % 2 != 0:
return x
# Determine if list is even and length of list is even
elif sum(x) % 2 != 0 and len(x) % 2 == 0:
for x in x:
if x % 2 != 0:
return x
# Determine if list is odd and length of list is odd
elif sum(x) % 2 == 0 and len(x) % 2 != 0:
for x in x:
if x % 2 == 0:
return x
# Determine if list is odd and length of list is even (PROBLEM)
elif sum(x) % 2 == 0 and len(x) % 2 == 0:
for x in x:
if x % 2 == 0:
return x
print (find_outlier(even))
print (find_outlier(odd))
</code></pre>
<p>Below is the correct solution to the problem reformatted from Dmitri's solution:</p>
<pre><code>def find_outlier(x):
odd = [i for i in x if i % 2 != 0]
even = [i for i in x if i % 2 == 0]
return odd[0] if len(odd) < len(even) else even[0]
</code></pre>
| 1 | 2016-08-22T22:06:40Z | 39,089,512 | <p>The problem is you are summing the list trying to use that to determine whether the list is primarily odds or evens. That doesn't work because the sum of a list of evens is even, but a sum of odds will be even or odd based on the number of items in the list.</p>
<p>Instead, just keep track of the last even and odd in the list and whether you have seen more than one of a given type. And as soon as you have two evens or two odds you can assume the outlier is the other one.</p>
<p>Also, using sum() and len() in each IF clause can be incredibly inefficient because you are doing it multiple times.</p>
| 1 | 2016-08-22T22:12:21Z | [
"python",
"algorithm"
] |
Finding the Parity Outlier in a list of odd/even integers | 39,089,459 | <p>I'm trying to find and return the single even integer in a list of odd integers or the sole odd integer in a list of even integers. My code works, however, if the length of the list for odd integers is even, it returns the first number in the list instead of the even integer. Any help is appreciated. Code below:</p>
<pre><code> even = [2, 4, 6, 8, 10, 12, 14, 2091] #2091 is the outlier and len(x) = 8
odd = [1, 3, 5, 7, 9, 11, 13, 4720] #4720 is the outlier and len(x) = 8
def find_outlier(x):
# Determine if list is even and length of list is odd
if sum(x) % 2 != 0 and len(x) % 2 != 0:
for x in x:
if x % 2 != 0:
return x
# Determine if list is even and length of list is even
elif sum(x) % 2 != 0 and len(x) % 2 == 0:
for x in x:
if x % 2 != 0:
return x
# Determine if list is odd and length of list is odd
elif sum(x) % 2 == 0 and len(x) % 2 != 0:
for x in x:
if x % 2 == 0:
return x
# Determine if list is odd and length of list is even (PROBLEM)
elif sum(x) % 2 == 0 and len(x) % 2 == 0:
for x in x:
if x % 2 == 0:
return x
print (find_outlier(even))
print (find_outlier(odd))
</code></pre>
<p>Below is the correct solution to the problem reformatted from Dmitri's solution:</p>
<pre><code>def find_outlier(x):
odd = [i for i in x if i % 2 != 0]
even = [i for i in x if i % 2 == 0]
return odd[0] if len(odd) < len(even) else even[0]
</code></pre>
| 1 | 2016-08-22T22:06:40Z | 39,089,518 | <p>Why do you care about the length at all? Here is much simpler solution:</p>
<pre><code>def find_outliner(a):
if a[0] % 2 != a[1] % 2:
return a[0] if a[2] % 2 == a[1] % 2 else a[1]
for i in a:
if i % 2 != a[0] % 2:
return i
</code></pre>
<p>How does it work?</p>
<ol>
<li>There should be at least three elements in the list, otherwise the problem does not make much sense</li>
<li>If the first two elements have different parity, check which element is wrong based on third (if the second and the third have the same parity, the first is the wrong one, otherwise - the second is the wrong one)</li>
<li>If the first two elements have the same parity, that means that parity of the first (and the second) element is the correct parity for list. Thus, the element with different parity is what we are looking for.</li>
</ol>
| 2 | 2016-08-22T22:12:37Z | [
"python",
"algorithm"
] |
Finding the Parity Outlier in a list of odd/even integers | 39,089,459 | <p>I'm trying to find and return the single even integer in a list of odd integers or the sole odd integer in a list of even integers. My code works, however, if the length of the list for odd integers is even, it returns the first number in the list instead of the even integer. Any help is appreciated. Code below:</p>
<pre><code> even = [2, 4, 6, 8, 10, 12, 14, 2091] #2091 is the outlier and len(x) = 8
odd = [1, 3, 5, 7, 9, 11, 13, 4720] #4720 is the outlier and len(x) = 8
def find_outlier(x):
# Determine if list is even and length of list is odd
if sum(x) % 2 != 0 and len(x) % 2 != 0:
for x in x:
if x % 2 != 0:
return x
# Determine if list is even and length of list is even
elif sum(x) % 2 != 0 and len(x) % 2 == 0:
for x in x:
if x % 2 != 0:
return x
# Determine if list is odd and length of list is odd
elif sum(x) % 2 == 0 and len(x) % 2 != 0:
for x in x:
if x % 2 == 0:
return x
# Determine if list is odd and length of list is even (PROBLEM)
elif sum(x) % 2 == 0 and len(x) % 2 == 0:
for x in x:
if x % 2 == 0:
return x
print (find_outlier(even))
print (find_outlier(odd))
</code></pre>
<p>Below is the correct solution to the problem reformatted from Dmitri's solution:</p>
<pre><code>def find_outlier(x):
odd = [i for i in x if i % 2 != 0]
even = [i for i in x if i % 2 == 0]
return odd[0] if len(odd) < len(even) else even[0]
</code></pre>
| 1 | 2016-08-22T22:06:40Z | 39,089,968 | <p>Just an alternative, collecting the evens and odds in two lists and then using the smaller list.</p>
<pre><code>def find_outlier(x):
evenodd = [], []
for v in x:
evenodd[v & 1].append(v)
return min(evenodd, key=len)[0]
</code></pre>
<p>Demo:</p>
<pre><code>>>> for x in [2, 4, 6, 8, 10, 12, 14, 2091], [1, 3, 5, 7, 9, 11, 13, 4720]:
print(find_outlier(x))
2091
4720
</code></pre>
| 0 | 2016-08-22T22:59:55Z | [
"python",
"algorithm"
] |
Getting a TypeError when trying to send a random packet in a socket | 39,089,493 | <p>I'm trying to make a simple UDP flooder to learn a a little about sockets, however i get "TypeError: an integer is required"</p>
<pre><code>import os
import socket
import random
s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
print("Python Script 1")
os.system("pause")
print("[*] Please enter parameters below")
ip = raw_input("Enter IP adress: ")
port = raw_input("Enter port: ")
size = int(raw_input("Enter Packet size: "))
amount = int(raw_input("Enter amount of packets (0 for infinite): "))
bytes = random._urandom(size)
print("[*] UDP Flooding started on " + ip + ":" + port)
while amount > 1:
s.sendto(bytes,(ip,port))
print("[*] Sent %s packets to %s : %s.") % (sent,ip,port)
sent = sent + 1
amount = amount - 1
while amount == 0:
s.sendto(bytes,(ip,port))
print("[*] Sent %s packets to %s : %s.") % (sent,ip,port)
sent = sent + 1
</code></pre>
<p>I get the error on s.sendto(bytes,(ip,port)), I've tried looking around on google but couldn't find anything. Thanks!</p>
| 0 | 2016-08-22T22:10:08Z | 39,089,520 | <p><code>port</code> must be an<code>int</code>, not a <code>str</code>.</p>
<pre><code>port = int(port)
</code></pre>
| 1 | 2016-08-22T22:12:42Z | [
"python",
"python-2.7"
] |
Installing Yapsy for Python script in Windows | 39,089,544 | <p>Im trying to run a script in python 2.7 but I need Yapsy, I download from github but I dont know how to install it, I cant find any documentation in github neither in <a href="http://yapsy.sourceforge.net/" rel="nofollow" title="sourceforge">sourceforge</a><a href="http://i.stack.imgur.com/x4XHf.png" rel="nofollow"><img src="http://i.stack.imgur.com/x4XHf.png" alt="enter image description here"></a></p>
| 0 | 2016-08-22T22:15:28Z | 39,089,777 | <p>From the <a href="https://yapsy.readthedocs.io/en/latest/" rel="nofollow">manual</a>:
<code>pip install -e "git+https://github.com/tibonihoo/yapsy.git#egg=yapsy&subdirectory=package"</code> or </p>
<p><code>pip install -e "hg+http://hg.code.sf.net/p/yapsy/code#egg=yapsy&subdirectory=package"
</code></p>
| 0 | 2016-08-22T22:40:36Z | [
"python",
"python-2.7"
] |
Why is numpy.prod() incorrectly returning negative results, or 0, for my long lists of natural numbers? | 39,089,618 | <p>I'm just working on Project Euler <a href="https://projecteuler.net/problem=12" rel="nofollow">problem 12</a>, so I need to do some testing against numbers that are multiples of over 500 unique factors.</p>
<p>I figured that the array [1, 2, 3... 500] would be a good starting point, since the product of that array is the lowest possible such number. However, numpy.prod() returns <em>zero</em> for this array. I'm sure I'm missing something obvious, but what the hell is it?</p>
<pre><code>>>> import numpy as np
>>> array = []
>>> for i in range(1,100):
... array.append(i)
...
>>> np.prod(array)
0
>>> array.append(501)
>>> np.prod(array)
0
>>> array.append(5320934)
>>> np.prod(array)
0
</code></pre>
| 2 | 2016-08-22T22:23:42Z | 39,089,668 | <p>Those numbers get very big, fast. </p>
<pre><code>>>> np.prod(array[:25])
7034535277573963776
>>> np.prod(array[:26])
-1569523520172457984
>>> type(_)
numpy.int64
</code></pre>
<p>You're actually overflowing numpy's data type here, hence the wack results. If you stick to python ints, you won't have overflow. </p>
<pre><code>>>> import operator
>>> reduce(operator.mul, array, 1)
933262154439441526816992388562667004907159682643816214685929638952175999932299156089414639761565182862536979208272237582511852109168640000000000000000000000L
</code></pre>
| 3 | 2016-08-22T22:28:58Z | [
"python",
"list",
"numpy",
"math"
] |
Why is numpy.prod() incorrectly returning negative results, or 0, for my long lists of natural numbers? | 39,089,618 | <p>I'm just working on Project Euler <a href="https://projecteuler.net/problem=12" rel="nofollow">problem 12</a>, so I need to do some testing against numbers that are multiples of over 500 unique factors.</p>
<p>I figured that the array [1, 2, 3... 500] would be a good starting point, since the product of that array is the lowest possible such number. However, numpy.prod() returns <em>zero</em> for this array. I'm sure I'm missing something obvious, but what the hell is it?</p>
<pre><code>>>> import numpy as np
>>> array = []
>>> for i in range(1,100):
... array.append(i)
...
>>> np.prod(array)
0
>>> array.append(501)
>>> np.prod(array)
0
>>> array.append(5320934)
>>> np.prod(array)
0
</code></pre>
| 2 | 2016-08-22T22:23:42Z | 39,089,671 | <p>Note that <a href="http://www.gossamer-threads.com/lists/python/python/105568" rel="nofollow">Python uses "unlimited" integers</a>, but in numpy everything is typed, and so it is a "C"-style (probably 64-bit) integer here. You're probably experiencing an overflow.</p>
<p>If you look at the documentation for <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.prod.html" rel="nofollow"><code>numpy.prod</code></a>, you can see the <code>dtype</code> parameter:</p>
<blockquote>
<p>The type of the returned array, as well as of the accumulator in which the elements are multiplied.</p>
</blockquote>
<p>There are a few things you can do:</p>
<ol>
<li><p>Drop back to Python, and multiply using its "unlimited integers" (see <a href="http://stackoverflow.com/questions/2104782/returning-the-product-of-a-list">this question</a> for how to do so).</p></li>
<li><p>Consider whether you actually need to find the product of such huge numbers. Often, when you're working with the product of very small or very large numbers, you switch to sums of logarithms. As @WarrenWeckesser notes, this is obviously imprecise (it's not like taking the exponent at the end will give you the exact solution) - rather, it's used to gauge whether one product is growing faster than another.</p></li>
</ol>
| 2 | 2016-08-22T22:29:02Z | [
"python",
"list",
"numpy",
"math"
] |
Why is numpy.prod() incorrectly returning negative results, or 0, for my long lists of natural numbers? | 39,089,618 | <p>I'm just working on Project Euler <a href="https://projecteuler.net/problem=12" rel="nofollow">problem 12</a>, so I need to do some testing against numbers that are multiples of over 500 unique factors.</p>
<p>I figured that the array [1, 2, 3... 500] would be a good starting point, since the product of that array is the lowest possible such number. However, numpy.prod() returns <em>zero</em> for this array. I'm sure I'm missing something obvious, but what the hell is it?</p>
<pre><code>>>> import numpy as np
>>> array = []
>>> for i in range(1,100):
... array.append(i)
...
>>> np.prod(array)
0
>>> array.append(501)
>>> np.prod(array)
0
>>> array.append(5320934)
>>> np.prod(array)
0
</code></pre>
| 2 | 2016-08-22T22:23:42Z | 39,100,107 | <p>You get the result 0 due to the large number of factors 2 in the product, there are more than 450 of those factors. Thus in a reduction modulo <code>2^64</code>, the result is zero.</p>
<p>Why the data type forces this reduction is explained in the other answers. </p>
<hr>
<pre><code>250+125+62+31+15+7+3+1 = 494 is the multiplicity of 2 in 500!
</code></pre>
| 0 | 2016-08-23T11:36:56Z | [
"python",
"list",
"numpy",
"math"
] |
How to use `Dirichlet Process Gaussian Mixture Model` in Scikit-learn? (n_components?) | 39,089,637 | <p><strong>My understanding of "an infinite mixture model with the Dirichlet Process as a prior distribution on the number of clusters" is that the number of clusters is determined by the data as they converge to a certain amount of clusters.</strong> </p>
<p>This <code>R Implementation</code> <a href="https://github.com/jacobian1980/ecostates" rel="nofollow">https://github.com/jacobian1980/ecostates</a> decides on the number of clusters in this way. Although, the <code>R implementation</code> uses a Gibbs sampler, I'm not sure if that affects this. </p>
<p>What confuses me is the <code>n_components</code> parameters. <code>n_components: int, default 1 :
Number of mixture components.</code> <strong>If the number of components is determined by the data and the Dirichlet Process, then what is this parameter?</strong> </p>
<hr>
<p>Ultimately, I'm trying to get: </p>
<p>(1) the cluster assignment for each sample; </p>
<p>(2) the probability vectors for each cluster; and </p>
<p>(3) the likelihood/log-likelihood for each sample. </p>
<p>It looks like (1) is the <code>predict</code> method, and (3) is the <code>score</code> method. However, the output of (1) is completely dependent on the <code>n_components</code> hyperparameter.</p>
<p>My apologies if this is a naive question, I'm very new to Bayesian programming and noticed there was <code>Dirichlet Process</code> in <code>Scikit-learn</code> that I wanted to try out. </p>
<hr>
<p>Here's the docs:
<a href="http://scikit-learn.org/stable/modules/generated/sklearn.mixture.DPGMM.html#sklearn.mixture.DPGMM" rel="nofollow">http://scikit-learn.org/stable/modules/generated/sklearn.mixture.DPGMM.html#sklearn.mixture.DPGMM</a> </p>
<p>Here's an example of usage:
<a href="http://scikit-learn.org/stable/auto_examples/mixture/plot_gmm.html" rel="nofollow">http://scikit-learn.org/stable/auto_examples/mixture/plot_gmm.html</a></p>
<p>Here's my naive usage:</p>
<pre><code>from sklearn.mixture import DPGMM
X = pd.read_table("Data/processed/data.tsv", sep="\t", index_col=0)
Mod_dpgmm = DPGMM(n_components=3)
Mod_dpgmm.fit(X)
</code></pre>
| 0 | 2016-08-22T22:25:55Z | 39,623,217 | <p>As mentioned by @maxymoo in the comments, <code>n_components</code> is a truncation parameter. </p>
<p>In the context of the Chinese Restaurant Process, which is related to the Stick-breaking representation in sklearn's DP-GMM, a new data point joins an existing cluster <code>k</code> with probability <code>|k| / n-1+alpha</code> and <em>starts</em> a new cluster with probability <code>alpha / n-1 + alpha</code>. This parameter can be interpreted as the concentration parameter of the Dirichlet Process and it will influence the final number of clusters.</p>
<p>Unlike R's implmentation that uses Gibbs sampling, sklearn's DP-GMM implementation uses variational inference. This can be related to the difference in results.</p>
<p>A gentle Dirichlet Process tutorial can be found <a href="http://www.cs.cmu.edu/~./kbe/dp_tutorial.pdf" rel="nofollow">here</a>.</p>
| 0 | 2016-09-21T17:42:52Z | [
"python",
"machine-learning",
"statistics",
"scikit-learn",
"bayesian"
] |
Cython compiling errors - variable referenced before assignment | 39,089,661 | <p>I'm goofing off with cython and a pretty big for loop - over a million. It takes about 40 minutes to run regular when I run as a regular python program. </p>
<p>vetdns.pyx and labeled cdef variables just below declaring the function - </p>
<pre><code>now = datetime.datetime.now()
today = now.strftime("%Y-%m-%d")
my_date = date.today()
dayoftheweek=calendar.day_name[my_date.weekday()]
#needed because of the weird naming and time objects vs datetime objects
read_date = datetime.datetime.strptime(today, '%Y-%m-%d')
previous_day = read_date - datetime.timedelta(days=1)
yesterday = previous_day.strftime('%Y-%m-%d')
my_dir = os.getcwd()
# extracted = "extracted_"+today
outname = "alexa_all_vetted"+today
downloaded_file = "top-1m"+today+".zip"
INPUT_FILE="dns-all"
OUTPUT_FILE="dns_blacklist_"+dayoftheweek
REMOVE_FILE="dns_blacklist_upto"+yesterday
PATH = "/home/money/Documents/hybrid"
FULL_FILENAME= os.path.join(PATH, OUTPUT_FILE)
CLEANUP_FILENAME=os.path.join(PATH, REMOVE_FILE)
##cdef outname, INPUT_FILE, OUTPUT_FILE labeled just inside function.
def main():
zip_file_url = "http://s3.amazonaws.com/alexa-static/top-1m.csv.zip"
urllib.urlretrieve(zip_file_url, downloaded_file)
###naming variables affected in for loop
cdef outname, INPUT_FILE, OUTPUT_FILE
with zipfile.ZipFile(downloaded_file) as zip_file:
for member in zip_file.namelist():
filename = os.path.basename(member)
# skip directories
if not filename:
continue
# copy file (taken from zipfile's extract)
source = zip_file.open(member)
target = file(os.path.join(my_dir, filename), "wb")
with source, target:
shutil.copyfileobj(source, target)
whitelist = open(outname,'w')
with open(member,'r') as member:
reader = csv.reader(member, delimiter=',')
alexia_hosts = []
for row in reader:
alexia_hosts.append(row[1])
whitelist.write("\n".join(alexia_hosts))
file_out=open(FULL_FILENAME,"w")
with open(INPUT_FILE, 'r') as dnsMISP:
with open(outname, 'r') as f:
alexa=[]
alexafull=[]
blacklist = []
for line in f:
line = line.strip()
alexahostname=urltools.extract(line)
alexa.append(alexahostname[4])
alexafull.append(line)
for line in dnsMISP:
line = line.strip()
hostname = urltools.extract(line)
# print hostname[4]
if hostname[4] in alexa:
print hostname[4]+",this hostname is in alexa"
pass
elif hostname[5] in alexafull:
print hostname[5]+",this hostname is in alexafull"
else:
blacklist.append(line)
file_out.write("\n".join(blacklist))
file_out.close()
main()
</code></pre>
<p>Built setup.py</p>
<pre><code>from distutils.core import setup
from Cython.Build import cythonize
setup(
ext_modules = cythonize("vetdns.pyx")
)
</code></pre>
<p>But when I run </p>
<pre><code>python setup.py build_ext --inplace
</code></pre>
<p>I get the following errors - </p>
<pre><code>Error compiling Cython file:
------------------------------------------------------------
...
source = zip_file.open(member)
target = file(os.path.join(my_dir, filename), "wb")
with source, target:
shutil.copyfileobj(source, target)
whitelist = open(outname,'w')
^
------------------------------------------------------------
vetdns.pyx:73:25: local variable 'outname' referenced before assignment
</code></pre>
<p>This is probably a little beyond me right now but I wanted to play around with it anyway. </p>
| 0 | 2016-08-22T22:28:22Z | 39,093,072 | <p>You declare <code>outname</code> as a local variable on this line:</p>
<pre><code>cdef outname, INPUT_FILE, OUTPUT_FILE
</code></pre>
<p>but then you never assign anything to it. Python requires that variables are assigned before you can use them, there is no default value they get initialized to.</p>
<p>I see that you've got a global variable named "outname", if you want to use the global variable you don't need to use a <code>cdef</code> inside your function. Same applies to your other global variables.</p>
<h3>Upadate</h3>
<p>One thing you can try that's worked well for me in the past is to pop out just the loop into a cythonized function. This way there is less cython code to debug/optimize but when most of the processing time is spent in just a few lines of code (which is often the case), compiling just these lines can make a big difference. In practice, that looks a little like this:</p>
<pre><code># my_script.py
import os
from my_helper import bottle_neck
def main():
a = 12
b = 22
c = 999
# More prep code
print bottle_neck(a, b, c)
main()
</code></pre>
<p>And in a different file:</p>
<pre><code># my_helper.pyx
def bottle_neck(int a, int b, int c):
# Silly example, this loop might never finish
while a > 0:
a = a & b
b = a - c
c = b * a
return a, b, c
</code></pre>
<p>Make sure you profile your code, it suck to assume something is slow to discover that it's in fact pretty fast only after you've taken the time to optimize it.</p>
| 2 | 2016-08-23T05:33:59Z | [
"python",
"cython"
] |
Rolling Regression Estimation in Python dataframe | 39,089,693 | <p>I have a dataframe like this:</p>
<pre><code> Date Y X1 X2 X3
22 2004-05-12 9.348158e-09 0.000081 0.000028 0.000036
23 2004-05-13 9.285989e-09 0.000073 0.000081 0.000097
24 2004-05-14 9.732308e-09 0.000085 0.000073 0.000096
25 2004-05-17 2.235977e-08 0.000089 0.000085 0.000099
26 2004-05-18 2.792661e-09 0.000034 0.000089 0.000150
27 2004-05-19 9.745323e-09 0.000048 0.000034 0.000053
......
1000 2004-05-20 1.835462e-09 0.000034 0.000048 0.000099
1001 2004-05-21 3.529089e-09 0.000037 0.000034 0.000043
1002 2004-05-24 3.453047e-09 0.000043 0.000037 0.000059
1003 2004-05-25 2.963131e-09 0.000038 0.000043 0.000059
1004 2004-05-26 1.390032e-09 0.000029 0.000038 0.000054
</code></pre>
<p>I want to run a rolling 100-day window OLS regression estimation, which is: </p>
<p>First for the 101st row, I run a regression of Y-X1,X2,X3 using the 1st to 100th rows, and estimate Y for the 101st row;</p>
<p>Then for the 102nd row, I run a regression of Y-X1,X2,X3 using the 2nd to 101st rows, and estimate Y for the 102nd row;</p>
<p>Then for the 103rd row, I run a regression of Y-X1,X2,X3 using the 2nd to 101st rows, and estimate Y for the 103rd row;</p>
<p>......</p>
<p>Until the last row.</p>
<p>How to do thisï¼</p>
| 1 | 2016-08-22T22:31:09Z | 39,089,927 | <pre><code>model = pd.stats.ols.MovingOLS(y=df.Y, x=df[['X1', 'X2', 'X3']],
window_type='rolling', window=100, intercept=True)
df['Y_hat'] = model.y_predict
</code></pre>
| 2 | 2016-08-22T22:55:26Z | [
"python",
"pandas",
"dataframe"
] |
How to install Python 3.5 on Raspbian Jessie | 39,089,698 | <p>I need to install Python 3.5+ on Rasbian (Debian for the Raspberry Pi). Currently only version 3.4 is supported. For the sources I want to compile I have to install:</p>
<pre><code>sudo apt-get install -y python3 python-empy python3-dev python3-empy python3-nose python3-pip python3-setuptools python3-vcstool pydocstyle pyflakes python3-coverage python3-mock python3-pep8
</code></pre>
<p>But I think that <code>apt-get</code> will install more than these packages, for example <code>libpython3-dev</code>.</p>
<p>I already install <code>python3</code> from <a href="https://www.python.org/downloads/" rel="nofollow">https://www.python.org/downloads/</a> but I think, that is not complete.</p>
<p>Can you give me some suggestion which way is the best to get this?</p>
<p>A similar question was posted here <a href="http://stackoverflow.com/questions/35385423/install-python-3-5-with-pip-on-debian-8">Install Python 3.5 with pip on Debian 8</a> but this solution seems not to work on arm64.</p>
<hr>
<p>Edit:</p>
<p>regarding to the comment of Padraic Cunningham: The first step I have done before. The second one results into this:</p>
<pre><code>$ sudo python3.5 get-pip.py
Traceback (most recent call last):
File "get-pip.py", line 19177, in <module>
main()
File "get-pip.py", line 194, in main
bootstrap(tmpdir=tmpdir)
File "get-pip.py", line 82, in bootstrap
import pip
File "/tmp/tmpoe3rjlw3/pip.zip/pip/__init__.py", line 16, in <module>
File "/tmp/tmpoe3rjlw3/pip.zip/pip/vcs/subversion.py", line 9, in <module>
File "/tmp/tmpoe3rjlw3/pip.zip/pip/index.py", line 30, in <module>
File "/tmp/tmpoe3rjlw3/pip.zip/pip/wheel.py", line 39, in <module>
File "/tmp/tmpoe3rjlw3/pip.zip/pip/_vendor/distlib/scripts.py", line 14, in <module>
File "/tmp/tmpoe3rjlw3/pip.zip/pip/_vendor/distlib/compat.py", line 66, in <module>
ImportError: cannot import name 'HTTPSHandler'
</code></pre>
| 0 | 2016-08-22T22:31:53Z | 39,089,725 | <blockquote>
<p>But I think that apt-get will install more than these
packages, for example libpython3-dev</p>
</blockquote>
<p>Why is that a problem? </p>
<blockquote>
<p>I already install python3 from <a href="https://www.python.org/downloads/" rel="nofollow">https://www.python.org/downloads/</a> but I think, that is not complete.</p>
</blockquote>
<p>Why do you think that? Did you untar it, and run </p>
<pre><code>./configure
</code></pre>
<p>What where the results?</p>
| -2 | 2016-08-22T22:34:18Z | [
"python",
"raspberry-pi",
"debian",
"raspbian"
] |
How to install Python 3.5 on Raspbian Jessie | 39,089,698 | <p>I need to install Python 3.5+ on Rasbian (Debian for the Raspberry Pi). Currently only version 3.4 is supported. For the sources I want to compile I have to install:</p>
<pre><code>sudo apt-get install -y python3 python-empy python3-dev python3-empy python3-nose python3-pip python3-setuptools python3-vcstool pydocstyle pyflakes python3-coverage python3-mock python3-pep8
</code></pre>
<p>But I think that <code>apt-get</code> will install more than these packages, for example <code>libpython3-dev</code>.</p>
<p>I already install <code>python3</code> from <a href="https://www.python.org/downloads/" rel="nofollow">https://www.python.org/downloads/</a> but I think, that is not complete.</p>
<p>Can you give me some suggestion which way is the best to get this?</p>
<p>A similar question was posted here <a href="http://stackoverflow.com/questions/35385423/install-python-3-5-with-pip-on-debian-8">Install Python 3.5 with pip on Debian 8</a> but this solution seems not to work on arm64.</p>
<hr>
<p>Edit:</p>
<p>regarding to the comment of Padraic Cunningham: The first step I have done before. The second one results into this:</p>
<pre><code>$ sudo python3.5 get-pip.py
Traceback (most recent call last):
File "get-pip.py", line 19177, in <module>
main()
File "get-pip.py", line 194, in main
bootstrap(tmpdir=tmpdir)
File "get-pip.py", line 82, in bootstrap
import pip
File "/tmp/tmpoe3rjlw3/pip.zip/pip/__init__.py", line 16, in <module>
File "/tmp/tmpoe3rjlw3/pip.zip/pip/vcs/subversion.py", line 9, in <module>
File "/tmp/tmpoe3rjlw3/pip.zip/pip/index.py", line 30, in <module>
File "/tmp/tmpoe3rjlw3/pip.zip/pip/wheel.py", line 39, in <module>
File "/tmp/tmpoe3rjlw3/pip.zip/pip/_vendor/distlib/scripts.py", line 14, in <module>
File "/tmp/tmpoe3rjlw3/pip.zip/pip/_vendor/distlib/compat.py", line 66, in <module>
ImportError: cannot import name 'HTTPSHandler'
</code></pre>
| 0 | 2016-08-22T22:31:53Z | 39,185,009 | <p>The suggestion of @Padraic Cunningham to install <code>libssl</code> header files was helpful.</p>
<pre><code>sudo apt-get install libssl-dev
</code></pre>
<p>But after this I further had to install <em>GCC</em> higher version 5 and <em>CMake</em> higher 3.5. The new <em>Raspian Stretch</em> comes with <em>Python 3.5</em> and additionally with <em>GCC 6.1</em> and <em>CMake 3.5</em>.</p>
<p>So the easiest way was to upgrade my system to Stretch (at the moment under test):</p>
<pre><code>sudo echo 'deb http://mirrordirector.raspbian.org/raspbian/ testing main contrib non-free rpi' > /etc/apt/sources.list.d/stretch.list
sudo apt-get update
sudo apt-get dist-upgrade
sudo apt-get autoremove
</code></pre>
<p>This is quiet easy and always up to date. At the end this is my prefered solution :)</p>
| 0 | 2016-08-27T19:35:49Z | [
"python",
"raspberry-pi",
"debian",
"raspbian"
] |
tkinter Label Isn't showing | 39,089,726 | <p>I'm following a well reviewed python book called "Python programming" and have followed the book to the letter, until in the middle of programming I wanted to test out my label so I tried. Code runs fine but label didn't appear. Please help me. Code is down below.</p>
<pre><code>import sys
import os
from tkinter import *
class Safe(Frame):
""" PS """
def __init__(self, master):
""" Initalize the frame """
super(Application, self).__init__(master)
self.grid()
self.create_widgets()
def create_widgets(self):
""" Create button , text, and entry widgets """
# Create instuction label
self.inst_label = Label(self, text = "Welcome")
self.inst_label.grid(row = 0, column = 0, columnspan = 2, sticky = W)
#main
root = Tk()
root.title("Password Safe")
root.geometry("500x400")
root.mainloop()
</code></pre>
| -2 | 2016-08-22T22:34:20Z | 39,090,267 | <p>First, you need to instantiate the class. Root is just an empty window.</p>
<pre><code>mywindow = Safe()
mywindow.title("Password Safe")
mywindow.mainloop()
</code></pre>
<ul>
<li><code>self.create_widgets()</code> will add the widgets to the frame.</li>
<li><code>self.inst_label.grid()</code> will tell Tk how to pack the label.</li>
</ul>
<p>So, you should be good to go from there.</p>
| 0 | 2016-08-22T23:37:50Z | [
"python",
"tkinter"
] |
Why do these two python regexes produce different results? | 39,089,760 | <pre><code>>>> re.match(r'"([^"]|(\\\"))*"', r'"I do not know what \"A\" is"').group(0)
'"I do not know what \\"'
>>> re.match(r'"((\\\")|[^"])*"', r'"I do not know what \"A\" is"').group(0)
'"I do not know what \\"A\\" is"'
</code></pre>
<p>These two regexes are intended to be looking for quoted strings, with escaped quote sequences. The difference, unless I am missing something, is the order of the disjunction in the parentheses.</p>
<p>Why do they not both accept the entire string?</p>
| 1 | 2016-08-22T22:38:33Z | 39,089,940 | <p>The order in alternation groups matters.</p>
<p>In the first regex the <code>[^"]</code> alternative is tried first for every character. It matches every single character up to (and including) the first <code>\</code>. On the next character (<code>"</code>) this alternative (<code>[^"]</code>) fails and the other one (<code>\\\"</code>) tried. The latter also fails since <code>"A</code> does not match <code>\\\"</code>. This stop the quantifier <code>*</code> from further matches.</p>
<p>In the second regex the <code>\\\"</code> alternative (parenthesis are redundant) tried first for every character and fails so the second alternative (<code>[^"]</code>) matches. But on at the first <code>\</code> the first alternative matches so the lookup pointer moves past <code>\"</code> to <code>A</code> and lookup goes on.</p>
<p>As a general rule of thumb, place the most narrow expression in alternation first.</p>
| 1 | 2016-08-22T22:56:46Z | [
"python",
"regex"
] |
Why do these two python regexes produce different results? | 39,089,760 | <pre><code>>>> re.match(r'"([^"]|(\\\"))*"', r'"I do not know what \"A\" is"').group(0)
'"I do not know what \\"'
>>> re.match(r'"((\\\")|[^"])*"', r'"I do not know what \"A\" is"').group(0)
'"I do not know what \\"A\\" is"'
</code></pre>
<p>These two regexes are intended to be looking for quoted strings, with escaped quote sequences. The difference, unless I am missing something, is the order of the disjunction in the parentheses.</p>
<p>Why do they not both accept the entire string?</p>
| 1 | 2016-08-22T22:38:33Z | 39,089,995 | <p>The regex <code>r'(A|B)'</code> will test first try to match A, and only if that fails will it try to match B (<a href="https://docs.python.org/3/library/re.html#regular-expression-syntax" rel="nofollow">docs</a>)</p>
<p>So the regex <code>([^"]|(\\\")</code> will first try to match a non-quote, and if that fails it will try to match an escaped quote mark.</p>
<p>So when the regex reaches <code>\"A\"</code> the first part part matches the <code>\</code> (it is not a quote. But then neither part matches <code>"</code>, so the match ends there. The backslash is gobbled by the <code>[^"]</code> so the second half of the expression is never used.</p>
<p>Turned around ((\\")|[^"]), when it reaches <code>\"A\"</code> will first try to match the <code>\"</code> (it works) then it will try to match <code>A</code> (it matches <code>[^"]</code> and so the match continues.</p>
| 0 | 2016-08-22T23:02:14Z | [
"python",
"regex"
] |
Why do these two python regexes produce different results? | 39,089,760 | <pre><code>>>> re.match(r'"([^"]|(\\\"))*"', r'"I do not know what \"A\" is"').group(0)
'"I do not know what \\"'
>>> re.match(r'"((\\\")|[^"])*"', r'"I do not know what \"A\" is"').group(0)
'"I do not know what \\"A\\" is"'
</code></pre>
<p>These two regexes are intended to be looking for quoted strings, with escaped quote sequences. The difference, unless I am missing something, is the order of the disjunction in the parentheses.</p>
<p>Why do they not both accept the entire string?</p>
| 1 | 2016-08-22T22:38:33Z | 39,090,086 | <p>What you say is true, the order is different. And something else is different.<br>
The first one <code>"([^"]|(\\\"))*"</code> will match an escape, making it<br>
match <code>"asdf\"</code>sde" while the other one doesn't. </p>
<p>Also if you have to handle escape quote, you have to handle escapes as well. So, neither one is valid. </p>
<p>Here are two kind of standard ways to do this.<br>
Both handle the escape.<br>
You can extend this to single quotes as well.<br>
<em>Use the Dot-All modifier <code>(?s)</code> if you want to span newlines.</em></p>
<p>Method 1. - alternation </p>
<p><code>"(?:\\.|[^"\\]+)*"</code> </p>
<pre><code> "
(?:
\\ . # Escape anything
| # or,
[^"\\]+ # Not escape not quote
)*
"
</code></pre>
<p>Method 2. - unrolled loop </p>
<p><code>"[^"\\]*(?:\\.[^"\\]*)*"</code> </p>
<pre><code> "
[^"\\]* # Optional not escape not quote
(?:
\\ . # Escape anything
[^"\\]* # Optional not escape not quote
)*
"
</code></pre>
<p>Both do the same. Method 2 is three to five time faster than Method 1.</p>
| 2 | 2016-08-22T23:12:12Z | [
"python",
"regex"
] |
Running time analysis of the loops | 39,089,761 | <p>Consider following loops:</p>
<pre><code>def func1(xs, ys, zs):
for x in xs:
for y in ys:
pass
for z in zs:
pass
</code></pre>
<p>The running time should take <code>size of xs * (size of ys + size of zs)</code>, which could be written in big-o notation as <code>O(X) * (O(Y) + O(Z))</code>.</p>
<pre><code>def func2(xs, ys, zs):
for y in ys:
for x in xs:
pass
for z in zs:
for x in xs:
pass
</code></pre>
<p>The running time of this functions should be <code>size of ys * size of xs + size of zs * size of xs</code> which would make in Big-O, <code>O(Y) * O(X) + O(Z) * O(X)</code>.</p>
<p>Question is, are these running time analyses correct? If so, are the running time of those functions equal? Because from arithmetic <code>x * (y + z) = x * y + x * z</code>.</p>
<p>Results from ipython's <code>%timeit</code> function show that i seem to be wrong.</p>
<pre><code>In [8]: ys1 = range(1, 500)
In [9]: zs1 = range(1, 1000)
In [11]: xs1 = range(1, 1000000)
In [12]: %timeit func1(xs1, ys1, zs1)
1 loop, best of 3: 15.7 s per loop
In [13]: %timeit func2(xs1, ys1, zs1)
1 loop, best of 3: 19.1 s per loop
</code></pre>
<p>Would like to understand what's wrong with my analyses. Thanks.</p>
| 1 | 2016-08-22T22:38:40Z | 39,089,921 | <p>You want to use <code>O(x * (y + x))</code> instead of <code>O(X) * (O(Y) + O(Z))</code> (where x is length of X, y is length of Y, etc) to describe complexity of your first loop (O should "wrap" the whole expression)</p>
<p>Why?</p>
<p>Assume that f(x) is function that returns exact number of actions required to perform task with size x.</p>
<p>By definition f(x) = O(x) if there exist a, b so that a * O(x) + b = f(x) for all x (note that it also means that for all O(x), all a all b, all c and all d, <code>a * O(x) + b</code> = <code>c * O(x) + d</code>). To understand why this means that you need to have O wrapping the expression, consider the following loop:</p>
<pre><code>for i in range(n):
for j in range(n):
pass # This is assumed to be exactly one action
</code></pre>
<p>Note that for this loop f(n) equals exactly to <code>n^2</code></p>
<p>Let's say we decided that complexity of this loop as <code>O(n) * O(n)</code> rather than <code>O(n ^ 2)</code>. Then, <code>O(n)^2</code> = <code>(a*O(n)+b)^2</code> = <code>a^2 * O(n) + a * b * O(n) + b ^ 2</code>. You can notice that in expansions there appears <code>a ^ 2 * O(n)</code>. It makes it impossible to add or substract such constant that this expression would be always equal to f(n) because O(n) obviously changes depending on input size. Thus, this is wrong notation.</p>
<p>O(n^2) though would be just right, because for a=1 and b=1, <code>a*O(n)+b=f(n)</code> for all n. </p>
<p>Thus, we need to rewrite complexity for all your loops, keeping that in mind. For your first loop, the correct complexity is <code>O(x * (y + z))</code> = <code>O(x*y + x*z)</code>. For your second loop, the correct complexity is O(y<em>z + z</em>x).</p>
<p>So yes, the overall complexity for both loops is the same.</p>
| 0 | 2016-08-22T22:55:05Z | [
"python",
"algorithm"
] |
Running time analysis of the loops | 39,089,761 | <p>Consider following loops:</p>
<pre><code>def func1(xs, ys, zs):
for x in xs:
for y in ys:
pass
for z in zs:
pass
</code></pre>
<p>The running time should take <code>size of xs * (size of ys + size of zs)</code>, which could be written in big-o notation as <code>O(X) * (O(Y) + O(Z))</code>.</p>
<pre><code>def func2(xs, ys, zs):
for y in ys:
for x in xs:
pass
for z in zs:
for x in xs:
pass
</code></pre>
<p>The running time of this functions should be <code>size of ys * size of xs + size of zs * size of xs</code> which would make in Big-O, <code>O(Y) * O(X) + O(Z) * O(X)</code>.</p>
<p>Question is, are these running time analyses correct? If so, are the running time of those functions equal? Because from arithmetic <code>x * (y + z) = x * y + x * z</code>.</p>
<p>Results from ipython's <code>%timeit</code> function show that i seem to be wrong.</p>
<pre><code>In [8]: ys1 = range(1, 500)
In [9]: zs1 = range(1, 1000)
In [11]: xs1 = range(1, 1000000)
In [12]: %timeit func1(xs1, ys1, zs1)
1 loop, best of 3: 15.7 s per loop
In [13]: %timeit func2(xs1, ys1, zs1)
1 loop, best of 3: 19.1 s per loop
</code></pre>
<p>Would like to understand what's wrong with my analyses. Thanks.</p>
| 1 | 2016-08-22T22:38:40Z | 39,090,124 | <p>You are measuring how long the for loops themselves take to execute, not the imaginary statement inside the loops.</p>
<p>When your loops are structured like this:</p>
<pre><code>for x in xs:
for y in ys:
pass
for z in zs:
pass
</code></pre>
<p>Consider how many times each list is iterated over:</p>
<ul>
<li><code>xs</code> is iterated over once from the outer loop</li>
<li><code>ys</code> is iterated over <code>X</code> times in the inner loop</li>
<li><code>zs</code> is iterated over <code>X</code> times in the inner loop</li>
</ul>
<p>so the total iterations is <code>X * (1 + Y + Z)</code> which expands out to <code>X + XY + XZ</code></p>
<p>Where as the number of times your <code>pass</code> statement executes is <code>X * (Y+Z)</code> or <code>XY + XZ</code> which is different from the number of total iterations.</p>
<p>When the loops are structured instead like this:</p>
<pre><code>for y in ys:
for x in xs:
pass
for z in zs:
for x in xs:
pass
</code></pre>
<ul>
<li><code>ys</code> iterated once from first outer loop</li>
<li><code>xs</code> iterated <code>Y</code> times in first inner loop</li>
<li><code>zs</code> iterated once from second outer loop</li>
<li><code>xs</code> iterated <code>Z</code> times in second inner loop</li>
</ul>
<p>Meaning the total number of iterations is <code>Y*(1+X) + Z*(1 + X)</code> which expands out to <code>XY + XZ + Y + Z</code> Which is much different then the first equation.</p>
<p>however the number of <code>pass</code> statements that are executed are the same: <code>XY + XZ</code></p>
<p>So basically: the number of actual statements executed are the same, however the number of iterations (getting the next element of a list) is generally greater for the second example, and since <code>pass</code> took less time then the for loop overhead the latter is what you were actually measuring.</p>
| 2 | 2016-08-22T23:16:26Z | [
"python",
"algorithm"
] |
Python read named PIPE | 39,089,776 | <p>I have a named pipe in linux and i want to read it from python. The problem is that the python process 'consumes' one core (100%) continuously. My code is the following:</p>
<pre><code>FIFO = '/var/run/mypipe'
os.mkfifo(FIFO)
with open(FIFO) as fifo:
while True:
line = fifo.read()
</code></pre>
<p>I want to ask if the 'sleep' will help the situation or the process going to loss some input data from pipe. I can't control the input so i don't know the frequency of data input. I read about select and poll but i didn't find any example for my problem. Finally, i want to ask if the 100% usage will have any impact on the data input(loss or something?).</p>
<p>edit: I don't want to break the loop. I want the process runs continuously and 'hears' for data from the pipe.</p>
| 0 | 2016-08-22T22:40:19Z | 39,089,792 | <p>In typical UNIX fashion, <code>read(2)</code> returns 0 bytes to indicate end-of-file which can mean:</p>
<ul>
<li>There are no more bytes in a file</li>
<li>The other end of a socket has shutdown the connection</li>
<li>The writer has closed a pipe</li>
</ul>
<p>In your case, <code>fifo.read()</code> is returning an empty string, because the writer has closed its file descriptor. </p>
<p>You should detect that case and break out of your loop:</p>
<p><strong>reader.py</strong>:</p>
<pre><code>import os
import errno
FIFO = 'mypipe'
try:
os.mkfifo(FIFO)
except OSError as oe:
if oe.errno != errno.EEXIST:
raise
print("Opening FIFO...")
with open(FIFO) as fifo:
print("FIFO opened")
while True:
data = fifo.read()
if len(data) == 0:
print("Writer closed")
break
print('Read: "{0}"'.format(data))
</code></pre>
<p><strong>Example session</strong></p>
<p><em>Terminal 1</em>:</p>
<pre class="lang-none prettyprint-override"><code>$ python reader.py
Opening FIFO...
<blocks>
</code></pre>
<p><em>Terminal 2</em>:</p>
<pre class="lang-none prettyprint-override"><code>$ echo -n 'hello' > mypipe
</code></pre>
<p><em>Terminal 1</em>:</p>
<pre class="lang-none prettyprint-override"><code>FIFO opened
Read: "hello"
Writer closed
$
</code></pre>
<hr>
<h1>Update 1 - Continuously re-open</h1>
<p>You indicate that you want to keep listening for writes on the pipe, presumably even after a writer has closed.</p>
<p>To do this efficiently, you can (and should) take advantage of the fact that</p>
<blockquote>
<p>Normally, opening the FIFO blocks until the other end is opened also.</p>
</blockquote>
<p>Here, I add another loop around <code>open</code> and the <code>read</code> loop. This way, once the pipe is closed, the code will attempt to re-open it, which will block until another writer opens the pipe:</p>
<pre class="lang-none prettyprint-override"><code>import os
import errno
FIFO = 'mypipe'
try:
os.mkfifo(FIFO)
except OSError as oe:
if oe.errno != errno.EEXIST:
raise
while True:
print("Opening FIFO...")
with open(FIFO) as fifo:
print("FIFO opened")
while True:
data = fifo.read()
if len(data) == 0:
print("Writer closed")
break
print('Read: "{0}"'.format(data))
</code></pre>
<hr>
<p><em>Terminal 1</em>:</p>
<pre class="lang-none prettyprint-override"><code>$ python reader.py
Opening FIFO...
<blocks>
</code></pre>
<p><em>Terminal 2</em>:</p>
<pre class="lang-none prettyprint-override"><code>$ echo -n 'hello' > mypipe
</code></pre>
<p><em>Terminal 1</em>:</p>
<pre class="lang-none prettyprint-override"><code>FIFO opened
Read: "hello"
Writer closed
Opening FIFO...
<blocks>
</code></pre>
<p><em>Terminal 2</em>:</p>
<pre class="lang-none prettyprint-override"><code>$ echo -n 'hello' > mypipe
</code></pre>
<p><em>Terminal 1</em>:</p>
<pre class="lang-none prettyprint-override"><code>FIFO opened
Read: "hello"
Writer closed
Opening FIFO...
<blocks>
</code></pre>
<p>... and so on.</p>
<hr>
<p>You can learn more by reading the <code>man</code> page for pipes:</p>
<ul>
<li><a href="http://man7.org/linux/man-pages/man7/pipe.7.html" rel="nofollow">PIPE(7) - Linux Programmer's Manual</a></li>
<li><a href="http://man7.org/linux/man-pages/man7/fifo.7.html" rel="nofollow">FIFO(7) - Linux Programmer's Manual</a></li>
</ul>
| 2 | 2016-08-22T22:41:52Z | [
"python",
"linux",
"named-pipes"
] |
3 tables many to many how to create relationship | 39,089,863 | <p>I have tables name category, post and user.
Users can follow categories</p>
<blockquote>
<p>users are relationship many to many with categories
posts are relationship many to many with categories
users are relationship one to many posts
Now I want to get all posts from categories in which categories has follow user</p>
</blockquote>
| -4 | 2016-08-22T22:48:55Z | 39,094,935 | <p>So if I understand you right:</p>
<ul>
<li>You have an entity User. This user is categorized by several
categories. And a category has several Users too. </li>
<li>Also your entity Post is categorized by several categories and vice
versa.</li>
<li>And a user can make several posts and a post can belong to several
users</li>
</ul>
<p>So if that's what you want to have, you just need to model each relationship as a table:</p>
<pre><code>USER(KEY, NAME, ...)
CATEGORY(KEY, DESC, ...)
POST(KEY, CONTENT, ...)
USER_2_CATEGORY(USER_KEY, CATEGORY_KEY)
POST_2_CATEGORY(POST_KEY, CATEGORY_KEY)
USER_2_POST(USER_KEY, POST_KEY)
</code></pre>
| 0 | 2016-08-23T07:29:31Z | [
"python",
"sql",
"sqlalchemy",
"flask-sqlalchemy"
] |
How to traverse the files in a directory and sub-directories in python | 39,089,872 | <p>I have scenario to process the files in python</p>
<p>my process tree structure is like</p>
<pre><code>dirctory
.
...subdir1
.
....sub-sub-dir1
.
. ..file1
</code></pre>
<ol>
<li><p>First I need to go the subdir1 and read one by one sub-sub-dirs (1 to n) and get the file from the sub-sub-dir and process. </p></li>
<li><p>Like this process all the files in sub-sub-dirs then go back to the sub-dir
loop.</p></li>
<li><p>Read next subdir and read the one by one sub-sub-dirs and get the file from the sub-sub-dir and process.</p></li>
</ol>
<p>Please, help me out how can we do the above in Python. I would be grateful to you if I get a quick response.</p>
<p>Thanks</p>
| -2 | 2016-08-22T22:49:45Z | 39,090,067 | <p>Something like that:</p>
<pre><code>directory_dict = dict()
# Create the list of the sub_directories
dir_list = [sub_path for sub_path in os.listdir(given_path) if os.path.isdir(given_path+'/'+sub_path)]
# Loop into the list of sub_directories
for sub_dir in dir_list:
# Create an empty dict to store the informations
sub_dir_dict = dict()
# Create the list of the sub_sub_directories
sub_sub_dir_list = [sub_path for sub_path in os.listdir('%s/%s' % (given_path, sub_dir)) if os.path.isdir(given_path+'/'+sub_dir+'/'+sub_path)]
# Loop into the sub_sub_directories list
for sub_sub_dir in sub_sub_dir_list:
# Set current directory to the sub_sub_directory path
os.chdir(given_path+'/'+sub_dir+'/'+sub_sub_dir)
# Filter files
files = [dir_file for dir_file in os.listdir(given_path+'/'+sub_dir+'/'+sub_sub_dir) if os.path.isfile(os.path.join(given_path+'/'+sub_dir+'/'+sub_sub_dir, dir_file))]
# Store the list of file into the sub_directory dict at the proper key
sub_dir_dict[sub_sub_dir] = files
# Store the sub_dir dictionaries into the directory_dict at the proper key
directory_dict[sub_dir] = sub_dir_dict
</code></pre>
| 1 | 2016-08-22T23:10:11Z | [
"python",
"python-2.7"
] |
return statement vs. print statement? | 39,089,877 | <p>Can someone explain why this code only prints 6? :)</p>
<pre><code>def func(x):
result = 0
for i in range(x):
result = result + i
return result
print(func(4))
</code></pre>
| -4 | 2016-08-22T22:50:29Z | 39,089,961 | <p>First of all, since your code isn't formatted right in the question and I can't edit it due to a pending edit (which I bet fixes it), I'm going to assume your code is supposed to look like this:</p>
<pre><code>def func(x):
result = 0
for i in range(x):
result = result + i
return result
print(func(4))
</code></pre>
<p>Lets break it down step by step. Your print will call <code>func</code>, give it the number 4, and then print whatever number comes out. So control jumps to <code>func</code> and begins processing there, with the number 4 for <code>x</code>. You initialize result to 0, and then enter the loop. <code>for i in range(x)</code> will get you a list of numbers <code>[0, 1, 2, 3]</code> (not actually a list, but we can treat it this way for this simplified explanation). For each number <code>i</code> in that list, you are adding it to the current value of <code>result</code>. So <code>result</code> goes through these steps:</p>
<pre><code>result = 0 + 0
result = 0 + 1
result = 1 + 2
result = 3 + 3
</code></pre>
<p>The final value of <code>result</code> is 6, which is returned, and printed. That is where your 6 is coming from. If you call <code>func(5)</code>, you will get 10, since it goes through the same steps, but adds an additional 4 to the same computation. What this function does is add the numbers from <code>0</code> up to <code>x - 1</code> (at least for positive integer inputs).</p>
| 0 | 2016-08-22T22:59:16Z | [
"python",
"printing",
"return"
] |
Most effective way to compile lots of information from different websites | 39,089,907 | <p>My problem is at work I have to click on a link to a website, then copy the company name, company telephone number and company address to an excel spreadsheet, each one in a different column. This information is in the same place on every website and is just time consuming as I have to click each link and then copy and paste the information across.</p>
<p>I have knowledge of the Python programming language, I just wondered if the best way to go about this is using that language to search through the source of the website and be only left with the relevant information or if to use another programming language. Also, any suggestions on libraries to read up on for guidance? </p>
| -1 | 2016-08-22T22:53:43Z | 39,089,958 | <p>You can use <a href="https://www.crummy.com/software/BeautifulSoup/" rel="nofollow">BeautifulSoup</a> in combination with requests/urllib to scrape and parse the source code of the website.</p>
<p>Then you can use <a href="https://openpyxl.readthedocs.io/en/default/" rel="nofollow">Openpyxl</a> to write the data into an Excel spreadsheet.</p>
| 1 | 2016-08-22T22:59:06Z | [
"python"
] |
Most effective way to compile lots of information from different websites | 39,089,907 | <p>My problem is at work I have to click on a link to a website, then copy the company name, company telephone number and company address to an excel spreadsheet, each one in a different column. This information is in the same place on every website and is just time consuming as I have to click each link and then copy and paste the information across.</p>
<p>I have knowledge of the Python programming language, I just wondered if the best way to go about this is using that language to search through the source of the website and be only left with the relevant information or if to use another programming language. Also, any suggestions on libraries to read up on for guidance? </p>
| -1 | 2016-08-22T22:53:43Z | 39,089,974 | <p>I have used the Beautiful Soup Python library for this type of work before. It organizes all the HTML code in a way that you can extract whatever data you want from it easily. You can see an example here: <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/" rel="nofollow">https://www.crummy.com/software/BeautifulSoup/bs4/doc/</a></p>
| 0 | 2016-08-22T23:00:17Z | [
"python"
] |
Why am I getting an empty list as the answer? | 39,089,930 | <p>I am supposed to be printing out all values for r (which should be a list of 5 values) but for some reason I am getting an empty list [ ] as the answer. All of the inputs to the function are single values except for the lst variable, which is a list of 5 values. Any idea on why I am getting an empty list? All of the code I am using can be seen below. </p>
<pre><code>from math import pi
from sympy import solve
class SolarHeating:
def waterheated(self, T0, T, lst, Cp, Eg, r):
self.m = var('m')
self.T0 = T0
self.T = T
self.lst = lst
self.Cp = Cp
self.Eg = Eg
self.r = r
A = pi * self.r**2
Qt = self.Eg * A
F = [(self.T - self.T0) * self.m * self.Cp / Qt - x for x in self.lst]
self.m = solve(F, self.m)
return self.m
lst = [0, .25, .5, .75, 1.0]
a = SolarHeating()
m = a.waterheated(20, 40, lst, 4.2, .928, .128)
print(m)
</code></pre>
| -1 | 2016-08-22T22:55:32Z | 39,090,000 | <pre><code> ...
F = [(self.T-self.T0)*self.m*self.Cp/Qt-x for x in self.lst]
self.m = solve(F,self.m)
return self.m
</code></pre>
<p>This is most probably a math problem, not a code problem. Print the value of <code>F</code> and check that it really has a solution that <code>solve()</code> should return.</p>
| 2 | 2016-08-22T23:02:57Z | [
"python",
"sympy"
] |
Websocket: javascript as client and python as server, and web host on Linux | 39,090,006 | <p>I need to build a website in which Javascript is used as the client language to communicate with a python server over websockets. The website needs to be hosted on Linux. For now, I'm using command <code>python -m SimpleHTTPServer</code> to build a simple server, and the server is also on the Linux and using python. </p>
<p>How do I go about at setting up the javascript client websocket communication? Or how should I approach the architecture?</p>
| -4 | 2016-08-22T23:03:41Z | 39,090,351 | <p>Assuming that your python websocket server is up an running. You can connect with it through your website through either html5:</p>
<pre><code>socket= new WebSocket('ws://www.example.com:8000/somesocket');
socket.onopen= function() {
socket.send('hello');
};
socket.onmessage= function(s) {
alert('got reply '+s);
};
</code></pre>
<p>Or via</p>
<p><a href="http://raw-sockets.sysapps.org/#interface-tcpsocket" rel="nofollow">http://raw-sockets.sysapps.org/#interface-tcpsocket</a></p>
<p><a href="https://www.w3.org/TR/tcp-udp-sockets/" rel="nofollow">https://www.w3.org/TR/tcp-udp-sockets/</a></p>
<pre><code>navigator.tcpPermission.requestPermission({remoteAddress:"127.0.0.1", remotePort:6789}).then(
() => {
// Permission was granted
// Create a new TCP client socket and connect to remote host
var mySocket = new TCPSocket("127.0.0.1", 6789);
// Send data to server
mySocket.writeable.write("Hello World").then(
() => {
// Data sent sucessfully, wait for response
console.log("Data has been sent to server");
mySocket.readable.getReader().read().then(
({ value, done }) => {
if (!done) {
// Response received, log it:
console.log("Data received from server:" + value);
}
// Close the TCP connection
mySocket.close();
}
);
},
e => console.error("Sending error: ", e);
);
</code></pre>
<p>Whatever your server looks like, you always need to make sure your server and client use the same "protocol", i.e. they use the same variables to send and order in which to send them. </p>
<p>If you also need to set up a socket server in python, I suggest you look at some tutorials online as this is a non-trivial task: <a href="http://www.binarytides.com/python-socket-server-code-example/" rel="nofollow">http://www.binarytides.com/python-socket-server-code-example/</a></p>
| 0 | 2016-08-22T23:49:58Z | [
"javascript",
"python",
"websocket",
"server",
"tcp-ip"
] |
Upgrade packages with pip from inside code | 39,090,071 | <p>I saw an older question, suggesting to use pip.main(package), however this does not <em>upgrade</em> a package. I could not find anything. Thanks in advance.</p>
| 3 | 2016-08-22T23:10:40Z | 39,090,123 | <p>Try <code>pip.main(['install', '--upgrade', package])</code> instead. <code>pip.main</code> just takes arguments exactly like the command line version.</p>
| 3 | 2016-08-22T23:16:03Z | [
"python",
"python-3.x",
"pip"
] |
python, mongoengine - do like/regex search | 39,090,178 | <p>I know I can do a glob-type search on mongodb:</p>
<pre><code>db.person.find({ name: /*.bob.*/ })
</code></pre>
<p>or </p>
<pre><code>db.person.find({ name: { $regex: '*.bob.*' }})
</code></pre>
<p>How do I do this with mongoengine without using a raw query (which is apparently the only way based on my searches)?</p>
<p>I've blindly tried several variations like:</p>
<pre><code>Person.objects(name='/.*bob.*/')
Person.objects(name='/\.*bob\.*/')
Person.objects(name='.*bob.*')
Person.objects(name='\\.*bob\\.*')
</code></pre>
<p>etc, to no avail...</p>
| 0 | 2016-08-22T23:24:10Z | 39,133,617 | <p>It looks like you can do it this way:</p>
<pre><code>import re
regex = re.compile('.*bob.*')
Person.objects(name=regex)
</code></pre>
| 0 | 2016-08-24T21:53:52Z | [
"python",
"mongoengine"
] |
Calling xlwings from Excel "No module named..." Error | 39,090,252 | <p>I'm trying to learn the ropes of starting a Python script from Excel VBA using xlwings 0.9.2. According to the docs, I need to change the <code>PYTHONPATH</code> to the path for my py file. I've seen several versions of this question, and various answers, but none have addressed my specific scenario. I have a basic test module "module1.py" and an Excel file "Book2.xlsm" located on the desktop which has a button to run this macro:</p>
<pre><code>Sub macro1()
RunPython ("import module1.py; module1.run_all()")
End Sub
</code></pre>
<p>module1 goes like this:</p>
<pre><code>import xlwings as xw
def run_all():
wb.Book.caller()
xw.sheets("Sheet1").range("A1").value = "Done!"
return
</code></pre>
<p>I then imported the "xlwings.bas" file and edited the VBA code to read <code>PYTHONPATH = "C:\Users\bwamp\Desktop\module1\module1</code>, which refers to the subfolder that holds "module1.py" (full path: "C:\Users\bwamp\Desktop\module1\module1\module1.py", for clarity). Press the button to run <code>macro1</code> and I get the following error:</p>
<hr>
<h2>Error</h2>
<p>Traceback (most recent call last):</p>
<p>File "", line 1, in </p>
<p>ImportError: No module named 'module1.py'; 'module1' is not a package</p>
<h2>Press Ctrl+C to copy this message to the clipboard.</h2>
<h2>OK</h2>
<p>Any ideas what I'm doing wrong?</p>
| 1 | 2016-08-22T23:35:23Z | 39,095,131 | <p>You have two errors: You need to import your module without the <code>.py</code> ending: </p>
<pre><code>Sub macro1()
RunPython ("import module1; module1.run_all()")
End Sub
</code></pre>
<p>And it's <code>xw.Book.caller()</code> instead of <code>wb.Book.caller()</code>.</p>
| 0 | 2016-08-23T07:38:55Z | [
"python",
"vba",
"xlwings"
] |
Calling xlwings from Excel "No module named..." Error | 39,090,252 | <p>I'm trying to learn the ropes of starting a Python script from Excel VBA using xlwings 0.9.2. According to the docs, I need to change the <code>PYTHONPATH</code> to the path for my py file. I've seen several versions of this question, and various answers, but none have addressed my specific scenario. I have a basic test module "module1.py" and an Excel file "Book2.xlsm" located on the desktop which has a button to run this macro:</p>
<pre><code>Sub macro1()
RunPython ("import module1.py; module1.run_all()")
End Sub
</code></pre>
<p>module1 goes like this:</p>
<pre><code>import xlwings as xw
def run_all():
wb.Book.caller()
xw.sheets("Sheet1").range("A1").value = "Done!"
return
</code></pre>
<p>I then imported the "xlwings.bas" file and edited the VBA code to read <code>PYTHONPATH = "C:\Users\bwamp\Desktop\module1\module1</code>, which refers to the subfolder that holds "module1.py" (full path: "C:\Users\bwamp\Desktop\module1\module1\module1.py", for clarity). Press the button to run <code>macro1</code> and I get the following error:</p>
<hr>
<h2>Error</h2>
<p>Traceback (most recent call last):</p>
<p>File "", line 1, in </p>
<p>ImportError: No module named 'module1.py'; 'module1' is not a package</p>
<h2>Press Ctrl+C to copy this message to the clipboard.</h2>
<h2>OK</h2>
<p>Any ideas what I'm doing wrong?</p>
| 1 | 2016-08-22T23:35:23Z | 39,474,566 | <p>I had the same error. Solved by downgrade to xlwings version 0.7.2</p>
| 0 | 2016-09-13T16:08:54Z | [
"python",
"vba",
"xlwings"
] |
How to make application urls appear throughout the project? | 39,090,298 | <p>My templates don't see URLs which are in my application, in code:</p>
<pre><code>urls.py in project:
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^', include('search.urls')),
url(r'^accounts/', include('accounts.urls')),
]
urls.py in application:
urlpatterns = [
url(r'^', include('registration.backends.simple.urls')),
]
</code></pre>
<p>I have error and I know why:</p>
<pre><code>NoReverseMatch at /accounts/login/
Reverse for 'auth_password_reset' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: []
<p>{% trans "Forgot your password?" %} <a href="{% url 'auth_password_reset' %}">{% trans "Reset it" %}</a>.</p>
</code></pre>
<p>But when I put <code>include('registration.backends.simple.urls')</code> in project urls
everything is good. I know I can have a namespace my URL, but I don't want do this.</p>
<p>I want to <strong><em>see</em></strong> only my URLs from my app in all my application, and I don't want put my URLs in root <code>urls.py</code>. I want them in a separate file. </p>
<p>Can you do something about it ?</p>
| 2 | 2016-08-22T23:42:15Z | 39,090,414 | <p>Need to terminate your regex strings with $, i.e,</p>
<pre><code>r'^admin/$',
</code></pre>
| 0 | 2016-08-22T23:59:36Z | [
"python",
"django"
] |
How to allow many responses for if statement and replies? | 39,090,322 | <p>I am making a sort of Siri program. But I'm not sure how to allow various responses, and various replies at random.</p>
<p>Does it involve dictionaries or a simpler alternative, or a random function? </p>
<pre><code>if greeting == "Hello", "Hi", "Hey":
print("Hello", "Hi", "Hey")
else:
print("I'm not sure what you said there")
</code></pre>
| -1 | 2016-08-22T23:45:20Z | 39,090,408 | <p>To pick a random response you can use <code>random.choice</code>, which selects a random element from a list:</p>
<pre><code>import random
if greeting in ["Hello", "Hi", "Hey"]:
response = random.choice(["Hello", "Hi", "Hey"])
print(response)
else:
print("I'm not sure what you said there")
</code></pre>
| 1 | 2016-08-22T23:58:31Z | [
"python"
] |
How to allow many responses for if statement and replies? | 39,090,322 | <p>I am making a sort of Siri program. But I'm not sure how to allow various responses, and various replies at random.</p>
<p>Does it involve dictionaries or a simpler alternative, or a random function? </p>
<pre><code>if greeting == "Hello", "Hi", "Hey":
print("Hello", "Hi", "Hey")
else:
print("I'm not sure what you said there")
</code></pre>
| -1 | 2016-08-22T23:45:20Z | 39,090,412 | <p>If you're talking about allowing multiple inputs from the user, that would go something like this:</p>
<pre><code>if greeting in ["hello", "hi", "hey"]:
# do stuff
</code></pre>
<p>If you also want to provide a random response back to the user, you could do something like this:</p>
<pre><code>if greeting in ["hello", "hi", "hey"]:
response = random.choice(["hello", "hi", "hey"])
</code></pre>
| 0 | 2016-08-22T23:59:24Z | [
"python"
] |
Handling "with open()" errors? | 39,090,358 | <p>So I got this code here:</p>
<pre><code>with open(os.path.join(Path, 'ki/lol/kappa/file.txt'), 'r') as masterfile:
</code></pre>
<p>How can I add a function that tells the user that the file "file.txt" was not found in this directory? I get an error which is called <code>IOError [Errno 2] No such file in this directory</code> after starting my program. How can I show a message like "No file found here" instead of having this error appearing?</p>
| -2 | 2016-08-22T23:50:30Z | 39,090,377 | <p>You use a <code>try</code> statement. This is called Exception Handling. See <a href="https://docs.python.org/3/tutorial/errors.html" rel="nofollow">Python docs</a> to learn more.</p>
| 0 | 2016-08-22T23:53:36Z | [
"python"
] |
Handling "with open()" errors? | 39,090,358 | <p>So I got this code here:</p>
<pre><code>with open(os.path.join(Path, 'ki/lol/kappa/file.txt'), 'r') as masterfile:
</code></pre>
<p>How can I add a function that tells the user that the file "file.txt" was not found in this directory? I get an error which is called <code>IOError [Errno 2] No such file in this directory</code> after starting my program. How can I show a message like "No file found here" instead of having this error appearing?</p>
| -2 | 2016-08-22T23:50:30Z | 39,090,379 | <p>You need to catch the exception.</p>
<pre><code>try:
with open(os.path.join(Path, 'ki/lol/kappa/file.txt'), 'r') as masterfile:
print "yay"
except IOError:
print "Oops, couldn't open the file"
</code></pre>
| 0 | 2016-08-22T23:53:37Z | [
"python"
] |
Scientific notation in python | 39,090,359 | <p>Hi I know that to print a number in a scientific notation I can do the following</p>
<pre><code>"%.3e" % 123.456
</code></pre>
<p>will give</p>
<pre><code>1.234e+02
</code></pre>
<p>however how can I obtain </p>
<pre><code>12.34e+01?
</code></pre>
| 2 | 2016-08-22T23:50:41Z | 39,090,443 | <p>For clarification, most usages of <a href="https://en.wikipedia.org/wiki/Scientific_notation" rel="nofollow">Scientific Notation</a> refers to <a href="https://en.wikipedia.org/wiki/Scientific_notation#Normalized_notation" rel="nofollow">Normalized Notation</a> which requires that the leading number be at least 1 but less than 10. In <a href="https://en.wikipedia.org/wiki/Scientific_notation#Engineering_notation" rel="nofollow">Engineering Notation</a>, the exponent is a multiple of three. These are the two most commonly used versions of Scientific Notation.</p>
| 3 | 2016-08-23T00:05:06Z | [
"python"
] |
How to parse raw HTTP request in Python 3? | 39,090,366 | <p>I am looking for a native way to parse an http request in Python 3.</p>
<p><a href="http://stackoverflow.com/questions/4685217/parse-raw-http-headers">This question</a> shows a way to do it in Python 2, but uses now deprecated modules, (and Python 2) and I am looking for a way to do it in Python 3.</p>
<p>I would mainly like to just figure out what resource is requested and parse the headers and from a simple request. (i.e):</p>
<pre><code>GET /index.html HTTP/1.1
Host: localhost
Connection: keep-alive
Cache-Control: max-age=0
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-US,en;q=0.8
</code></pre>
<p>Can someone show me a basic way to parse this request?</p>
| 1 | 2016-08-22T23:52:13Z | 39,090,882 | <p>Each one of those field names should be delimited by carriage return then newline, and then the field name and value are delimited by a colon. So assuming you already have the response as a string, it <em>should</em> be as easy as:</p>
<pre><code>fields = resp.split("\r\n")
fields = fields[1:] #ignore the GET / HTTP/1.1
output = {}
for field in fields:
key,value = field.split(':')#split each line by http field name and value
output[key] = value
</code></pre>
| 0 | 2016-08-23T01:13:08Z | [
"python",
"python-3.x",
"http"
] |
How to parse raw HTTP request in Python 3? | 39,090,366 | <p>I am looking for a native way to parse an http request in Python 3.</p>
<p><a href="http://stackoverflow.com/questions/4685217/parse-raw-http-headers">This question</a> shows a way to do it in Python 2, but uses now deprecated modules, (and Python 2) and I am looking for a way to do it in Python 3.</p>
<p>I would mainly like to just figure out what resource is requested and parse the headers and from a simple request. (i.e):</p>
<pre><code>GET /index.html HTTP/1.1
Host: localhost
Connection: keep-alive
Cache-Control: max-age=0
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-US,en;q=0.8
</code></pre>
<p>Can someone show me a basic way to parse this request?</p>
| 1 | 2016-08-22T23:52:13Z | 39,091,087 | <p>You could use the <a href="https://docs.python.org/3/library/email.message.html#email.message.Message" rel="nofollow"><code>email.message.Message</code></a> class from the <a href="https://docs.python.org/3/library/email.html" rel="nofollow"><code>email</code></a> module in the standard library. </p>
<p>By modifying the <a href="http://stackoverflow.com/a/4685559/16148">answer</a> from the question you linked, below is a Python3 example of parsing HTTP headers.</p>
<p>Suppose you wanted to create a dictionary containing all of your header fields:</p>
<pre><code>import email
import pprint
from io import StringIO
request_string = 'GET / HTTP/1.1\r\nHost: localhost\r\nConnection: keep-alive\r\nCache-Control: max-age=0\r\nUpgrade-Insecure-Requests: 1\r\nUser-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36\r\nAccept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8\r\nAccept-Encoding: gzip, deflate, sdch\r\nAccept-Language: en-US,en;q=0.8'
# pop the first line so we only process headers
_, headers = request_string.split('\r\n', 1)
# construct a message from the request string
message = email.message_from_file(StringIO(headers))
# construct a dictionary containing the headers
headers = dict(message.items())
# pretty-print the dictionary of headers
pprint.pprint(headers, width=160)
</code></pre>
<p>if you ran this at a python prompt, the result would look like:</p>
<pre><code>{'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
'Accept-Encoding': 'gzip, deflate, sdch',
'Accept-Language': 'en-US,en;q=0.8',
'Cache-Control': 'max-age=0',
'Connection': 'keep-alive',
'Host': 'localhost',
'Upgrade-Insecure-Requests': '1',
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36'}
</code></pre>
| 1 | 2016-08-23T01:42:57Z | [
"python",
"python-3.x",
"http"
] |
Rolling Time Series AR(1) Regression Estimation in Python dataframe and MovingOLS? | 39,090,442 | <p>2 questions here:</p>
<p>First. I have a dataframe like this:</p>
<pre><code> Date Y X1 X2 X3
22 2004-05-12 9.348158e-09 0.000081 0.000028 0.000036
23 2004-05-13 9.285989e-09 0.000073 0.000081 0.000097
24 2004-05-14 9.732308e-09 0.000085 0.000073 0.000096
25 2004-05-17 2.235977e-08 0.000089 0.000085 0.000099
26 2004-05-18 2.792661e-09 0.000034 0.000089 0.000150
27 2004-05-19 9.745323e-09 0.000048
1000 2004-05-20 1.835462e-09 0.000034 0.000048 0.000099
1001 2004-05-21 3.529089e-09 0.000037 0.000034 0.000043
1002 2004-05-24 3.453047e-09 0.000043 0.000037 0.000059
1003 2004-05-25 2.963131e-09 0.000038 0.000043 0.000059
1004 2004-05-26 1.390032e-09 0.000029 0.000038 0.000054
</code></pre>
<p>I want to run a rolling 100-day window OLS regression estimation, which is: </p>
<p>First for the 101st row, I run a AR(1) regression of Y using the 1st to 100th rows, and estimate Y for the 101st row;</p>
<p>Then for the 102nd row, I run a AR(1) regression of Y using the 2nd to 101st rows, and estimate Y for the 102nd row;</p>
<p>Then for the 103rd row, I run a AR(1) regression of Y using the 2nd to 101st rows, and estimate Y for the 103rd row;</p>
<p>......</p>
<p>Until the last row.</p>
<p>I'm now using the following code for an AR(1) regression:</p>
<pre><code>df = pd.DataFrame({'data':data_in['Y'],'Date':data_in['Date']})
df = df.set_index('Date')
ar = statsmodels.tsa.ar_model.AR(df)
res_ar = ar.fit(maxlag=1)
</code></pre>
<p>Of course it's free to use any possible method to achieve the goal. How to do thisï¼</p>
<p>Second. When I use MovingOLS, the output is like this:</p>
<pre><code>-------------------------Summary of Regression Analysis-------------------------
Formula: Y ~ <RV(t-1)> + <RV(t-1)*RQ(t-1)^0.5> + <RV(t-1|t-5)> + <RV(t-1|t-22)>
+ <intercept>
Number of Observations: 1420
Number of Degrees of Freedom: 5
R-squared: 0.3370
Adj R-squared: 0.3352
Rmse: 0.0001
F-stat (4, 1415): 179.8353, p-value: 0.0000
Degrees of Freedom: model 4, resid 1415
-----------------------Summary of Estimated Coefficients------------------------
Variable Coef Std Err t-stat p-value CI 2.5% CI 97.5%
--------------------------------------------------------------------------------
RV(t-1) 0.5031 0.0496 10.14 0.0000 0.4058 0.6003
RV(t-1)*RQ(t-1)^0.5 -55.2344 10.1137 -5.46 0.0000 -75.0573 -35.4115
RV(t-1|t-5) 0.1736 0.0542 3.20 0.0014 0.0673 0.2799
RV(t-1|t-22) 0.2381 0.0563 4.23 0.0000 0.1276 0.3485
intercept 0.0000 0.0000 2.22 0.0268 0.0000 0.0000
---------------------------------End of Summary---------------------------------
</code></pre>
<p>How does it integrate many regression results into such a summaryï¼</p>
| 0 | 2016-08-23T00:05:04Z | 39,091,166 | <p>You are trying to model your samples with an equation. This equation has many parameters (called estimators). The value of the estimator will change depending on the training data that is used to calculate it. When you are estimating such model parameters using cross-validation on your data this means that you will get a distribution for each of these parameters. Basically <code>Coef</code> will be the average of the estimator and <code>Std Err</code> will be its standard deviation. The other numbers tell you about the confidence that these statistics about your estimators are correct.</p>
| 0 | 2016-08-23T01:54:22Z | [
"python",
"pandas",
"dataframe"
] |
Json add additional payload in the request | 39,090,448 | <p>I am very new to Python. I run into this problem and hope you can help. Let me explain what I try to do and let me know if I am confusing you.</p>
<p>I have this Python script and it works fine with creating an event.</p>
<pre><code># Set the request parameters
url = 'https://outlook.office365.com/api/v1.0/me/events?$Select=Start,End'
user = 'user1@domain.com'
pwd = getpass.getpass('Please enter your AD password: ')
# Create JSON payload
data = {
"Subject": "Testing Outlock Event",
"Body": {
"ContentType": "HTML",
"Content": "Test Content"
},
"Start": "2016-05-23T15:00:00.000Z",
"End": "2016-05-23T16:00:00.000Z",
"Attendees": [
{
"EmailAddress": {
"Address": "user1@domain.com",
"Name": "User1"
},
"Type": "Required" },
{
"EmailAddress": {
"Address": "user2@domain.com",
"Name": "User2"
},
"Type": "Optional" }
]
}
json_payload = json.dumps(data)
# Build the HTTP request
opener = urllib2.build_opener(urllib2.HTTPHandler)
request = urllib2.Request(url, data=json_payload)
auth = base64.encodestring('%s:%s' % (user, pwd)).replace('\n', '')
request.add_header('Authorization', 'Basic %s' % auth)
request.add_header('Content-Type', 'application/json')
request.add_header('Accept', 'application/json')
request.get_method = lambda: 'POST'
# Perform the request
result = opener.open(request)
</code></pre>
<p>Since other posts suggest to set properties for Json separately (<a href="https://social.msdn.microsoft.com/Forums/en-US/223b2e54-4b3f-4f3d-822a-534c93b18b1f/outlook-calendar-office-365-rest-api-creating-meeting-with-attachment-in-it?forum=appsforoffice" rel="nofollow">here</a>) for the attachment, so I include the data_attachment code below in addition to the request (see "data_attachment" and "json_payloadAttachment"). However, I am not sure how to add that in the request and make one POST.</p>
<pre><code># Set the request parameters
url = 'https://outlook.office365.com/api/v1.0/me/events?$Select=Start,End'
user = 'user1@domain.com'
pwd = getpass.getpass('Please enter your AD password: ')
# Create JSON payload
data = {
"Subject": "Testing Outlock Event",
"Body": {
"ContentType": "HTML",
"Content": "Test Content"
},
"Start": "2016-05-23T15:00:00.000Z",
"End": "2016-05-23T16:00:00.000Z",
"Attendees": [
{
"EmailAddress": {
"Address": "user1@domain.com",
"Name": "User1"
},
"Type": "Required" },
{
"EmailAddress": {
"Address": "user2@domain.com",
"Name": "User2"
},
"Type": "Optional" }
]
}
data_attachment = {
"@odata.type": "#Microsoft.OutlookServices.FileAttachment",
"Name": "test123.txt",
"ContentBytes": "VGVzdDEyMw=="
}
json_payload = json.dumps(data)
json_payloadAttachment = json.dumps(data_attachment)
# Build the HTTP request
opener = urllib2.build_opener(urllib2.HTTPHandler)
request = urllib2.Request(url, data=json_payload) # NOT Sure where to put the attachment payload here
auth = base64.encodestring('%s:%s' % (user, pwd)).replace('\n', '')
request.add_header('Authorization', 'Basic %s' % auth)
request.add_header('Content-Type', 'application/json')
request.add_header('Accept', 'application/json')
request.get_method = lambda: 'POST'
# Perform the request
result = opener.open(request)
</code></pre>
<p>Please help. Thanks in advance.</p>
| 0 | 2016-08-23T00:06:12Z | 39,090,601 | <p>It appears that you need to merge the data; for example you can add another key to your data dictionary called <code>Attachments</code> which contains an array of dictionaries and merge them that way; then serialize your data to JSON.
You don't need <code>json_payloadAttachment</code>.</p>
<pre><code>...
data["Attachments"] = [data_attachment]
json_payload = json.dumps(data)
</code></pre>
<p>You're also missing the <code>HasAttachments</code> key according to the link you posted.</p>
<pre><code>data["HasAttachments"] = True
</code></pre>
| 1 | 2016-08-23T00:31:16Z | [
"python",
"json"
] |
a python library that accepts some text, and replaces phone numbers, names, and so on with tokens | 39,090,495 | <p>I need a python library that accepts some text, and replaces phone numbers, names, and so on with tokens. Example:</p>
<p>Input: Please call Robert on 0430013454 to discuss this further.</p>
<p>Output: Please call <em>NAME</em> on <em>PHONE</em> to discuss this further.</p>
<p>In other words I need to take a sentence, any sentence, then the program will be run on that sentence and remove anything that looks like a name, phone number or any other identifier, and replace it with a token I.E <em>NAME</em>, <em>PHONE NUMBER</em> So that token would just be text to replace the info so that it is no longer displayed.</p>
<p>Must be python 2.7 compatible. Would anybody know how this would be done? </p>
<p>Cheers!</p>
| -6 | 2016-08-23T00:15:19Z | 39,091,018 | <p>Not really sure about name recognition. However, if you know the names that you would be looking for it would be easy. You could have a list of all of the names that you're looking for and check to see if each one is in the string and if so just use <code>string.replace</code>. If the names are random you could maybe look into NLTK I think they might have some name entity recognition. I really don't know anything about it though...</p>
<p>But as for phone numbers, that's easy. You can split the string into a list and check to see if any element consists of numbers. You could even check the length to make sure it's 10 digits (i'm assuming all numbers will be 10 based on your example).</p>
<p>Something like this...</p>
<pre><code>example_input = 'Please call Robert on 0430013454 to discuss this further.'
new_list = example_input.split(' ')
for word in new_list:
if word.isdigit():
pos = new_list.index(word)
new_list[pos] = 'PHONE'
example_output = ' '.join(new_list)
print example_output
</code></pre>
<p>This would be the output: <code>'Please call Robert on PHONE to discuss this further'</code></p>
<p>The if statement would be something like <code>if word.isdigit() and len(word) == 10:</code> if you wanted to make sure the length of the digits is 10.</p>
| 0 | 2016-08-23T01:32:32Z | [
"python",
"python-2.7",
"pyparsing"
] |
a python library that accepts some text, and replaces phone numbers, names, and so on with tokens | 39,090,495 | <p>I need a python library that accepts some text, and replaces phone numbers, names, and so on with tokens. Example:</p>
<p>Input: Please call Robert on 0430013454 to discuss this further.</p>
<p>Output: Please call <em>NAME</em> on <em>PHONE</em> to discuss this further.</p>
<p>In other words I need to take a sentence, any sentence, then the program will be run on that sentence and remove anything that looks like a name, phone number or any other identifier, and replace it with a token I.E <em>NAME</em>, <em>PHONE NUMBER</em> So that token would just be text to replace the info so that it is no longer displayed.</p>
<p>Must be python 2.7 compatible. Would anybody know how this would be done? </p>
<p>Cheers!</p>
| -6 | 2016-08-23T00:15:19Z | 39,091,553 | <p>As Harrison pointed out, nltk has named entity recognition, which is what you want for this task. <a href="https://gist.github.com/onyxfish/322906" rel="nofollow">Here</a> is a good sample to get you started.</p>
<p>From the site:</p>
<pre><code>import nltk
sentences = nltk.sent_tokenize(text)
tokenized_sentences = [nltk.word_tokenize(sentence) for sentence in sentences]
tagged_sentences = [nltk.pos_tag(sentence) for sentence in tokenized_sentences]
chunked_sentences = nltk.ne_chunk_sents(tagged_sentences, binary=True)
def extract_entity_names(t):
entity_names = []
if hasattr(t, 'label') and t.label:
if t.label() == 'NE':
entity_names.append(' '.join([child[0] for child in t]))
else:
for child in t:
entity_names.extend(extract_entity_names(child))
return entity_names
entity_names = []
for tree in chunked_sentences:
# Print results per sentence
# print extract_entity_names(tree)
entity_names.extend(extract_entity_names(tree))
# Print all entity names
#print entity_names
# Print unique entity names
print set(entity_names)
</code></pre>
| 1 | 2016-08-23T02:48:54Z | [
"python",
"python-2.7",
"pyparsing"
] |
How to get z to show up properly in Pyplot math mode | 39,090,559 | <p>I'm trying to create an axis label for a graph made using matplotlib.pyplot, and I'm using math mode for subscripts and superscripts. However, whenever I try to put a z inside math mode, it instead comes out as an approximately equals sign. Anyone know how to fix it? It shows up normally if I put it outside math mode, but that puts an unacceptable space between the H and the z. Here's my python program:</p>
<pre><code>import matplotlib.pyplot as plt
import numpy as np
h = 6.626e-34
c = 3.0e+8
k = 1.38e-23
def planck(w):
intensity = 2*h*w**3/((c**2)*(np.exp(h*w/(k*10000))-1))
return intensity
wavelength = np.logspace(-4,16,1000)
intensity = planck(wavelength)
plt.loglog(wavelength,intensity,'k')
plt.ylim([1e-20,1e-6])
plt.xlim([1e7,1e17])
plt.ylabel(r"$I_\nu \ (W m^{-2} \! {Hz}^{-1} \! sr^{-1})$")
plt.show()
</code></pre>
<p>On another note, is there a way to increase the size of specific characters inside of math mode in matplotlib?</p>
| 0 | 2016-08-23T00:24:57Z | 39,090,681 | <p>It's not really an approximately-equals sign, it's just an italic z whose diagonal stroke is invisible in the font and size you're using. Making it bigger clarifies things:</p>
<pre><code>plt.ylabel(r"$I_\nu \ (W m^{-2} \! {Hz}^{-1} \! sr^{-1})$", fontsize="x-large")
</code></pre>
| 0 | 2016-08-23T00:41:39Z | [
"python",
"matplotlib",
"tex"
] |
JSON to CSV in python: each JSON file has different keys | 39,090,683 | <p>I'm trying to write many JSON files to a CSV file. Each JSON file has several keys, but different files have different keys. Here are three JSON files as an example.</p>
<p>file A:</p>
<pre><code>{"a": 1, "c": 2}
</code></pre>
<p>file B: </p>
<pre><code>{"b": 5, "d": 3}
</code></pre>
<p>file C:</p>
<pre><code>{"a": 6, "b": 7}
</code></pre>
<p>I'd like one CSV file like this with four columns and three rows (commas omitted for simplicity):</p>
<pre><code>a b c d
1 2
5 3
6 7
</code></pre>
<p>One way to do this is by multiple try/except statements using csv writer. But that becomes infeasible as I am dealing with a large number of keys. Are there any alternatives?</p>
| 1 | 2016-08-23T00:41:52Z | 39,090,775 | <p>You could load each individual dictionary with the missing keys and give them null values. So it might look like this</p>
<pre><code>for items in list:
for x in ['a','b','c','d']:
if x not in item:
item[x] = ""
</code></pre>
<p>Now that each dictionary has the same keys, you should be able to write the csv easily in the format you want.</p>
| 2 | 2016-08-23T00:55:05Z | [
"python",
"json",
"csv"
] |
JSON to CSV in python: each JSON file has different keys | 39,090,683 | <p>I'm trying to write many JSON files to a CSV file. Each JSON file has several keys, but different files have different keys. Here are three JSON files as an example.</p>
<p>file A:</p>
<pre><code>{"a": 1, "c": 2}
</code></pre>
<p>file B: </p>
<pre><code>{"b": 5, "d": 3}
</code></pre>
<p>file C:</p>
<pre><code>{"a": 6, "b": 7}
</code></pre>
<p>I'd like one CSV file like this with four columns and three rows (commas omitted for simplicity):</p>
<pre><code>a b c d
1 2
5 3
6 7
</code></pre>
<p>One way to do this is by multiple try/except statements using csv writer. But that becomes infeasible as I am dealing with a large number of keys. Are there any alternatives?</p>
| 1 | 2016-08-23T00:41:52Z | 39,090,778 | <p>You can append each JSON file to a list and then create dataframes and concatenate.</p>
<pre><code>a = {"a": 1, "c": 2}
b = {"b": 5, "d": 3}
c = {"a": 6, "b": 7}
data = [a, b, c]
>>> pd.concat([pd.DataFrame(s, index=[0]) for s in data]).reset_index()
a b c d
0 1 NaN 2 NaN
1 NaN 5 NaN 3
2 6 7 NaN NaN
</code></pre>
| 2 | 2016-08-23T00:55:51Z | [
"python",
"json",
"csv"
] |
JSON to CSV in python: each JSON file has different keys | 39,090,683 | <p>I'm trying to write many JSON files to a CSV file. Each JSON file has several keys, but different files have different keys. Here are three JSON files as an example.</p>
<p>file A:</p>
<pre><code>{"a": 1, "c": 2}
</code></pre>
<p>file B: </p>
<pre><code>{"b": 5, "d": 3}
</code></pre>
<p>file C:</p>
<pre><code>{"a": 6, "b": 7}
</code></pre>
<p>I'd like one CSV file like this with four columns and three rows (commas omitted for simplicity):</p>
<pre><code>a b c d
1 2
5 3
6 7
</code></pre>
<p>One way to do this is by multiple try/except statements using csv writer. But that becomes infeasible as I am dealing with a large number of keys. Are there any alternatives?</p>
| 1 | 2016-08-23T00:41:52Z | 39,090,794 | <p>Assuming you know all the possible field names ahead of time <a href="https://docs.python.org/3.5/library/csv.html#csv.DictWriter" rel="nofollow"><code>csv.DictWriter</code></a> already comes with a solution for this, use the <code>restval</code> argument to the constructor:</p>
<blockquote>
<p>If the row read has fewer fields than the fieldnames sequence, the
remaining keys take the value of the optional <code>restval</code> parameter.</p>
</blockquote>
<p>so specifying <code>csv.DictWriter(..., restval=" ")</code> would replace any missing values with a single space although by default <code>restval</code> is set to <code>""</code> (an empty string) which will probably be more useful to you anyway.</p>
<p>so basically your code would look like this:</p>
<pre><code>import csv, json
all_fields = ["a","b","c","d"]
all_files = ["A.json","B.json","C.json"]
with open("OUTPUT.csv", "w") as output_file:
writer = csv.DictWriter(output_file,all_fields)
writer.writeheader()
for filename in all_files:
with open(filename,"r") as in_file:
writer.writerow(json.load(in_file))
</code></pre>
| 2 | 2016-08-23T00:57:15Z | [
"python",
"json",
"csv"
] |
JSON to CSV in python: each JSON file has different keys | 39,090,683 | <p>I'm trying to write many JSON files to a CSV file. Each JSON file has several keys, but different files have different keys. Here are three JSON files as an example.</p>
<p>file A:</p>
<pre><code>{"a": 1, "c": 2}
</code></pre>
<p>file B: </p>
<pre><code>{"b": 5, "d": 3}
</code></pre>
<p>file C:</p>
<pre><code>{"a": 6, "b": 7}
</code></pre>
<p>I'd like one CSV file like this with four columns and three rows (commas omitted for simplicity):</p>
<pre><code>a b c d
1 2
5 3
6 7
</code></pre>
<p>One way to do this is by multiple try/except statements using csv writer. But that becomes infeasible as I am dealing with a large number of keys. Are there any alternatives?</p>
| 1 | 2016-08-23T00:41:52Z | 39,090,816 | <p>This works :</p>
<pre><code>csv_separator = ';'
data = [{"a": 1, "c": 2},
{"b": 5, "d": 3},
{"a": 6, "b": 7}]
headers = sorted(list(set(sum([list(l.keys()) for l in data], []))))
with open('output.csv', 'w+') as f:
f.write(csv_separator.join(headers))
for l in data:
line_elements = []
for k in headers:
try:
line_elements.append(str(l[k]))
except: # key not in dict, append empty string, i'll let you catch the exception properly
line_elements.append('')
f.write(csv_separator.join(line_elements))
# Output :
# a;b;c;d
# 1;;2;
# ;5;;3
# 6;7;;
</code></pre>
| 0 | 2016-08-23T01:00:39Z | [
"python",
"json",
"csv"
] |
about tree.DecisionTreeClassifier adjust class_weight | 39,090,706 | <p>I have a unbalanced dataset, there are totally 209 rows (samples) which include 166 rows (class0) and 43 rows (class1).
Therefore, I want to solve the unbalanced problem,
then I used the python instruction to adjust the class weight.</p>
<pre><code>tree.DecisionTreeClassifier(max_depth=4,class_weight={1:3.8})
clf.fit(scale_data, data_answer
</code></pre>
<p>Finally, in the result (fig.1), samples are still 209 but values became 166.0 (class0) and 166.34 (class1). The class1 samples the digits after decimal.
I can not explain the result, even can not compile the source code which is written by Cpython (<a href="https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tree/_tree.pyx#L1948" rel="nofollow">https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tree/_tree.pyx#L1948</a>>)
Could anyone help me?
Thank you.</p>
<p><a href="http://i.stack.imgur.com/tcAWk.png" rel="nofollow">fig.1</a></p>
| 0 | 2016-08-23T00:45:27Z | 39,091,079 | <p>Class 1 doesn't "sample the digits after the decimal." I'm not sure what that even means. Instead, the samples are weighted, so the value is 43*3.8 = 163.4</p>
| 0 | 2016-08-23T01:42:21Z | [
"python",
"tree",
"classification"
] |
Webpage contained within one dynamic page, unable to use driver interactions with Selenium (Python) | 39,090,768 | <p>The homepage for the web application I'm testing has a loading screen when you first load it, then a username/password box appears. It is a dynamically generated UI element and the cursor defaults to being inside the username field.</p>
<p>I looked around and someone suggested using action chains. When I use action chains, I can immediately input text into the username and password fields and then press enter and the next page loads fine. Unfortunately, action chains are not a viable long-term answer for me due to my particular setup.</p>
<p>When I use the webdriver's <code>find_element_by_id</code> I am able to locate it and I am not able to <code>send_keys</code> to the element though because it is somehow not visible. I receive </p>
<blockquote>
<p>selenium.common.exceptions.ElementNotVisibleException: Message: element not visible. </p>
</blockquote>
<p>I'm also not able to click the field or otherwise interact with it without getting this error.</p>
<p>I have also tried identifying and interacting with the elements via other means, such as "xpaths" and css, to no avail. They are always <code>not visible</code>.</p>
<p>Strangely, it works with dynamic page titles. When the page first loads it is <code>Loading...</code> and when finished it is <code>Login</code>. The driver will return the current title when <code>driver.title</code> is called.</p>
<p>Does anyone have a suggestion?</p>
| 1 | 2016-08-23T00:53:52Z | 39,091,571 | <p>Actually if there is loading progress bar appears in you login page, You should try using <a href="http://selenium-python.readthedocs.io/waits.html#explicit-waits" rel="nofollow"><code>WebDriverWait</code></a> to wait until element is getting visible as below :-</p>
<pre><code>from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
wait = WebDriverWait(driver, 10)
element = wait.until(EC.visibility_of_element_located((By.ID, "enter element id here")))
# now use send_keys
element.send_keys("enter value here")
</code></pre>
<p><strong>Edited1</strong> :- If you're getting <code>TimeoutException</code>, I would suggest you try to wait before finding element to to be invisible loading progress bar using <code>WebDriverWait</code> instead of hard coded sleep wait then find desire element as below :-</p>
<pre><code>wait = WebDriverWait(driver, 10)
wait.until(EC.invisibility_of_element_located((By.ID, "enter loading progress bar id or other locators here")))
#now after invisible of loading progress bar wait for desire element
element = wait.until(EC.presence_of_element_located((By.ID, "enter element id here")))
# now use send_keys
element.send_keys("enter value here")
</code></pre>
<p><strong>Edited2</strong> :- actually <code>presence_of_element_located</code> of element just checking element present on the DOM or not while <code>visibility_of_element_located</code> checking present and visible both, means <code>presence_of_element_located</code> also able to find hidden element as well as visible element while visibility gets only visible that's why <code>presence_of_element_located</code> works.</p>
<p>Now problem during <code>send_keys</code>, because selenium can not be intract to element until it's not visible that's why you are in trouble may be there are some hidden <code>CSS</code> works on desire element which makes it invisible that's why selenium unable to interact with it but don't worry you are still able to set value using <code>execute_script</code>.</p>
<p>Now you can try to set value on input element instead of using <code>send_keys</code> after element finding as :-</p>
<pre><code>driver.execute_script("arguments[0].value = arguments[1]", element, "enter your value here")
</code></pre>
| 1 | 2016-08-23T02:50:41Z | [
"python",
"selenium",
"testing"
] |
Webpage contained within one dynamic page, unable to use driver interactions with Selenium (Python) | 39,090,768 | <p>The homepage for the web application I'm testing has a loading screen when you first load it, then a username/password box appears. It is a dynamically generated UI element and the cursor defaults to being inside the username field.</p>
<p>I looked around and someone suggested using action chains. When I use action chains, I can immediately input text into the username and password fields and then press enter and the next page loads fine. Unfortunately, action chains are not a viable long-term answer for me due to my particular setup.</p>
<p>When I use the webdriver's <code>find_element_by_id</code> I am able to locate it and I am not able to <code>send_keys</code> to the element though because it is somehow not visible. I receive </p>
<blockquote>
<p>selenium.common.exceptions.ElementNotVisibleException: Message: element not visible. </p>
</blockquote>
<p>I'm also not able to click the field or otherwise interact with it without getting this error.</p>
<p>I have also tried identifying and interacting with the elements via other means, such as "xpaths" and css, to no avail. They are always <code>not visible</code>.</p>
<p>Strangely, it works with dynamic page titles. When the page first loads it is <code>Loading...</code> and when finished it is <code>Login</code>. The driver will return the current title when <code>driver.title</code> is called.</p>
<p>Does anyone have a suggestion?</p>
| 1 | 2016-08-23T00:53:52Z | 39,091,712 | <p>As suggested by saurabh , use
1 self.wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, OR.Sub_categories)))</p>
<p>Else put a sleep and see however it is not advisable to use that, may be the xpath you have changes at the time of page load</p>
| 0 | 2016-08-23T03:09:39Z | [
"python",
"selenium",
"testing"
] |
How can I make a python decorator function to reschedule a function in n seconds using asyncio? | 39,090,875 | <p>This is my current code:</p>
<pre><code>import asyncio
import serial
def repeat(seconds):
def wrap(func):
def decorated(*args):
loop = asyncio.get_event_loop()
loop.call_at(loop.time() + seconds, decorated, *args)
print('scheduled')
func(*args)
return func
return decorated
return wrap
@repeat(10)
def send_command(ser, text):
try:
if text == 'DATA':
print("\nSending Data Request")
ser.write(b'\n022022')
elif text == 'STAY':
print("\nInmediate Stay ARM")
ser.write(b'\n0640010002044D')
elif text == 'AWAY':
print("\nInmediate Away ARM")
ser.write(b'\n0640010003044E')
elif text == 'DISARM':
print("\nDISARM")
ser.write(b'\n0940010001040700055B')
elif text == 'CHIME':
print("\nChime toggle")
ser.write(b'\n0640010007014F')
except serial.SerialException as e:
raise e
if __name__ == '__main__':
ser = serial.Serial('/dev/ttyUSB0', 9600, parity=serial.PARITY_ODD, write_timeout=0, timeout=0)
loop = asyncio.get_event_loop()
loop.call_at(loop.time() + 5, send_command, ser, 'DATA')
loop.run_forever()
</code></pre>
<p>In this example I'm trying to schedule the send_command function to run in 5 seconds and every 10 seconds afterwards. It seems to work but I'm a bit confused with the <code>loop.call_at(loop.time() + seconds, decorated, *args)</code> call. Any comments will be appreciated.</p>
| 3 | 2016-08-23T01:12:09Z | 39,098,000 | <p>Your code is fine (except as noted you should return func's result inside decorator), I improved it a bit.</p>
<p>It's easier to see and test with synthetic example:</p>
<pre><code>import asyncio
import functools
def repeat(seconds):
def wrap(func):
@functools.wraps(func) # see http://stackoverflow.com/q/308999/1113207
def decorated(*args, **kwargs):
# We should call func that decorated again to
# force decorator's `call_at` code to execute again:
loop = asyncio.get_event_loop()
loop.call_at(
loop.time() + seconds,
functools.partial(decorated, *args, **kwargs) # see http://stackoverflow.com/q/3252228/1113207
)
# We should return result of func's excecution:
return func(*args, **kwargs)
return decorated
return wrap
@repeat(2)
def send_command():
print('send_command')
async def main():
send_command() # call once, rescheduling started
for i in range(10):
print(i)
await asyncio.sleep(1)
if __name__ == "__main__":
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
</code></pre>
<p>Output:</p>
<pre><code>send_command
0
1
send_command
2
3
send_command
4
5
send_command
6
7
send_command
8
9
send_command
[Finished in 10.3s]
</code></pre>
| 1 | 2016-08-23T09:57:48Z | [
"python",
"decorator",
"python-asyncio"
] |
Flask config import fails on Heroku | 39,090,989 | <p>My application works fine when run locally (with <code>flask run</code>), and it also works on Heroku when the <code>app.config.from_object(config.DevelopmentConfig)</code> is commented out. However, gunicorn can't find the config file when deployed on Heroku. (I can't try gunicorn locally on my Windows machine.)</p>
<h2>__init__.py</h2>
<pre><code>from flask import Flask
app = Flask(__name__)
app.config.from_object('config.DevelopmentConfig')
from app import views
</code></pre>
<h2>Procfile</h2>
<pre><code>web: gunicorn app:app
</code></pre>
<h2>Directory structure</h2>
<p>My <code>config.py</code> is the project root, although I did add a copy in the <code>app</code> directory to no avail.</p>
<pre><code>/ProjectRoot
config.py
/app
__init.py__
views.py
/static
/templates
</code></pre>
<h2>Heroku log</h2>
<p>The error log with time stamps removed:</p>
<pre><code>: [2016-08-23 01:18:51 +0000] [9] [INFO] Worker exiting (pid: 9)
:
: Original exception:
:
: Process exited with status 3
: self.wsgi = self.app.wsgi()
: File "/app/.heroku/python/lib/python2.7/site-packages/gunicorn/app/base.py", line 67, in wsgi
: self.callable = self.load()
: self.load_wsgi()
: File "/app/.heroku/python/lib/python2.7/site-packages/gunicorn/workers/base.py", line 136, in load_wsgi
: worker.init_process()
: [2016-08-23 01:18:51 +0000] [10] [ERROR] Exception in worker process
: Traceback (most recent call last):
: File "/app/.heroku/python/lib/python2.7/site-packages/gunicorn/arbiter.py", line 557, in spawn_worker
: File "/app/.heroku/python/lib/python2.7/site-packages/gunicorn/workers/base.py", line 126, in init_process
: ImportStringError: import_string() failed for 'config.DevelopmentConfig'. Possible reasons are:
:
: File "/app/.heroku/python/lib/python2.7/site-packages/werkzeug/utils.py", line 443, in import_string
: obj = import_string(obj)
: State changed from starting to up
: app.config.from_object('config.DevelopmentConfig')
: File "/app/.heroku/python/lib/python2.7/site-packages/gunicorn/app/wsgiapp.py", line 65, in load
: return self.load_wsgiapp()
: File "/app/.heroku/python/lib/python2.7/site-packages/gunicorn/app/wsgiapp.py", line 52, in load_wsgiapp
: return util.import_app(self.app_uri)
: File "/app/.heroku/python/lib/python2.7/site-packages/gunicorn/util.py", line 357, in import_app
: __import__(module)
: File "/app/app/__init__.py", line 10, in <module>
: File "/app/.heroku/python/lib/python2.7/site-packages/flask/config.py", line 163, in from_object
: File "/app/.heroku/python/lib/python2.7/site-packages/werkzeug/utils.py", line 436, in import_string
: raise ImportError(e)
: - missing __init__.py in a package;
: - package or module path not included in sys.path;
: - duplicated package or module name taking precedence in sys.path;
: - missing module, class, function or variable;
:
: Debugged import:
:
:
: ImportError: 'module' object has no attribute 'DevelopmentConfig'
: Original exception:
: - 'config' found in '/app/config.pyc'.
:
: [2016-08-23 01:18:51 +0000] [10] [INFO] Worker exiting (pid: 10)
: [2016-08-23 01:18:51 +0000] [3] [INFO] Shutting down: Master
: [2016-08-23 01:18:51 +0000] [3] [INFO] Reason: Worker failed to boot.
: sys.exc_info()[2])
: - 'config.DevelopmentConfig' not found.
: State changed from up to crashed
</code></pre>
<p><strong>Update</strong> I changed <code>config</code> too <code>foo</code> and, much to my surprise, it seemed to work. So maybe there <em>is</em> a duplicate in the path. I will experiment with it some more before writing up an answer.</p>
| -1 | 2016-08-23T01:27:44Z | 39,108,483 | <p>I changed the config file's name from to <code>config_app.py</code> and leave the file in the project's root and it runs fine, both locally and on heroku. (Don't forget to modify <code>app.config.from_object()</code> accordingly.)</p>
<p>I'm not sure, but it seems that the error suggestion "duplicated package or module name taking precedence in sys.path;" was applicable.</p>
| 0 | 2016-08-23T18:38:48Z | [
"python",
"heroku",
"flask"
] |
Matplotlib graph expand the x axis | 39,091,030 | <p>I have the following <a href="http://i.stack.imgur.com/cFAL2.png" rel="nofollow"><img src="http://i.stack.imgur.com/cFAL2.png" alt="graph"></a>.</p>
<pre><code>import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
x_values = [2**6,2**7,2**8,2**9,2**10,2**12]
y_values_ST = [7.3,15,29,58,117,468]
y_values_S3 = [2.3,4.6,9.1,19,39,156]
xticks=['2^6','2^7','2^8','2^9','2^10','2^12']
plt.plot(x_values, y_values_ST,'-gv')
plt.plot(x_values, y_values_S3,'-r+')
plt.legend(['ST','S^3'], loc='upper left')
plt.xticks(x_values,xticks)
fig.suptitle('Encrypted Query Size Overhead')
plt.xlabel('Query size')
plt.ylabel('Size in KB')
plt.grid()
fig.savefig('token_size_plot.pdf')
plt.show()
</code></pre>
<p>1)How i can delete the last gap as shown after 2^12?
2)How i can spread more the values in the x axis such that the first two values are not overlapped?</p>
| 0 | 2016-08-23T01:34:40Z | 39,091,155 | <blockquote>
<p>1)How i can delete the last gap as shown after 2^12? </p>
</blockquote>
<p>Set the limits explicitly, e.g.:</p>
<pre><code>plt.xlim(2**5.8, 2**12.2)
</code></pre>
<blockquote>
<p>2)How i can spread more the values in the x axis such that the first two values are not overlapped?</p>
</blockquote>
<p>You seem to want a log plot. Use <code>pyplot.semilog()</code>, or set the log scale on the x-axis (base 2 seems appropriate in your case):</p>
<pre><code>plt.xscale('log', basex=2)
</code></pre>
<p>Note that in this case you don't even have to set the <code>2^*</code> ticks manually, they will be created this way automatically.</p>
<p><a href="http://i.stack.imgur.com/H1WXy.png" rel="nofollow"><img src="http://i.stack.imgur.com/H1WXy.png" alt="enter image description here"></a></p>
| 1 | 2016-08-23T01:52:26Z | [
"python",
"matplotlib"
] |
Matplotlib graph expand the x axis | 39,091,030 | <p>I have the following <a href="http://i.stack.imgur.com/cFAL2.png" rel="nofollow"><img src="http://i.stack.imgur.com/cFAL2.png" alt="graph"></a>.</p>
<pre><code>import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
x_values = [2**6,2**7,2**8,2**9,2**10,2**12]
y_values_ST = [7.3,15,29,58,117,468]
y_values_S3 = [2.3,4.6,9.1,19,39,156]
xticks=['2^6','2^7','2^8','2^9','2^10','2^12']
plt.plot(x_values, y_values_ST,'-gv')
plt.plot(x_values, y_values_S3,'-r+')
plt.legend(['ST','S^3'], loc='upper left')
plt.xticks(x_values,xticks)
fig.suptitle('Encrypted Query Size Overhead')
plt.xlabel('Query size')
plt.ylabel('Size in KB')
plt.grid()
fig.savefig('token_size_plot.pdf')
plt.show()
</code></pre>
<p>1)How i can delete the last gap as shown after 2^12?
2)How i can spread more the values in the x axis such that the first two values are not overlapped?</p>
| 0 | 2016-08-23T01:34:40Z | 39,091,184 | <p>1.Using <code>autoscale</code>, specify the axes, or alternately you can use <code>plt.axis('tight')</code> for both the axes. 2.Using log scaled x-axis. Code below:</p>
<pre><code>import matplotlib.pyplot as plt
fig = plt.figure()
x_values = [2**6,2**7,2**8,2**9,2**10,2**12]
y_values_ST = [7.3,15,29,58,117,468]
y_values_S3 = [2.3,4.6,9.1,19,39,156]
xticks=['2^6','2^7','2^8','2^9','2^10','2^12']
ax = plt.gca()
ax.set_xscale('log')
plt.plot(x_values, y_values_ST,'-gv')
plt.plot(x_values, y_values_S3,'-r+')
plt.legend(['ST','S^3'], loc='upper left')
plt.xticks(x_values,xticks)
fig.suptitle('Encrypted Query Size Overhead')
plt.xlabel('Query size')
plt.ylabel('Size in KB')
plt.autoscale(enable=True, axis='x', tight=True)#plt.axis('tight')
plt.grid()
fig.savefig('token_size_plot.pdf')
plt.show()
</code></pre>
| 0 | 2016-08-23T01:57:32Z | [
"python",
"matplotlib"
] |
Lazy evaluation of variables | 39,091,071 | <p>I want to lexicographically compare two lists, but the values inside the list should be computed when needed. For instance, for these two lists</p>
<pre><code>a = list([1, 3, 3])
b = list([1, 2, 2])
(a < b) == False
(b < a) == True
</code></pre>
<p>I'd like the values in the list to be functions and in the case of <code>a</code> and <code>b</code>, the values (i.e. the function) at index=2 would not be evaluated as the values at index=1 (<code>a[1]==3, b[1]==2</code>) are already sufficient to determine that <code>b < a</code>.</p>
<p>One option would be to manually compare the elements, and that's probably what I will do when I don't find a solution that allows me to use the list's comparator, but I found that the manual loop is a tad slower than the list's builtin comparator which is why I want to make use of it.</p>
<p><strong>Update</strong></p>
<p>Here's a way to accomplish what I am trying to do, but I was wondering if there are any built-in functions that would do this faster (and which makes use of this feature of lists).</p>
<pre><code>def lex_comp(a, b):
for func_a, func_b in izip(a, b):
v_a = func_a()
v_b = func_b()
if v_a < v_b: return -1
if v_b > v_a: return +1
return 0
def foo1(): return 1
def foo2(): return 1
def bar1(): return 1
def bar2(): return 2
def func1(): return ...
def func2(): return ...
list_a = [foo1, bar1, func1, ...]
list_b = [foo2, bar2, func2, ...]
# now you can use the comparator for instance to sort a list of these lists
sort([list_a, list_b], cmp=lex_comp)
</code></pre>
| 2 | 2016-08-23T01:41:04Z | 39,091,388 | <p>Here is an approach that uses lazy evaluation:</p>
<pre><code>>>> def f(x):
... return 2**x
...
>>> def g(x):
... return x*2
...
>>> [f(x) for x in range(1,10)]
[2, 4, 8, 16, 32, 64, 128, 256, 512]
>>> [g(x) for x in range(1,10)]
[2, 4, 6, 8, 10, 12, 14, 16, 18]
>>> zipped = zip((f(i) for i in range(1,10)),(g(i) for i in range(1,10)))
>>> x,y = next(itertools.dropwhile(lambda t: t[0]==t[1],zipped))
>>> x > y
True
>>> x < y
False
>>> x
8
>>> y
6
>>>
</code></pre>
| 1 | 2016-08-23T02:25:41Z | [
"python",
"comparison",
"lexicographic"
] |
Lazy evaluation of variables | 39,091,071 | <p>I want to lexicographically compare two lists, but the values inside the list should be computed when needed. For instance, for these two lists</p>
<pre><code>a = list([1, 3, 3])
b = list([1, 2, 2])
(a < b) == False
(b < a) == True
</code></pre>
<p>I'd like the values in the list to be functions and in the case of <code>a</code> and <code>b</code>, the values (i.e. the function) at index=2 would not be evaluated as the values at index=1 (<code>a[1]==3, b[1]==2</code>) are already sufficient to determine that <code>b < a</code>.</p>
<p>One option would be to manually compare the elements, and that's probably what I will do when I don't find a solution that allows me to use the list's comparator, but I found that the manual loop is a tad slower than the list's builtin comparator which is why I want to make use of it.</p>
<p><strong>Update</strong></p>
<p>Here's a way to accomplish what I am trying to do, but I was wondering if there are any built-in functions that would do this faster (and which makes use of this feature of lists).</p>
<pre><code>def lex_comp(a, b):
for func_a, func_b in izip(a, b):
v_a = func_a()
v_b = func_b()
if v_a < v_b: return -1
if v_b > v_a: return +1
return 0
def foo1(): return 1
def foo2(): return 1
def bar1(): return 1
def bar2(): return 2
def func1(): return ...
def func2(): return ...
list_a = [foo1, bar1, func1, ...]
list_b = [foo2, bar2, func2, ...]
# now you can use the comparator for instance to sort a list of these lists
sort([list_a, list_b], cmp=lex_comp)
</code></pre>
| 2 | 2016-08-23T01:41:04Z | 39,091,422 | <p>Try this (the extra parameters to the function are just for illustration purposes):</p>
<pre><code>import itertools
def f(a, x):
print "lazy eval of {}".format(a)
return x
a = [lambda: f('a', 1), lambda: f('b', 3), lambda: f('c', 3)]
b = [lambda: f('d', 1), lambda: f('e', 2), lambda: f('f', 2)]
c = [lambda: f('g', 1), lambda: f('h', 2), lambda: f('i', 2)]
def lazyCmpList(a, b):
l = len(list(itertools.takewhile(lambda (x, y): x() == y(), itertools.izip(a, b))))
if l == len(a):
return 0
else:
return cmp(a[l](), b[l]())
print lazyCmpList(a, b)
print lazyCmpList(b, a)
print lazyCmpList(b, c)
</code></pre>
<p>Produces:</p>
<pre><code>lazy eval of a
lazy eval of d
lazy eval of b
lazy eval of e
-1
lazy eval of d
lazy eval of a
lazy eval of e
lazy eval of b
1
lazy eval of d
lazy eval of g
lazy eval of e
lazy eval of h
lazy eval of f
lazy eval of i
0
</code></pre>
<p>Note that the code assumes the list of functions are of the same length. It could be enhanced to support non-equal list length, you'd have to define what the logic was i.e. what should <code>cmp([f1, f2, f3], [f1, f2, f3, f1])</code> produce?</p>
<p>I haven't compared the speed but given your updated code I would imagine any speedup will be marginal (looping done in C code rather than Python). This solution may actually be slower as it is more complex and involved more memory allocation.</p>
<p>Given you are trying to sort a list of functions by evaluating them it follows that the functions will be evaluated i.e. O(nlogn) times and so your best speedup may be to look at using <a href="http://stackoverflow.com/questions/1988804/what-is-memoization-and-how-can-i-use-it-in-python">memoization</a> to avoid repeated revaluation of the functions.</p>
| 2 | 2016-08-23T02:31:11Z | [
"python",
"comparison",
"lexicographic"
] |
Lazy evaluation of variables | 39,091,071 | <p>I want to lexicographically compare two lists, but the values inside the list should be computed when needed. For instance, for these two lists</p>
<pre><code>a = list([1, 3, 3])
b = list([1, 2, 2])
(a < b) == False
(b < a) == True
</code></pre>
<p>I'd like the values in the list to be functions and in the case of <code>a</code> and <code>b</code>, the values (i.e. the function) at index=2 would not be evaluated as the values at index=1 (<code>a[1]==3, b[1]==2</code>) are already sufficient to determine that <code>b < a</code>.</p>
<p>One option would be to manually compare the elements, and that's probably what I will do when I don't find a solution that allows me to use the list's comparator, but I found that the manual loop is a tad slower than the list's builtin comparator which is why I want to make use of it.</p>
<p><strong>Update</strong></p>
<p>Here's a way to accomplish what I am trying to do, but I was wondering if there are any built-in functions that would do this faster (and which makes use of this feature of lists).</p>
<pre><code>def lex_comp(a, b):
for func_a, func_b in izip(a, b):
v_a = func_a()
v_b = func_b()
if v_a < v_b: return -1
if v_b > v_a: return +1
return 0
def foo1(): return 1
def foo2(): return 1
def bar1(): return 1
def bar2(): return 2
def func1(): return ...
def func2(): return ...
list_a = [foo1, bar1, func1, ...]
list_b = [foo2, bar2, func2, ...]
# now you can use the comparator for instance to sort a list of these lists
sort([list_a, list_b], cmp=lex_comp)
</code></pre>
| 2 | 2016-08-23T01:41:04Z | 39,135,032 | <p>I did some testing and found that @juanpa's answer and the version in my update are the fastest versions:</p>
<pre><code>import random
import itertools
import functools
num_rows = 100
data = [[random.randint(0, 2) for i in xrange(10)] for j in xrange(num_rows)]
# turn data values into functions.
def return_func(value):
return value
list_funcs = [[functools.partial(return_func, v) for v in row] for row in data]
def lazy_cmp_FujiApple(a, b):
l = len(list(itertools.takewhile(lambda (x, y): x() == y(), itertools.izip(a, b))))
if l == len(a):
return 0
else:
return cmp(a[l](), b[l]())
sorted1 = sorted(list_funcs, lazy_cmp_FujiApple)
%timeit sorted(list_funcs, lazy_cmp_FujiApple)
# 100 loops, best of 3: 2.77 ms per loop
def lex_comp_mine(a, b):
for func_a, func_b in itertools.izip(a, b):
v_a = func_a()
v_b = func_b()
if v_a < v_b: return -1
if v_a > v_b: return +1
return 0
sorted2 = sorted(list_funcs, cmp=lex_comp_mine)
%timeit sorted(list_funcs, cmp=lex_comp_mine)
# 1000 loops, best of 3: 930 µs per loop
def lazy_comp_juanpa(a, b):
x, y = next(itertools.dropwhile(lambda t: t[0]==t[1], itertools.izip(a, b)))
return cmp(x, y)
sorted3 = sorted(list_funcs, cmp=lazy_comp_juanpa)
%timeit sorted(list_funcs, cmp=lex_comp_mine)
# 1000 loops, best of 3: 949 µs per loop
%timeit sorted(data)
# 10000 loops, best of 3: 45.4 µs per loop
# print sorted(data)
# print [[c() for c in row] for row in sorted1]
# print [[c() for c in row] for row in sorted2]
# print sorted3
</code></pre>
<p>I guess the creation of an intermediate list is hurting performance of @FujiApple's version. When running my comparator version on the original <code>data</code> list and comparing the runtime to Python's native list sorting, I note that my version is about 10times slower (501 µs vs 45.4 µs per loop). I guess theres' no easy way to get close to the performance of Python's native implementation...</p>
| 1 | 2016-08-25T00:44:21Z | [
"python",
"comparison",
"lexicographic"
] |
How to read data, apply a function and return the result with Django REST Framework? | 39,091,108 | <p>Consider a simple task to calculate "y = ax + b", where "a" and "b" are given by the model and "x" is given by the user through an API request, like http://someurl.com/api/15, where x=15.</p>
<p>Usually, the API would return "a" and "b" in a JSON format. But, instead, I want to solve this equation on the server and only return "y". However, I can't figure it out how to get "x" from the URL and where to place the last function to return "y" to the JSON. Any thoughts?</p>
<p>models.py:</p>
<pre><code>from django.db import models
class SimpleEquation(models.Model):
a = models.IntegerField()
b = models.IntegerField()
</code></pre>
<p>serializers.py:</p>
<pre><code>from rest_framework import serializers
from .models import SimpleEquation
class SimpleEquationSerializer(serializers.ModelSerializer):
class Meta:
model = SimpleEquation
fields = ('a','b') # Should return 'y' instead
</code></pre>
<p>views.py:</p>
<pre><code>from rest_framework import generics
from .serializers import SimpleEquationSerializer
class Results(generics.ListAPIView):
queryset = SimpleEquation.objects.all()[0]
serializer_class = SimpleEquationSerializer
</code></pre>
<p>My dumb function so far:</p>
<pre><code>def the_function(request):
x = SOME_REQUEST_GET_METHOD
pars = SimpleEquation.objects.all()[0]
a = pars.a
b = pars.b
y = a*x + b
return y
</code></pre>
| 0 | 2016-08-23T01:46:28Z | 39,091,286 | <p>The <a href="https://docs.djangoproject.com/en/1.9/topics/http/urls/" rel="nofollow">URL dispatcher</a> would capture the value and pass it to the view. Something like this may work:</p>
<p><code>URLconf</code></p>
<pre><code>from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^regression/[+-]?\d+.\d+?/$', views.regression),
]
</code></pre>
<p><code>views.py</code></p>
<pre><code>def regression(request, x)
x = float(x)
pars = SimpleEquation.objects.all()[0]
a = pars.a
b = pars.b
y = a*x + b
return y
</code></pre>
| 0 | 2016-08-23T02:11:30Z | [
"python",
"json",
"django",
"django-rest-framework"
] |
How to read data, apply a function and return the result with Django REST Framework? | 39,091,108 | <p>Consider a simple task to calculate "y = ax + b", where "a" and "b" are given by the model and "x" is given by the user through an API request, like http://someurl.com/api/15, where x=15.</p>
<p>Usually, the API would return "a" and "b" in a JSON format. But, instead, I want to solve this equation on the server and only return "y". However, I can't figure it out how to get "x" from the URL and where to place the last function to return "y" to the JSON. Any thoughts?</p>
<p>models.py:</p>
<pre><code>from django.db import models
class SimpleEquation(models.Model):
a = models.IntegerField()
b = models.IntegerField()
</code></pre>
<p>serializers.py:</p>
<pre><code>from rest_framework import serializers
from .models import SimpleEquation
class SimpleEquationSerializer(serializers.ModelSerializer):
class Meta:
model = SimpleEquation
fields = ('a','b') # Should return 'y' instead
</code></pre>
<p>views.py:</p>
<pre><code>from rest_framework import generics
from .serializers import SimpleEquationSerializer
class Results(generics.ListAPIView):
queryset = SimpleEquation.objects.all()[0]
serializer_class = SimpleEquationSerializer
</code></pre>
<p>My dumb function so far:</p>
<pre><code>def the_function(request):
x = SOME_REQUEST_GET_METHOD
pars = SimpleEquation.objects.all()[0]
a = pars.a
b = pars.b
y = a*x + b
return y
</code></pre>
| 0 | 2016-08-23T01:46:28Z | 39,091,287 | <p>Use <a href="http://www.django-rest-framework.org/api-guide/fields/#serializermethodfield" rel="nofollow">Serializer Method Field</a></p>
<pre><code>from rest_framework import serializers
from .models import SimpleEquation
class SimpleEquationSerializer(serializers.ModelSerializer):
y = serializers.SerializerMethodField('get_y')
class Meta:
model = SimpleEquation
fields = ('y')
def get_y(self, obj):
x = self.context['request'].x
y = obj.a*x + obj.b # obj comes from the queryset from view
return y
</code></pre>
| 1 | 2016-08-23T02:11:32Z | [
"python",
"json",
"django",
"django-rest-framework"
] |
How to check if Django object is None in javascript? | 39,091,167 | <p>How do you check if a Django object is None in js?</p>
<p>I currently have a variable <code>person</code> that stores a Django object or None. In my js I have:</p>
<pre><code>if ({{person}} != None) {
execute_function({{person}})
}
</code></pre>
<p>What seems to be the issue here?</p>
| 1 | 2016-08-23T01:54:24Z | 39,094,118 | <p>This worked for me:</p>
<pre><code>{% if person != None %}
var p = ...
...
{% endif %}
</code></pre>
| 0 | 2016-08-23T06:46:10Z | [
"javascript",
"python",
"django"
] |
How to check if Django object is None in javascript? | 39,091,167 | <p>How do you check if a Django object is None in js?</p>
<p>I currently have a variable <code>person</code> that stores a Django object or None. In my js I have:</p>
<pre><code>if ({{person}} != None) {
execute_function({{person}})
}
</code></pre>
<p>What seems to be the issue here?</p>
| 1 | 2016-08-23T01:54:24Z | 39,110,589 | <p>John Smiths answer makes the most sense, check it in Django's templates.
Actually better would be: </p>
<pre><code>{% if person %}
execute function
{% endif%}
</code></pre>
<p>If you need to check it using JavaScript, JavaScript uses null instead of None, so assuming that the JavaScript code is also in the Django html template (and not loaded as an external file) this should work. </p>
<pre><code>if ({{person}} != null) {
execute_function({{person}})
}
</code></pre>
<p>edit :</p>
<p>adding a bit more detail:
That will probably be parsed to something like:</p>
<pre><code>if (john != null){
execute_function(john)
}
</code></pre>
<p>JavaScipt won't understand john , but it will understand the quoted version 'john' :</p>
<pre><code>if ('john') != null){
execute_function('john')
}
</code></pre>
<p>The easiest way to achieve this would be to add a model method to the Person model.</p>
<pre><code>Class Person(models.Model):
...field definitions here.
def quoted_name(self):
return "'%s'" % self.name
</code></pre>
<p>Then in the template (and empty string evaluates to false):</p>
<pre><code>if ({{person.quoted_name }}) {
execute_function({{person.quoted_name }})
}
</code></pre>
| 3 | 2016-08-23T20:59:52Z | [
"javascript",
"python",
"django"
] |
How to import python module from docker | 39,091,186 | <p>I made a docker image contains nginx, uwsgi and some python module, using volumes out the docker to develop code.</p>
<p>So how should I use python environment from docker when coding?</p>
| -1 | 2016-08-23T01:57:56Z | 39,093,316 | <p>I'm not sure what you are trying to do. But here are some tips, that may help you.</p>
<ol>
<li>Python libraries for working with docker from python
<ul>
<li><a href="https://github.com/docker/docker-py" rel="nofollow">https://github.com/docker/docker-py</a> </li>
<li><a href="https://github.com/deepgram/sidomo" rel="nofollow">https://github.com/deepgram/sidomo</a></li>
</ul></li>
<li>You can start container's python console
<code>docker run -ti myimage python</code></li>
<li>Also you can have connected <code>volumes</code> where you will store your source code and than run this code with container's environment</li>
</ol>
<p><strong>NEW IDEA</strong></p>
<p>Importing module in python means having module's folder in your <code>PYTHONPATH</code>. So basically you probably would need to mount your docker with something like <a href="https://github.com/libfuse/sshfs" rel="nofollow"><code>sshfs</code></a> to some folder, and than add this folder to your <code>PYTHONPATH</code>. After that you can do <code>from {docker_module} ...</code></p>
| 1 | 2016-08-23T05:52:55Z | [
"python",
"django",
"docker"
] |
Wrong output in Implementing Kruskal Algorithm in Python | 39,091,191 | <p>I am working on Krusal's Algorithm. However I failed to get the right output. I don't know where I made mistaks.</p>
<p>Here is my code:</p>
<pre><code>parent = dict()
rank = dict()
def make_set(vertice):
parent[vertice] = vertice
rank[vertice] = 0
def find(vertice):
if parent[vertice] != vertice:
parent[vertice] = find(parent[vertice])
return parent[vertice]
def union(vertice1, vertice2):
root1 = find(vertice1)
root2 = find(vertice2)
if root1 != root2:
if rank[root1] > rank[root2]:
parent[root2] = root1
else:
parent[root1] = root2
if rank[root1] == rank[root2]: rank[root2] += 1
def kruskal(graph):
for vertice in graph['vertices']:
make_set(vertice)
minimum_spanning_tree = set()
edges = list(graph['edges'])
for edge in edges:
vertice1, vertice2, weight = edge
if find(vertice1) != find(vertice2):
union(vertice1, vertice2)
minimum_spanning_tree.add(edge)
return minimum_spanning_tree
graph = {
'vertices': [0,1, 2, 3, 4, 5],
'edges': set([ //(first node, second node, weight)
(0, 3,5),
(3, 5,2),
( 5, 4,10),
( 4, 1,3),
(1, 0,8),
(0, 2,1),(2,3,6),( 2,5,4),( 2,4,9),(2,1,7),
])
}
a = kruskal(graph)
print(a)
</code></pre>
<p>I found that if I change "Edges" into (weight, first node, second node) format, I can got right answer in format of (weight, first node, second node). But how can I modify it if I wanna use "Edges" in format of (first node, second node, weigth)?</p>
| 0 | 2016-08-23T01:59:05Z | 39,092,248 | <p>at first glance, try this:</p>
<pre><code>edges = list(graph['edges'])
</code></pre>
<p>instead</p>
<pre><code>edges = sorted(graph['edges'], key=lambda e: e[2])
</code></pre>
| 0 | 2016-08-23T04:13:42Z | [
"python",
"graph-theory",
"minimum-spanning-tree",
"kruskals-algorithm"
] |
How does Chrome "Simplify Page"? | 39,091,221 | <p>I'm trying to implement this in Python and don't know where to start. My ultimate goal is to extract the title and body from news article such as:</p>
<p><a href="http://investorplace.com/2016/08/csco-stock-2-trades-cisco-systems-earnings/" rel="nofollow">http://investorplace.com/2016/08/csco-stock-2-trades-cisco-systems-earnings/</a></p>
| -2 | 2016-08-23T02:02:38Z | 39,091,310 | <p>The <a class='doc-link' href="http://stackoverflow.com/documentation/python/1792/web-scraping-with-python#t=20160823021300902437">Web Scraping Documentation</a> should give you some orientation.</p>
<p>Take a look at the <code>webpage source</code> and use <code>inspect element</code> in the items that you want!</p>
<p>Then it's all a matter of creating a <code>soup()</code> and using <code>find()</code> or <code>findAll()</code> to retrieve the correct tags.</p>
| 1 | 2016-08-23T02:14:38Z | [
"python",
"google-chrome",
"web-scraping",
"beautifulsoup",
"scrapy"
] |
Why are some of the values of items' fields repeating in this Scrapy spider? | 39,091,239 | <p>When my spider runs on a url like <a href="http://211sepa.org/get-help/housing/" rel="nofollow">this</a>:</p>
<pre><code>def parse_subandtaxonomy(self, response):
item = response.meta['item']
for sub in response.xpath('//div[@class = "page-content"]/section'):
item['Subcategory'] = sub.xpath('h2/text()').extract()
for tax in sub.xpath('ul/li/a'):
item['Taxonomy'] = tax.xpath('text()').extract()
for href in tax.xpath('@href'):
# url = response.urljoin(href.extract()) - > this gave me 301 redirects
badurl = urljoin('https://211sepa.org/search/', href.extract())
url = badurl.replace('search?', 'search/?area_served=Philadelphia&', 1) # shut off to test multi-page
request = scrapy.Request(url, callback=self.parse_listings)
request.meta['item'] = item
yield item
</code></pre>
<p>I recieve this output, which is what I expect:</p>
<pre><code>{"Category": ["Housing"], "Subcategory": ["Affordable Housing"], "Taxonomy": ["Section 8 Vouchers"]}
{"Category": ["Housing"], "Subcategory": ["Affordable Housing"], "Taxonomy": ["Public Housing"]}
{"Category": ["Housing"], "Subcategory": ["Affordable Housing"], "Taxonomy": ["Low Income/ Subsidized Rental Housing"]}
{"Category": ["Housing"], "Subcategory": ["Shelter"], "Taxonomy": ["Homeless Shelters"]}
{"Category": ["Housing"], "Subcategory": ["Shelter"], "Taxonomy": ["Homeless Shelter Centralized Intake"]}
{"Category": ["Housing"], "Subcategory": ["Shelter"], "Taxonomy": ["Domestic Violence Shelters"]}
{"Category": ["Housing"], "Subcategory": ["Shelter"], "Taxonomy": ["Runaway/ Youth Shelters"]}
{"Category": ["Housing"], "Subcategory": ["Shelter"], "Taxonomy": ["Cold Weather Shelters/ Warming Centers"]}
{"Category": ["Housing"], "Subcategory": ["Shelter"], "Taxonomy": ["Homeless Shelter for Pregnant Women"]}
{"Category": ["Housing"], "Subcategory": ["Stay Housed"], "Taxonomy": ["Rent Payment Assistance"]}
{"Category": ["Housing"], "Subcategory": ["Stay Housed"], "Taxonomy": ["Mortgage Payment Assistance"]}
{"Category": ["Housing"], "Subcategory": ["Stay Housed"], "Taxonomy": ["Landlord/ Tenant Mediation"]}
{"Category": ["Housing"], "Subcategory": ["Stay Housed"], "Taxonomy": ["General Dispute Mediation"]}
{"Category": ["Housing"], "Subcategory": ["Overcome Homelessness"], "Taxonomy": ["Transitional Housing/ Shelter"]}
{"Category": ["Housing"], "Subcategory": ["Overcome Homelessness"], "Taxonomy": ["Rental Deposit Assistance"]}
{"Category": ["Housing"], "Subcategory": ["Overcome Homelessness"], "Taxonomy": ["Permanent Supportive Housing"]}
</code></pre>
<p>but then when I change <code>yield item</code> to <code>yield request</code> to continue on in the crawl, each item has <code>{"Category": ["Housing"], "Subcategory": ["Overcome Homelessness"], "Taxonomy": ["Permanent Supportive Housing"] ... other item info ... }</code> instead of its respective subcategory and taxonomy. Each item that I eventually want from each taxonomy is scraped, but it's incorrectly labeled as described above. Any idea what's going on?</p>
| -1 | 2016-08-23T02:05:05Z | 39,099,493 | <p>It might be an issue with scopes. You should always try to create your item on the highest scope possible to prevent data retention, i.e. if the current <code>item</code> doesn't have <code>Taxonomy</code> field, the object will retain data from the previous loop cycle. That's why the code should have create new object in every loop cycle when possible. </p>
<p>Try this:</p>
<pre><code>def parse_subandtaxonomy(self, response):
for sub in response.xpath('//div[@class = "page-content"]/section'):
subcategory = sub.xpath('h2/text()').extract()
subcategory = sub.xpath('h2/text()').extract_first() # this just takes first element which is nicer!
for tax in sub.xpath('ul/li/a'):
item = response.meta['item'].copy()
item['Subcategory'] = subcategory
item['Taxonomy'] = tax.xpath('text()').extract()
for href in tax.xpath('@href'):
# url = response.urljoin(href.extract()) - > this gave me 301 redirects
badurl = urljoin('https://211sepa.org/search/', href.extract())
url = badurl.replace('search?', 'search/?area_served=Philadelphia&', 1) # shut off to test multi-page
request = scrapy.Request(url,
callback=self.parse_listings,
meta={'item': item}) # you can put meta here directly
yield request
</code></pre>
| 0 | 2016-08-23T11:07:23Z | [
"python",
"python-3.x",
"scrapy",
"scrapy-spider"
] |
python parse XML with multiple elements and insert into sqlite | 39,091,279 | <p>I'm very new to python so please excuse me.. I have parsed an XML file and am inserting into sqlite just fine however I now need to get text value from multiple elements with the same name(channel-category) and insert into one sql column like</p>
<pre><code>somecategory1, somecategory2
</code></pre>
<p>here is what I'm doing right now</p>
<pre><code>elif elem.tag == "channel":
cid = elem.get("id").replace("'", "")
title = elem.findtext("display-name")
chncategory = elem.findtext("channel-category")
..somecode..
..somecode..
result = Channel(cid, title, chncategory, logo, streamUrl, visible)
</code></pre>
<p>I then call this</p>
<pre><code>c.execute('INSERT OR IGNORE INTO channels(id, title, chncategory, logo, stream_url, visible, weight, source) VALUES(?, ?, ?, ?, ?, ?, (CASE ? WHEN -1 THEN (SELECT COALESCE(MAX(weight)+1, 0) FROM channels WHERE source=?) ELSE ? END), ?)',
[channel.id, channel.title, channel.chncategory, channel.logo, channel.streamUrl, channel.visible, channel.weight,
self.source.KEY, channel.weight, self.source.KEY])
</code></pre>
<p>which works fine.. however it only grabs the FIRST channel-category element and I need to grab them all and add into that column so it displays like</p>
<pre><code>somecategory1, somecategory2, etc
</code></pre>
<p>my xml looks like this</p>
<pre><code><tv info="blahblah">
<channel id="channel1">
<display-name lang="en">channel1</display-name>
<icon src="somewhere.png" />
<url>http://someurl.com</url>
<channel-category>somecategory1</channel-category>
<channel-category>somecategory2</channel-category>
</channel>
</tv>
</code></pre>
<p>How would I make this work so instead of just grabbing the first value and putting it into the column, have it grab them ALL and insert to that one column?</p>
| 0 | 2016-08-23T02:09:52Z | 39,091,355 | <p>How about, instead of </p>
<pre><code>chncategory = elem.findtext("channel-category")
</code></pre>
<p>You use:</p>
<pre><code>In [5]: chncategory = ', '.join(map(lambda x: x.text, elem.findall("channel-category")))
In [6]: chncategory
Out[6]: 'somecategory1, somecategory2'
</code></pre>
| 0 | 2016-08-23T02:20:48Z | [
"python",
"xml",
"database",
"list",
"sqlite"
] |
Finding row that has number instersecting two columns | 39,091,301 | <p>Data has three columns. I need to find the row that has the number intersecting between second and third columns. For example, which row has number 15 between second and third column in the data below?</p>
<pre><code>a 1 5
b 7 10
c 13 17
d 20 24
</code></pre>
<p>The ideal result should be </p>
<pre><code>c 13 17
</code></pre>
<p>as it has '15' intersecting that row between second and third column. Is there a way to do it using Python (specifically Python 2.7)?</p>
| 0 | 2016-08-23T02:14:03Z | 39,091,372 | <p>You mean this?</p>
<pre><code>import pandas as pd
df = pd.DataFrame([('a', 1, 5), ('b', 7, 10), ('c', 13, 17), ('d', 20, 24)],
columns=['col1', 'col2', 'col3'])
df[(df.col2 < 15) & (df.col3 > 15)]
</code></pre>
<p>yields...</p>
<pre><code> col1 col2 col3
2 c 13 17
</code></pre>
| 1 | 2016-08-23T02:23:42Z | [
"python",
"python-2.7",
"csv",
"pandas",
"intersection"
] |
Finding row that has number instersecting two columns | 39,091,301 | <p>Data has three columns. I need to find the row that has the number intersecting between second and third columns. For example, which row has number 15 between second and third column in the data below?</p>
<pre><code>a 1 5
b 7 10
c 13 17
d 20 24
</code></pre>
<p>The ideal result should be </p>
<pre><code>c 13 17
</code></pre>
<p>as it has '15' intersecting that row between second and third column. Is there a way to do it using Python (specifically Python 2.7)?</p>
| 0 | 2016-08-23T02:14:03Z | 39,091,437 | <p>Another approach, using <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.query.html" rel="nofollow">query</a>:</p>
<pre><code>In [7]: df
Out[7]:
tag start end
0 a 1 5
1 b 7 10
2 c 13 17
3 d 20 24
In [8]: df.query('start < 15 < end')
Out[8]:
tag start end
2 c 13 17
</code></pre>
| 0 | 2016-08-23T02:33:35Z | [
"python",
"python-2.7",
"csv",
"pandas",
"intersection"
] |
Why does doing Django query cause: django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet? | 39,091,416 | <p>I'm working on a Django 1.8.2 project.</p>
<p>This project has multiple Django applications.</p>
<p>Application <code>app_a</code> has class <code>MyClassA</code> as follows:</p>
<pre><code>class MyClassA(models.Model):
name = models.CharField(max_length=50, null=True, blank=True)
@staticmethod
def my_static_method():
ret_val = MyClassA.objects.filter()
return "World"
</code></pre>
<p>Application <code>app_b</code> has class <code>MyClassB</code> as follows:</p>
<pre><code>class MyClassB(models.Model):
name = models.CharField(max_length=50, null=False, blank=False)
def my_method(self, arg1=MyClassA.my_static_method()):
return "Hello"
</code></pre>
<p>When I run <code>manage.py test</code>, it works fine.</p>
<p>However, then I change <code>MyClassA.my_static_method()</code> to the following:</p>
<pre><code>@staticmethod
def my_static_method():
ret_val = MyClassA.objects.filter(name=None)
return "World"
</code></pre>
<p>When I do that, and then run <code>manage.py test</code>, it fails with the following error:</p>
<pre><code> File "my-virtual-env/lib/python2.7/site-packages/django/apps/registry.py", line 131, in check_models_ready
raise AppRegistryNotReady("Models aren't loaded yet.")
django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet.
</code></pre>
<p>Why is this happening? How do I fix this?</p>
<p>The only change that I made is adding the filter value <code>name=None</code>.</p>
| 1 | 2016-08-23T02:30:26Z | 39,093,981 | <p>In this case you will get an error only if you make a mistake in the manager function. I tried the same and it worked for me. but I got the same error when I made an error in the filter() .like MyClassA.objects.filter(a_field_not_in_the_model=None).</p>
<p>I think you have to re check your original code. check if your model is ok.</p>
| 0 | 2016-08-23T06:37:41Z | [
"python",
"django"
] |
Why does doing Django query cause: django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet? | 39,091,416 | <p>I'm working on a Django 1.8.2 project.</p>
<p>This project has multiple Django applications.</p>
<p>Application <code>app_a</code> has class <code>MyClassA</code> as follows:</p>
<pre><code>class MyClassA(models.Model):
name = models.CharField(max_length=50, null=True, blank=True)
@staticmethod
def my_static_method():
ret_val = MyClassA.objects.filter()
return "World"
</code></pre>
<p>Application <code>app_b</code> has class <code>MyClassB</code> as follows:</p>
<pre><code>class MyClassB(models.Model):
name = models.CharField(max_length=50, null=False, blank=False)
def my_method(self, arg1=MyClassA.my_static_method()):
return "Hello"
</code></pre>
<p>When I run <code>manage.py test</code>, it works fine.</p>
<p>However, then I change <code>MyClassA.my_static_method()</code> to the following:</p>
<pre><code>@staticmethod
def my_static_method():
ret_val = MyClassA.objects.filter(name=None)
return "World"
</code></pre>
<p>When I do that, and then run <code>manage.py test</code>, it fails with the following error:</p>
<pre><code> File "my-virtual-env/lib/python2.7/site-packages/django/apps/registry.py", line 131, in check_models_ready
raise AppRegistryNotReady("Models aren't loaded yet.")
django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet.
</code></pre>
<p>Why is this happening? How do I fix this?</p>
<p>The only change that I made is adding the filter value <code>name=None</code>.</p>
| 1 | 2016-08-23T02:30:26Z | 39,094,241 | <p>In Django you must not run queries at import time. (See <a href="https://docs.djangoproject.com/en/dev/ref/applications/#how-applications-are-loaded" rel="nofollow">here</a> for details.)</p>
<p>Because default argument values in Python are evaluated when the function is defined (as opposed to when it is called), your <code>MyClassB.my_method()</code> definition is calling <code>MyClassA.my_static_method()</code>, which attempts to run a query.</p>
<p>Why did you see an error in one version of your code and not the other? One of them is evaluating the query (i.e. trying to access the database) and one isn't, for whatever reason. It's your responsibility to make sure that nothing you do at import time tries to access the database.</p>
<p>If your goal is for that default argument to be evaluated on each call, the standard idiom in Python is:</p>
<pre><code>def my_method(self, arg1=None):
if arg1 is None:
arg1 = MyClassA.my_static_method()
</code></pre>
| 1 | 2016-08-23T06:54:16Z | [
"python",
"django"
] |
Python2 - How to remove characters from output? | 39,091,442 | <p>I made this script that outputs the balance of a group of addresses. The output however comes in a list of one. How do I get python to extract the value from the list, so it doesn't show the ['']?</p>
<pre><code>from lxml import html
import requests
page = requests.get('https://blockchain.info/xpub/xpub6BfKpqjTwvH21wJGWEfxLppb8sU7C6FJge2kWb9315oP4ZVqCXG29cdUtkyu7YQhHyfA5nt63nzcNZHYmqXYHDxYo8mm1Xq1dAC7YtodwUR')
tree = html.fromstring(page.content)
balance = tree.xpath('//*[@id="final_balance"]/font/span/text()')
print str(balance)
</code></pre>
<p>Regards.</p>
| 0 | 2016-08-23T02:34:00Z | 39,091,459 | <p>Try this:</p>
<pre><code>balance = tree.xpath('//*[@id="final_balance"]/font/span/text()')[0]
print balance
</code></pre>
<p>When you have a list <code>foo</code>, <code>foo[0]</code> gets the first element of <code>foo</code>. Since your list has only one element, that's the <em>only</em> element of <code>foo</code>. Then you can just print it out. (Similarly, you could use <code>foo[1]</code> to get the second element, <code>foo[2]</code> to get the third, etc.)</p>
| 1 | 2016-08-23T02:36:14Z | [
"python",
"json",
"python-2.7"
] |
Python2 - How to remove characters from output? | 39,091,442 | <p>I made this script that outputs the balance of a group of addresses. The output however comes in a list of one. How do I get python to extract the value from the list, so it doesn't show the ['']?</p>
<pre><code>from lxml import html
import requests
page = requests.get('https://blockchain.info/xpub/xpub6BfKpqjTwvH21wJGWEfxLppb8sU7C6FJge2kWb9315oP4ZVqCXG29cdUtkyu7YQhHyfA5nt63nzcNZHYmqXYHDxYo8mm1Xq1dAC7YtodwUR')
tree = html.fromstring(page.content)
balance = tree.xpath('//*[@id="final_balance"]/font/span/text()')
print str(balance)
</code></pre>
<p>Regards.</p>
| 0 | 2016-08-23T02:34:00Z | 39,091,462 | <pre><code>In [1]: balance
Out[1]: ['0.00622801 BTC']
In [2]: type(balance)
Out[2]: list
In [3]: ''.join(balance)
Out[3]: '0.00622801 BTC'
</code></pre>
| 0 | 2016-08-23T02:36:36Z | [
"python",
"json",
"python-2.7"
] |
How to get different number of ticks and labels in matplotlib? | 39,091,451 | <p>I can't work out how to reduce a number of tick labels in my plot while preserving the number of ticks. Is there a way to do it or can I only have as many ticks as the number of labels? Thanks!</p>
| 1 | 2016-08-23T02:35:41Z | 39,092,758 | <p>Set for some ticks empty tick labels. </p>
<pre><code># based on http://matplotlib.org/examples/ticks_and_spines/ticklabels_demo_rotation.html
import matplotlib.pyplot as plt
x = [1, 2, 3, 4]
y = [1, 4, 9, 6]
labels = ['Frogs', 'Hogs', '', 'Slogs']
plt.plot(x, y, 'ro')
# You can specify a rotation for the tick labels in degrees or with keywords.
plt.xticks(x, labels, rotation='vertical')
# Pad margins so that markers don't get clipped by the axes
plt.margins(0.2)
# Tweak spacing to prevent clipping of tick-labels
plt.subplots_adjust(bottom=0.15)
plt.show()
</code></pre>
<p><a href="http://i.stack.imgur.com/yKL6T.png" rel="nofollow"><img src="http://i.stack.imgur.com/yKL6T.png" alt="enter image description here"></a></p>
| 1 | 2016-08-23T05:05:45Z | [
"python",
"matplotlib"
] |
How to get different number of ticks and labels in matplotlib? | 39,091,451 | <p>I can't work out how to reduce a number of tick labels in my plot while preserving the number of ticks. Is there a way to do it or can I only have as many ticks as the number of labels? Thanks!</p>
| 1 | 2016-08-23T02:35:41Z | 39,095,066 | <p>Just to answer my comment on Serenity's answer, here's how to get the numerical labels.</p>
<pre><code>x = range(100)
labels = []
for i in x:
if i % 10 == 0:
i=i
else:
i=' '
labels.append(i)
</code></pre>
<p>And this does the job.</p>
| 1 | 2016-08-23T07:35:48Z | [
"python",
"matplotlib"
] |
argparse not taking default option | 39,091,452 | <p>Can anyone tell me why the default option is being taken below?</p>
<h3>Code:</h3>
<pre><code>import argparse
parser = argparse.ArgumentParser(description='SCRIPT')
parser.add_argument('-fe','--force_edl',action='store',dest='force_edl',choices=['True', 'False'], default = False,help='<Required> Enable EDL loading by default..',required=False)
global force_edl
results = parser.parse_args()
if results.force_edl:
force_edl = results.force_edl
print "force_edl"
print force_edl
</code></pre>
<h3>Error message:</h3>
<blockquote>
<p>Traceback (most recent call last):</p>
<p>File "defaultparse.py", line 10, in </p>
<p>print force_edl</p>
<p>NameError: global name 'force_edl' is not defined</p>
</blockquote>
| 0 | 2016-08-23T02:35:44Z | 39,091,539 | <pre><code>if results.force_edl:
force_edl = results.force_edl
</code></pre>
<p>The reason why the assignment inside the above <code>if</code> doesn't take place is because:</p>
<pre><code>>>> results
Namespace(force_edl=False)
>>> results.force_edl
False
</code></pre>
<p><code>results.force_edl</code> is a <code>boolean</code> with the value <code>False</code>. What you instead need to be doing is:</p>
<pre><code>if 'force_edl' in results:
force_edl = results.force_edl
</code></pre>
<p>Or, since you already know that <code>results</code> will always have <code>force_dl</code>, just assign directly:</p>
<pre><code>force_edl = results.force_edl
</code></pre>
| 2 | 2016-08-23T02:46:46Z | [
"python"
] |
argparse not taking default option | 39,091,452 | <p>Can anyone tell me why the default option is being taken below?</p>
<h3>Code:</h3>
<pre><code>import argparse
parser = argparse.ArgumentParser(description='SCRIPT')
parser.add_argument('-fe','--force_edl',action='store',dest='force_edl',choices=['True', 'False'], default = False,help='<Required> Enable EDL loading by default..',required=False)
global force_edl
results = parser.parse_args()
if results.force_edl:
force_edl = results.force_edl
print "force_edl"
print force_edl
</code></pre>
<h3>Error message:</h3>
<blockquote>
<p>Traceback (most recent call last):</p>
<p>File "defaultparse.py", line 10, in </p>
<p>print force_edl</p>
<p>NameError: global name 'force_edl' is not defined</p>
</blockquote>
| 0 | 2016-08-23T02:35:44Z | 39,091,603 | <p><code>results.force_edl</code> will always be <code>False</code>. You're updating the global variable after conditional checking, which will never be executed. And the global <code>force_edl</code> will still be undefined since you didn't assign any value to it when you declared.</p>
<p>Do something like the following:</p>
<pre><code>global force_edl = False
</code></pre>
| 0 | 2016-08-23T02:55:08Z | [
"python"
] |
argparse not taking default option | 39,091,452 | <p>Can anyone tell me why the default option is being taken below?</p>
<h3>Code:</h3>
<pre><code>import argparse
parser = argparse.ArgumentParser(description='SCRIPT')
parser.add_argument('-fe','--force_edl',action='store',dest='force_edl',choices=['True', 'False'], default = False,help='<Required> Enable EDL loading by default..',required=False)
global force_edl
results = parser.parse_args()
if results.force_edl:
force_edl = results.force_edl
print "force_edl"
print force_edl
</code></pre>
<h3>Error message:</h3>
<blockquote>
<p>Traceback (most recent call last):</p>
<p>File "defaultparse.py", line 10, in </p>
<p>print force_edl</p>
<p>NameError: global name 'force_edl' is not defined</p>
</blockquote>
| 0 | 2016-08-23T02:35:44Z | 39,091,687 | <p>The error occurred because the variable force_edl was just "<strong>DECLARED</strong>" but not "<strong>DEFINED</strong>" with some value.</p>
<p>It gets assigned in your <code>if</code> block only but that <code>if</code> block won't execute since the value by default will be a false value and hence you get this error.</p>
<blockquote>
<p>You must assign it some value before you use it.</p>
</blockquote>
| 0 | 2016-08-23T03:05:14Z | [
"python"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.