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 listlengths 1 5 |
|---|---|---|---|---|---|---|---|---|---|
Most efficient way to search in list of dicts | 38,865,201 | <p>I have the following list of dicts.</p>
<pre><code>people = [
{'name': "Tom", 'age': 10},
{'name': "Mark", 'age': 5},
{'name': "Pam", 'age': 7}
]
</code></pre>
<p>Which would be the most optimized way in terms of performance to search in list of dicts. Following are different some methods:</p>
<pre><code>next((item for item in dicts if item["name"] == "Pam"), None)
</code></pre>
<p>OR</p>
<pre><code>filter(lambda person: person['name'] == 'Pam', people)
</code></pre>
<p>OR</p>
<pre><code>def search(name):
for p in people:
if p['name'] == name:
return p
</code></pre>
<p>OR</p>
<pre><code>def search_dictionaries(key, value, list_of_dictionaries):
return [element for element in list_of_dictionaries if element[key] == value]
</code></pre>
<p>Any other method is also welcome. Thanks.</p>
| -1 | 2016-08-10T05:50:07Z | 38,865,327 | <p>If you are searching for a single item then this is the "best" approach</p>
<pre><code>def search(name):
for p in people:
if p['name'] == name:
return p
</code></pre>
<p>All the other implementations will iterate over all the items in the list, whereas this one will stop once the item is found</p>
| 0 | 2016-08-10T05:59:30Z | [
"python",
"list",
"dictionary"
] |
Most efficient way to search in list of dicts | 38,865,201 | <p>I have the following list of dicts.</p>
<pre><code>people = [
{'name': "Tom", 'age': 10},
{'name': "Mark", 'age': 5},
{'name': "Pam", 'age': 7}
]
</code></pre>
<p>Which would be the most optimized way in terms of performance to search in list of dicts. Following are different some methods:</p>
<pre><code>next((item for item in dicts if item["name"] == "Pam"), None)
</code></pre>
<p>OR</p>
<pre><code>filter(lambda person: person['name'] == 'Pam', people)
</code></pre>
<p>OR</p>
<pre><code>def search(name):
for p in people:
if p['name'] == name:
return p
</code></pre>
<p>OR</p>
<pre><code>def search_dictionaries(key, value, list_of_dictionaries):
return [element for element in list_of_dictionaries if element[key] == value]
</code></pre>
<p>Any other method is also welcome. Thanks.</p>
| -1 | 2016-08-10T05:50:07Z | 38,865,437 | <p>Doing a quick timeit on the functions show that using filter seems to be the fastest of all the methods</p>
<p><code>%timeit filter(lambda person: person['name'] == 'Pam', people)</code></p>
<p>1000000 loops, best of 3: 263 ns per loop</p>
<ul>
<li>Using next produces a time of 731ns</li>
<li>Using the search method produces a time of 361ns</li>
<li>And lastly the seach_dictionaries uses 811ns</li>
</ul>
| 1 | 2016-08-10T06:06:19Z | [
"python",
"list",
"dictionary"
] |
How to insert app-level constants into a django template | 38,865,279 | <p>Suppose I have a constant defined in my <code>models.py</code> as <code>NUM_IMAGES</code> and I want to access that in a template within the same app. How would I go about doing this? I certainly don't want to put it in the project's <code>settings.py</code>, exposing it to the entire project, nor do I particularly want to expose all settings values to the app as this might hurt modularity. So then, how would I go about referencing my <code>NUM_IMAGES</code> in a template, say <code>detail.html</code>?</p>
| 0 | 2016-08-10T05:55:45Z | 38,865,597 | <p>You can easily expose your constants to view by just wrapping them in context.
so if you want to access NUM_IMAGES in view
first import it into views.py file</p>
<pre><code>from models import NUM_IMAGES
</code></pre>
<p>then pass it to required view</p>
<pre><code>def myview(request):
#something to do
return render( request,'app/page.html',{'NUM_IMAGES':NUM_IMAGES})
</code></pre>
| 1 | 2016-08-10T06:16:54Z | [
"python",
"django"
] |
Are f-strings supposed to work in Python 3.4? | 38,865,348 | <p>Is this supposed to work in Python 3.4:</p>
<p><code>>>> a='tttt'</code></p>
<p><code>>>> print(f'The value of a is {a}')</code></p>
| 0 | 2016-08-09T23:58:21Z | 38,865,359 | <p>No, <code>f</code> strings <a href="https://docs.python.org/3.6/whatsnew/3.6.html#whatsnew-fstrings" rel="nofollow">were introduced in Python 3.6</a> which is currently (as of August 2016) in alpha.</p>
| 1 | 2016-08-10T06:01:46Z | [
"python",
"string",
"python-3.x"
] |
Are f-strings supposed to work in Python 3.4? | 38,865,348 | <p>Is this supposed to work in Python 3.4:</p>
<p><code>>>> a='tttt'</code></p>
<p><code>>>> print(f'The value of a is {a}')</code></p>
| 0 | 2016-08-09T23:58:21Z | 38,866,741 | <p>You could at least emulate them if really needed</p>
<pre><code>def f(string):
# (!) Using globals is bad bad bad
return string.format(**globals())
# Use as follows:
ans = 'SPAM'
print(f('we love {ans}'))
</code></pre>
<p>Or maybe some other ways, like a class with reloaded <code>__getitem__</code> if you like f[...] syntax</p>
| 1 | 2016-08-10T07:23:29Z | [
"python",
"string",
"python-3.x"
] |
Input to the fit method in scikit-learn | 38,865,377 | <p>I'm reading the scikit-learn documentation's Type Casting <a href="http://scikit-learn.org/stable/tutorial/basic/tutorial.html#type-casting" rel="nofollow">example</a>. </p>
<p>My question is about an ndarray operation which is given as an input to the <code>fit</code> method. (Refer the code below)</p>
<pre><code>>>> from sklearn import datasets
>>> from sklearn.svm import SVC
>>> iris = datasets.load_iris()
>>> clf = SVC()
>>> clf.fit(iris.data, iris.target)
SVC(C=1.0, cache_size=200, class_weight=None, coef0=0.0,
decision_function_shape=None, degree=3, gamma='auto', kernel='rbf',
max_iter=-1, probability=False, random_state=None, shrinking=True,
tol=0.001, verbose=False)
>>> list(clf.predict(iris.data[:3]))
[0, 0, 0]
>>> clf.fit(iris.data, iris.target_names[iris.target])
SVC(C=1.0, cache_size=200, class_weight=None, coef0=0.0,
decision_function_shape=None, degree=3, gamma='auto', kernel='rbf',
max_iter=-1, probability=False, random_state=None, shrinking=True,
tol=0.001, verbose=False)
>>> list(clf.predict(iris.data[:3]))
['setosa', 'setosa', 'setosa']
</code></pre>
<p><strong>Question:</strong> In this part in the code above <code>clf.fit(iris.data, iris.target_names[iris.target])</code>, what is the operation performed as <code>iris.target_names[iris.target]</code> ?</p>
<p>A few more information:</p>
<pre><code>iris.target_names
array(['setosa', 'versicolor', 'virginica'],
dtype='|S10')
iris.target
array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2])
iris.target_names[iris.target]
array(['setosa', 'setosa', 'setosa', 'setosa', 'setosa', 'setosa',
'setosa', 'setosa', 'setosa', 'setosa', 'setosa', 'setosa',
'setosa', 'setosa', 'setosa', 'setosa', 'setosa', 'setosa',
'setosa', 'setosa', 'setosa', 'setosa', 'setosa', 'setosa',
'setosa', 'setosa', 'setosa', 'setosa', 'setosa', 'setosa',
'setosa', 'setosa', 'setosa', 'setosa', 'setosa', 'setosa',
'setosa', 'setosa', 'setosa', 'setosa', 'setosa', 'setosa',
'setosa', 'setosa', 'setosa', 'setosa', 'setosa', 'setosa',
'setosa', 'setosa', 'versicolor', 'versicolor', 'versicolor',
'versicolor', 'versicolor', 'versicolor', 'versicolor',
'versicolor', 'versicolor', 'versicolor', 'versicolor',
'versicolor', 'versicolor', 'versicolor', 'versicolor',
'versicolor', 'versicolor', 'versicolor', 'versicolor',
'versicolor', 'versicolor', 'versicolor', 'versicolor',
'versicolor', 'versicolor', 'versicolor', 'versicolor',
'versicolor', 'versicolor', 'versicolor', 'versicolor',
'versicolor', 'versicolor', 'versicolor', 'versicolor',
'versicolor', 'versicolor', 'versicolor', 'versicolor',
'versicolor', 'versicolor', 'versicolor', 'versicolor',
'versicolor', 'versicolor', 'versicolor', 'versicolor',
'versicolor', 'versicolor', 'versicolor', 'virginica', 'virginica',
'virginica', 'virginica', 'virginica', 'virginica', 'virginica',
'virginica', 'virginica', 'virginica', 'virginica', 'virginica',
'virginica', 'virginica', 'virginica', 'virginica', 'virginica',
'virginica', 'virginica', 'virginica', 'virginica', 'virginica',
'virginica', 'virginica', 'virginica', 'virginica', 'virginica',
'virginica', 'virginica', 'virginica', 'virginica', 'virginica',
'virginica', 'virginica', 'virginica', 'virginica', 'virginica',
'virginica', 'virginica', 'virginica', 'virginica', 'virginica',
'virginica', 'virginica', 'virginica', 'virginica', 'virginica',
'virginica', 'virginica', 'virginica'],
dtype='|S10')
</code></pre>
<p>I understand my question is not scikit-learn specific but has something to do with the understanding of numpy operations. I have read the numpy documentation but couldn't figure this out myself. Any help is much appreciated. Thanks.</p>
| 0 | 2016-08-10T06:02:42Z | 38,865,654 | <p><code>iris.target</code> is used as an <a href="http://docs.scipy.org/doc/numpy-1.10.1/user/basics.indexing.html#index-arrays" rel="nofollow">index array</a> in that operation. </p>
<p>Consider the following array:</p>
<pre><code>arr = np.array(['a', 'b', 'c'])
arr
Out:
array(['a', 'b', 'c'],
dtype='<U1')
</code></pre>
<p>At index 0, it has 'a':</p>
<pre><code>arr[0]
Out: 'a'
</code></pre>
<p>At index 0 and 1, it has 'a' and 'b':</p>
<pre><code>arr[[0, 1]]
Out:
array(['a', 'b'],
dtype='<U1')
</code></pre>
<p>These indices may have duplicates:</p>
<pre><code>arr[[0, 1, 0]]
Out:
array(['a', 'b', 'a'],
dtype='<U1')
</code></pre>
<p>In your example, <code>iris.target</code> is an array of encoded labels. To get their names, you use <code>iris.target</code> as an index to <code>iris.target_names</code> so it gives you the corresponding names for each element.</p>
| 0 | 2016-08-10T06:20:15Z | [
"python",
"numpy",
"scikit-learn"
] |
Or statements for complex regex formation in python | 38,865,480 | <p>I need to formulate a regex to pick up only the first part of a particular string rather than the second part. For example: </p>
<pre><code> (part1) (Part2)
SAI Table
Cloth
DARA
</code></pre>
<p>I want to extract only <code>SAI</code> (i.e. part1 and not part2). Notice that the 2nd line is empty in part 1 and hence it should return an empty space (and not <code>cloth</code>). The same regex must work for all three cases of strings. In the case of string2 part one must return a blank space and not <code>table</code>. There is no certain length of spaces between the two parts. It varies.</p>
<p>This is the regex I tried, but it only works for string1 and string3:</p>
<pre><code>[\s]{1,}((?:[a-zA-Z)(@\-,."'',&*]+[\s]?)+)[\s]{2,}
</code></pre>
<p>Is there any way to write a regex that would work in this case? </p>
<p>I can only use regex here as I need it to return any string present there. The string can be alpha-numerals and may contain the most popularly used symbols present in my earlier regex. The space between the two is never fixed. </p>
<p>I also need it to return a space where it is empty in part 1. We can ignore part 2. But I have to make sure that the regex does not match part 2.</p>
| 0 | 2016-08-10T06:09:59Z | 38,866,178 | <p>Using named capturing groups you are able to distinguish between captured parts:</p>
<pre><code>(?: +(?P<one>(?:\w+)?))?(?: +(?P<two>(?:\w+)?))
</code></pre>
<p><a href="https://regex101.com/r/uB7wV6/2" rel="nofollow">Live demo</a></p>
| 0 | 2016-08-10T06:50:13Z | [
"python",
"regex",
"string"
] |
Or statements for complex regex formation in python | 38,865,480 | <p>I need to formulate a regex to pick up only the first part of a particular string rather than the second part. For example: </p>
<pre><code> (part1) (Part2)
SAI Table
Cloth
DARA
</code></pre>
<p>I want to extract only <code>SAI</code> (i.e. part1 and not part2). Notice that the 2nd line is empty in part 1 and hence it should return an empty space (and not <code>cloth</code>). The same regex must work for all three cases of strings. In the case of string2 part one must return a blank space and not <code>table</code>. There is no certain length of spaces between the two parts. It varies.</p>
<p>This is the regex I tried, but it only works for string1 and string3:</p>
<pre><code>[\s]{1,}((?:[a-zA-Z)(@\-,."'',&*]+[\s]?)+)[\s]{2,}
</code></pre>
<p>Is there any way to write a regex that would work in this case? </p>
<p>I can only use regex here as I need it to return any string present there. The string can be alpha-numerals and may contain the most popularly used symbols present in my earlier regex. The space between the two is never fixed. </p>
<p>I also need it to return a space where it is empty in part 1. We can ignore part 2. But I have to make sure that the regex does not match part 2.</p>
| 0 | 2016-08-10T06:09:59Z | 38,868,005 | <p>If the first column (<em>part1</em>) is <strong>always</strong> followed by 2 spaces, whereas the second (<em>part2</em>) is not, you can rely on that condition to prevent a match in the last column. We can use the <a href="http://www.regular-expressions.info/lookaround.html" rel="nofollow">lookahead</a> <code>(?=[\t ]{2})</code> to assert for 2 consecutive spaces or tabs.</p>
<p><strong>Code</strong></p>
<pre class="lang-python prettyprint-override"><code>import re
patt = r'^[\t ]*(\S+(?:[\t ]\S+)*(?=[\t ]{2})| )'
str = r'''
(part1) (Part2)
SAI Table
Cloth
DARA
'''
print re.findall(patt, str, re.MULTILINE)
</code></pre>
<p><strong>Output</strong></p>
<pre><code>['(part1)', 'SAI', ' ', 'DARA']
</code></pre>
<p><kbd><a href="http://ideone.com/lqvLXX" rel="nofollow">ideone demo</a></kbd></p>
<p>You may as well change <code>\S</code> to <code>[a-zA-Z)(@\-,."'',&*]</code> to limit the allowed characters.</p>
| 1 | 2016-08-10T08:28:14Z | [
"python",
"regex",
"string"
] |
how to inquire an iterator in python without changing its pre-inquire state | 38,865,601 | <p>I built an iterable object A that holds a list of other objects B. I want to be able to automatically skip a particular object B on the list if it is flagged bad when the object A is used in a for loop.</p>
<pre><code>class A():
def __init__(self):
self.Blist = [B(1), B(2), B(3)] #where B(2).is_bad() is True, while the other .is_bad() are False
def __iter__(self):
nextB = iter(self.Blist)
#if nextB.next().is_bad():
# return after skip
#else:
# return nextB
</code></pre>
<p>However, I cannot figure out how to write the conditional that is commented in pseudo code above, without skipping the iteration inquired (the else clause fails)</p>
<p>Thanks!</p>
| 5 | 2016-08-10T06:17:03Z | 38,865,761 | <p>How about:</p>
<pre><code>def __iter__(self):
nextB = iter(self.Blist)
for b_obj in nextB:
if b_obj.is_bad():
yield b_obj
</code></pre>
<p>A simplified example:</p>
<pre><code>class B:
def __init__(self, cond):
self.cond = cond
def is_bad(self):
return self.cond
class A:
def __init__(self):
self.Blist = [B(True), B(False), B(True)]
def __iter__(self):
nextB = iter(self.Blist)
for b_obj in nextB:
if b_obj.is_bad():
yield b_obj
a = A()
for x in a:
print(x.is_bad())
>> True
True
</code></pre>
| 1 | 2016-08-10T06:26:54Z | [
"python",
"oop",
"iterator"
] |
how to inquire an iterator in python without changing its pre-inquire state | 38,865,601 | <p>I built an iterable object A that holds a list of other objects B. I want to be able to automatically skip a particular object B on the list if it is flagged bad when the object A is used in a for loop.</p>
<pre><code>class A():
def __init__(self):
self.Blist = [B(1), B(2), B(3)] #where B(2).is_bad() is True, while the other .is_bad() are False
def __iter__(self):
nextB = iter(self.Blist)
#if nextB.next().is_bad():
# return after skip
#else:
# return nextB
</code></pre>
<p>However, I cannot figure out how to write the conditional that is commented in pseudo code above, without skipping the iteration inquired (the else clause fails)</p>
<p>Thanks!</p>
| 5 | 2016-08-10T06:17:03Z | 38,865,781 | <p>You can use a generator function:</p>
<pre><code> def __iter__(self):
for item in self.Blist:
if not item.is_bad():
yield item
</code></pre>
<p>A generator function is marked by the keyword <code>yield</code>. A generator function returns a generator object, which is an iterator. It will suspend execution at the <code>yield</code> statement and then resume processing when the calling routine calls <code>next</code> on the interator. </p>
| 1 | 2016-08-10T06:27:47Z | [
"python",
"oop",
"iterator"
] |
How can I run python scikit-learn on Raspberry Pi? | 38,865,708 | <p>I'm new in embedded programming, and would like to understand what I need to do to run python scikit-learn on a capable embedded processor.<br>
See Raspberry Pi as an example. </p>
| 0 | 2016-08-10T06:23:27Z | 38,866,597 | <p><code>scikit-learn</code> will run on a Raspberry Pi just as well as any other Linux machine.</p>
<p>To install it, make sure you have <code>pip3</code> (<code>sudo apt-get install python3-pip</code>), and use <code>sudo pip3 install scikit-learn</code>.</p>
<p>All Python scripts utilizing <code>scikit-learn</code> will now run as normal.</p>
| 0 | 2016-08-10T07:16:20Z | [
"python",
"raspberry-pi",
"scikit-learn"
] |
match values of dictionaries | 38,865,743 | <p>I have a collection of records stored if several dictionaries:</p>
<pre><code>d1 = {'id':['223','444'],'value_1':['v1','x1']}
d2 = {'id': ['223','666'],'value_2':['v2','x2']}
d3 = {'id':['223','444'], 'value_3':['v3','x3']}
</code></pre>
<p>I want to search all the records that match the id of the first dictionary and save them in a new one with all the fields, 'value_1', 'value_2' and 'value_3':</p>
<pre><code>d_4 = {'id':[],'value_1':[],'value_2':[],'value_3':[]}
</code></pre>
<p>if one of the records doesn't exist in all the dictionaries I will add '----' in that field. So the output, in this case, will be:</p>
<pre><code>d_4
{'id': ['223', '444'],
'value_1': ['v1', 'x1'],
'value_2': ['v2', '----'],
'value_3': ['x3', 'x3']}
</code></pre>
<p>I wrote this code to do so:</p>
<pre><code>for i,id_d1 in enumerate(d1['id']):
d_4['id'].append(id_d1)
d_4['value_1'].append(d1['value_1'][i])
if id_d1 in d2['id']:
for j,id_d2 in enumerate(d2['id']):
if id_d1==id_d2:
d_4['value_2'].append(d2['value_2'][j])
else:
d_4['value_2'].append('----')
if id_d1 in d3['id']:
for k,id_d3 in enumerate(d3['id']):
if id_d1==id_d3:
d_4['value_3'].append(d3['value_3'][j])
else:
d_4['value_3'].append('----')
</code></pre>
<p>But doesn't seems like a good approach.</p>
| 0 | 2016-08-10T06:25:34Z | 38,868,600 | <p>Maybe this will help you:</p>
<p>Code:</p>
<pre><code>import sys
print(sys.version)
# you should use an iterable for your data
in_list = [{'id':['223','444'],'value_1':['v1','x1']},
{'id': ['223','666'],'value_2':['v2','x2']},
{'id':['223','444'], 'value_3':['v3','x3']}
]
print "Input:\n", in_list
# note that dictionaries are not ordered
out_dict = {}
out_dict["id"] = in_list[0]["id"]
out_dict["value_1"] = in_list[0]["value_1"]
for i,d in enumerate(in_list[1:]):
values = [v[1] for v in d.items() if "value" in v[0]][0]
#print(i, d, values)
if in_list[i+1]["id"] != in_list[0]["id"]:
values[1] = "---"
out_dict["value_{}".format(i+2)] = values
print "Output:\n", out_dict
</code></pre>
<p>Out:</p>
<pre><code>2.7.2 (default, Aug 31 2011, 14:05:14)
[GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build)]
Input:
[{'value_1': ['v1', 'x1'], 'id': ['223', '444']}, {'id': ['223', '666'], 'value_2': ['v2', 'x2']}, {'id': ['223', '444'], 'value_3': ['v3', 'x3']}]
Output:
{'value_1': ['v1', 'x1'], 'id': ['223', '444'], 'value_3': ['v3', 'x3'], 'value_2': ['v2', '---']}
</code></pre>
<p><hr>
Update: fix errors to get required output
Update2: i+1 offset</p>
| 1 | 2016-08-10T08:56:06Z | [
"python",
"dictionary"
] |
Script causing DevTools to crash | 38,865,750 | <p>I'm trying to write a chatbot for entertainment, and one of its primary functions is meme lookup. I first wrote this in Python, but I'm now rewriting it in JavaScript, as it can then run totally client side.</p>
<p>Here is my JavaScript <code>meme()</code> function:</p>
<pre><code>function meme(srch) {
reqUrl = "http://api.pixplorer.co.uk/image?amount=1&size=tb&word=meme";
memesrch = "";
while (srch) {
memesrch += "+" + srch[0];
srch.slice(1);
}
reqUrl += memesrch;
$.get(reqUrl, function( result ) {
memeUrl = result['images'][0]['imageurl'];
});
return "<a href='" + memeUrl + "'><img src='" + memeUrl + "' style='height: 130px;' /></a>";
}
</code></pre>
<p>Here's the original Python function for it, if it might help:</p>
<pre><code>def meme(srch):
reqUrl = "http://api.pixplorer.co.uk/image?amount=1&size=tb&word=meme"
if srch:
memesrch = ""
while srch:
memesrch += srch[0] + "+"
srch = srch[1:]
memesrch = memesrch[:-1]
reqUrl += memesrch
memeUrl = eval(urllib2.urlopen(reqUrl).read())['images'][0]['imageurl']
return "<a href='" + memeUrl + "'><img src='" + memeUrl + "' style='height: 130px;' /></a>"
</code></pre>
<p>My problem with this is that when I first run <code>meme()</code> in the console after a page load/reload, it says the variable <code>memeUrl</code> isn't defined. Then, from the second time onwards, it works fine. However, if I then type <code>meme(["doge"])</code> or give any string in an array, or even just a string like <code>meme("hello")</code> to the <code>meme()</code> function, it doesn't return anything, not even an error. After that, anything I type returns nothing, not even something like <code>1+1</code>, or <code>3</code>, or <code>$</code>. After a few seconds the webpage crashes. Here are some screenshots: <a href="http://i.stack.imgur.com/LUulI.png" rel="nofollow">Screenshot of DevTools</a>, <a href="http://i.stack.imgur.com/Oygwy.png" rel="nofollow">Screenshot of Webpage Crash</a>.</p>
<p>I have no idea what's causing these, as the only thing I can think of that could cause this problem is an infinite loop, but there isn't one in my code.</p>
| 0 | 2016-08-10T06:26:27Z | 38,865,917 | <p>There is an infinite loop:</p>
<pre><code>while (srch) {
...
}
</code></pre>
<p><code>srch.slice</code> does not change the originial array "srch".
Maybe this solves your issue: Instead of your while loop do the following:</p>
<pre><code>memesrch = (srch typeof Array)
? '+' + srch.join('+')
: '+' + srch;
</code></pre>
| 0 | 2016-08-10T06:36:23Z | [
"javascript",
"python",
"google-chrome",
"devtools"
] |
how to address zip list in sort lambda | 38,865,850 | <p>I have a class with 2 attributes which are lists themselves:</p>
<pre><code>class data...:
list1 = [["g1", 2.0], ["x1", 3.0]...] # n elements
list2 = [[2, 4, 5],[3, 2, 1]...] # n elements
</code></pre>
<p>I need to zip sort both lists, based on value of the second element of <code>list2</code>.</p>
<pre><code>zipped = zip(dataobj.list1, dataobj.list2)
zipped.sort(cmp = lambda k: dataobj.list2[2])
</code></pre>
<p>This seems to not work. </p>
<p>How do I reference the second element of <code>dataobj.list2[2]</code> as this is not working and gave me the following error:</p>
<pre><code>TypeError: <lambda>() takes exactly 1 argument (2 given)
</code></pre>
| 1 | 2016-08-10T06:31:45Z | 38,865,958 | <p><code>cmp</code> should be a reference to a function that compares two values. Instead, you need something much simpler - a <code>key</code> field.</p>
<p>The easiest way would be to reference the value directly from <code>zipped</code> instead of going back to the original value in <code>list2</code>. Note, BTW, that lists in python are zero-based, so the second element would be <code>[1]</code>, not <code>[2]</code>. To make a long story short:</p>
<pre><code>zipped.sort(key = lambda k : k[1][1])
</code></pre>
| 2 | 2016-08-10T06:38:09Z | [
"python",
"sorting",
"lambda"
] |
strange with use request.args? | 38,865,858 | <p>submit an Ip to post1.py</p>
<pre><code>@main.route('/post1',methods=['GET','POST'])
@login_required
def post1():
Ip=request.form['Ip']
print Ip
return redirect(url_for('.post',Ip=Ip))
</code></pre>
<p>then redirect to post.py</p>
<pre><code>@main.route('/post', methods=['GET', 'POST'])
@login_required
def post():
#Ip=request.args['Ip']
form = RepairForm(request.form)
print request.form
if request.method == "POST":
repair = Repair(Ip=form.ip.data,Series=form.series.data,Hostname=form.hostname.data,
ManagerIp=form.managerip.data,Comp=form.comp.data,
Model=form.model.data,Location=form.location.data,Box=form.box.data,
Important=form.important.data,Faultype=form.faultype.data,
Subject=form.subject.data,Body=form.body.data,Classify=form.classify.data,
Status=form.status.data,auth_id=current_user._get_current_object().id,
Owner=current_user._get_current_object().username,)
db.session.add(repair)
db.session.commit()
flash('æ¥ä¿®æå')
return redirect(url_for('.index'))
form.ip.data=1
print form.ip.data
form.hostname.data=1
print form.hostname.data
print request.form
form.managerip.data=1
form.comp.data=1
form.model.data=1
form.location.data=1
form.box.data=1
form.important.data=1
form.faultype.data=1
form.classify.data=1
form.status.data=1
return render_template('post.html',form=form)
</code></pre>
<p>all test ok,but when I uncomment <strong><em>Ip=request.args['Ip']</em></strong>,then test returns 'The browser (or proxy) sent a request that this server could not understand',</p>
| -1 | 2016-08-10T06:32:24Z | 38,867,983 | <p>use request.args.get('Ip') solved this error,but do not know the reason because request.args['Ip'] still can get the data.</p>
| 0 | 2016-08-10T08:27:04Z | [
"python",
"forms",
"flask",
"request"
] |
strange with use request.args? | 38,865,858 | <p>submit an Ip to post1.py</p>
<pre><code>@main.route('/post1',methods=['GET','POST'])
@login_required
def post1():
Ip=request.form['Ip']
print Ip
return redirect(url_for('.post',Ip=Ip))
</code></pre>
<p>then redirect to post.py</p>
<pre><code>@main.route('/post', methods=['GET', 'POST'])
@login_required
def post():
#Ip=request.args['Ip']
form = RepairForm(request.form)
print request.form
if request.method == "POST":
repair = Repair(Ip=form.ip.data,Series=form.series.data,Hostname=form.hostname.data,
ManagerIp=form.managerip.data,Comp=form.comp.data,
Model=form.model.data,Location=form.location.data,Box=form.box.data,
Important=form.important.data,Faultype=form.faultype.data,
Subject=form.subject.data,Body=form.body.data,Classify=form.classify.data,
Status=form.status.data,auth_id=current_user._get_current_object().id,
Owner=current_user._get_current_object().username,)
db.session.add(repair)
db.session.commit()
flash('æ¥ä¿®æå')
return redirect(url_for('.index'))
form.ip.data=1
print form.ip.data
form.hostname.data=1
print form.hostname.data
print request.form
form.managerip.data=1
form.comp.data=1
form.model.data=1
form.location.data=1
form.box.data=1
form.important.data=1
form.faultype.data=1
form.classify.data=1
form.status.data=1
return render_template('post.html',form=form)
</code></pre>
<p>all test ok,but when I uncomment <strong><em>Ip=request.args['Ip']</em></strong>,then test returns 'The browser (or proxy) sent a request that this server could not understand',</p>
| -1 | 2016-08-10T06:32:24Z | 38,868,384 | <p>This post points out the <a href="http://stackoverflow.com/questions/8552675/form-sending-error-flask">Form sending error</a>:</p>
<blockquote>
<p>Flask raises an HTTP error when it fails to find a key in the args and form dictionaries. What Flask assumes by default is that if you are asking for a particular key and it's not there then something got left out of the request and the entire request is invalid.</p>
</blockquote>
<p>You can't use <code>request.args['Ip']</code>because Flask use a custom dictionary implementation from werkzeug called <a href="http://werkzeug.pocoo.org/docs/0.11/datastructures/#werkzeug.datastructures.MultiDict" rel="nofollow">MultiDict</a>. It has his own get method.</p>
| 0 | 2016-08-10T08:45:57Z | [
"python",
"forms",
"flask",
"request"
] |
Getting non string value as a json key in python | 38,866,023 | <p>I'm using "ODK" integeration in one of my django project.</p>
<p>I'm getting a json format from a response(request.body) in a django view which is in the way that all the keys in it are non-string.
ex : </p>
<pre><code>{
key1 : "value1",
key2 : "value2"
}
</code></pre>
<p>Since the keys in it are non string I have no idea how to access the values inside the json.I need to know what type of json this one is and how to progress it in order to convert the json to a dictionary.</p>
<p>This is the json file am getting:</p>
<pre><code>{
token: "testauthtoken",
content: "record",
formId: "maintenance_ct",
formVersion: "",
}
</code></pre>
| 0 | 2016-08-10T06:41:32Z | 38,866,455 | <p>As others have pointed out, this is not valid JSON, for two reasons: the unquoted key names and the trailing comma at the end.</p>
<p>Your best bet if possible would be to fix the server code that generates this to produce correct JSON instead. Perhaps that code is creating the "JSON" by manually pasting strings together? If so, you could change it to use <code>json.dumps()</code> instead. That will give you valid JSON.</p>
<p>Failing that, you could preprocess the "JSON" text to surround the key names with quotes and to remove the trailing comma. This can be a bit fragile, but if you know the format of the input data will remain similar, it's one way to do it:</p>
<pre><code>import json, re
badJson = '''
{
token: "testauthtoken",
content: "record",
formId: "maintenance_ct",
formVersion: "",
}
'''
print( 'badJson:' )
print( badJson )
goodJson = re.sub( r'\n\s*(\S+)\s*:', r'\n"\1":', badJson )
goodJson = re.sub( r',\s*}', r'\n}', goodJson )
print( 'goodJson:' )
print( goodJson )
goodData = json.loads( goodJson )
print( 'goodData:' )
print( goodData )
</code></pre>
<p>This prints:</p>
<pre><code>badJson:
{
token: "testauthtoken",
content: "record",
formId: "maintenance_ct",
formVersion: "",
}
goodJson:
{
"token": "testauthtoken",
"content": "record",
"formId": "maintenance_ct",
"formVersion": ""
}
goodData:
{'formId': 'maintenance_ct', 'content': 'record', 'token': 'testauthtoken', 'formVersion': ''}
</code></pre>
<p>When I first wrote this answer I misunderstood the question and provided a JavaScript solution instead of Python. In case this is useful for anyone I'll leave it here:</p>
<p>While the input text is not valid JSON, it is a valid JavaScript object literal. So you can treat it as such and use <code>eval()</code> to parse it. In fact, this is how libraries such as jQuery parsed JSON in old browsers that didn't support <code>JSON.parse()</code>.</p>
<p><strong>BEWARE:</strong> You had best be sure that you trust the source of this data string, since you are treating it as executable code!</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>// Set up a string like your input data string.
// All on one line here so we can use a string constant for testing,
// but your multiline data string will work the same.
var dataString = '{ token: "testauthtoken", content: "record", formId: "maintenance_ct", formVersion: "", }'
// Now use eval() to convert it to a JavaScript object.
// We wrap the string in parentheses so it will parse as an expression.
var data = eval( '(' + dataString + ')' );
// Finally, we can access the values.
console.log( 'token: ', data.token );
console.log( 'content: ', data.content );
console.log( 'formId: ', data.formId );
console.log( 'formVersion: ', data.formVersion );</code></pre>
</div>
</div>
</p>
| 2 | 2016-08-10T07:07:51Z | [
"python",
"json",
"dictionary"
] |
how to run selective modules from a directory using nosetests? | 38,866,116 | <p>I have multiple modules in same directory and i'm running the below nosetests command:
nosetests --processes=2 --process-timeout=1500 -v --nocapture -a=attr --attr=api --exclude-dir-file=src/tests/externalapi/test_p0_security_tests.py --with-xunitmp</p>
<p>No luck tests in test_p0_security_tests.py still executed.</p>
| -1 | 2016-08-10T06:46:50Z | 38,870,038 | <p><code>nosetests</code> does not support <code>--exclude-dir-file</code> by default. Since you are not reporting getting an error about the option being invalid, and there is only one plugin I know that provides this option, I'm assuming you are using the <a href="https://pypi.python.org/pypi/nose-exclude" rel="nofollow"><code>nose-exclude</code></a> plugin. <code>--exclude-dir-file</code> takes for value a <em>file that contains a list of directories to ignore</em>. Passing the name of a module to ignore is not the correct use for it.</p>
<p>At any rate, there's the <code>--ignore-files</code> option which does take a regular expression. The regular expression appears to be matched against the <em>base name</em> of the test file rather than the full path. <code>--ignore-files=test_p0_security_tests.py</code> should do it. (If you want you can escape the dot because it is a wildcard, but I usually don't bother.)</p>
| 0 | 2016-08-10T09:57:23Z | [
"python",
"nose"
] |
TypeError: framechange() missing 1 required positional argument: 'get' | 38,866,117 | <p>I'm trying to create a basic password storage program and am having trouble with the error code in the title</p>
<pre><code>class StartPage(tk.Frame):
entry = "password"
def framechange(self, get):
if self.entry.get() == "password":
controller.show_frame("PageOne")
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
label = tk.Label(self, text="Welcome", font=TITLE_FONT)
label.pack(side="top", fill="x", pady=10)
self.entry = tk.Entry(self)
self.entry.pack(side="top", fill="x", pady=10, padx=10)
button1 = tk.Button(self, text="Login",command = self.framechange)
button1.pack()
</code></pre>
<p>Any help would be great, thanks </p>
| -1 | 2016-08-10T06:46:55Z | 38,866,182 | <p>The <code>framechange</code> method expects an argument, yet you are not providing it when it is called by the button's callback (<code>button1 = tk.Button(self, text="Login",command = self.framechange</code>).</p>
<p>It seems like you don't even need that argument, as you are not using it. </p>
<p>Try changing <code>def framechange(self, get):</code> to <code>def framechange(self):</code></p>
| 0 | 2016-08-10T06:50:32Z | [
"python",
"get"
] |
Resize images to very small n x n dimensions | 38,866,162 | <p>I am resizing my images to 50 x 50 in python. Skimage transform and PIL thumbnail both resize the image while preserving the aspect ratio.
Whats the other way to do it?
I have tried:
For PIL thumbnail,</p>
<pre><code>im.thumbnail((50,50),Image.ANTIALIAS)
</code></pre>
<p>This gives me a (42,50) image not a (50,50) image.</p>
<p>For skimage.transform</p>
<pre><code>image = skimage.transform.resize(image, (50, 50))
</code></pre>
<p>It returns a completely distorted image.</p>
| 0 | 2016-08-10T06:49:15Z | 39,942,518 | <p>Use <code>im.resize((50,50), Image.ANTIALIAS)</code></p>
| 0 | 2016-10-09T10:25:31Z | [
"python",
"image",
"resize",
"python-imaging-library",
"skimage"
] |
pywinauto.findwindows.WindowNotFoundError in pywinauto | 38,866,272 | <p>I am new in pywinauto and have just started learning. I have installed pywinauto with pip in my local 32 bit Windows 7 OS.
So, I have this sample code to open an URL in chrome browser.</p>
<pre><code>from pywinauto import application
app=application.Application()
app.start(r'C:\Program Files\Google\Chrome\Application\chrome.exe')
app.window_(title='New Tab')
app.window_().TypeKeys('{F6}')
app.window_().TypeKeys('{ESC}')
app.window_().TypeKeys('www.facebook.com')
</code></pre>
<p>On running it, it is throwing error:</p>
<pre><code>Traceback (most recent call last):
File "pywinauto_nil.py", line 6, in <module>
app.window_().TypeKeys('{F6}')
File "C:\Python27\lib\site-packages\pywinauto\application.py", line 252, in
__getattr__
ctrls = _resolve_control(self.criteria)
File "C:\Python27\lib\site-packages\pywinauto\application.py", line 758, in _resolve_control
raise e.original_exception
pywinauto.findwindows.WindowNotFoundError
</code></pre>
<p>I have googled, but could not find any helpful solution.</p>
<p>Where am I going wrong?</p>
| 3 | 2016-08-10T06:55:42Z | 38,868,466 | <p>The full answer would be long and complicated. Let's start from your small problem.</p>
<ol>
<li><p>Chrome spawns few more processes that is not connected with <code>app</code> object. Solution: use <code>Application().connect(title='New tab')</code> (or <code>title_re</code> or whatever possible for <a href="http://pywinauto.github.io/docs/code/pywinauto.findwindows.html" rel="nofollow">find_windows</a>).</p></li>
<li><p>The bigger problem is that Chrome controls cannot be detected and handled by pywinauto 0.5.4 because MS UI Automation support is on the way (70% done in UIA branch on GitHub, see <a href="https://github.com/pywinauto/pywinauto/wiki/0.6.0-README-prototype" rel="nofollow">the short intro</a>). By the way, pywinauto/UIA can handle top-level windows in a process-agnostic way: <code>Desktop(backend='uia').NewTab.type_keys('some_URL')</code></p></li>
<li><p>One more detail about Chrome. It doesn't enable UIA support by default. <a href="https://github.com/pywinauto/pywinauto/wiki/How-to-enable-accessibility-(tips-and-tricks)" rel="nofollow">To enable UIA accessibility</a> it must run so: <code>chrome.exe --force-renderer-accessibility</code>. Though UIA mode is enabled by default in Firefox and Opera.</p></li>
</ol>
<p>And finally pywinauto is not specifically designed for Web automation. Right now it might be combined with Selenium.</p>
| 3 | 2016-08-10T08:49:48Z | [
"python",
"pywinauto"
] |
pywinauto.findwindows.WindowNotFoundError in pywinauto | 38,866,272 | <p>I am new in pywinauto and have just started learning. I have installed pywinauto with pip in my local 32 bit Windows 7 OS.
So, I have this sample code to open an URL in chrome browser.</p>
<pre><code>from pywinauto import application
app=application.Application()
app.start(r'C:\Program Files\Google\Chrome\Application\chrome.exe')
app.window_(title='New Tab')
app.window_().TypeKeys('{F6}')
app.window_().TypeKeys('{ESC}')
app.window_().TypeKeys('www.facebook.com')
</code></pre>
<p>On running it, it is throwing error:</p>
<pre><code>Traceback (most recent call last):
File "pywinauto_nil.py", line 6, in <module>
app.window_().TypeKeys('{F6}')
File "C:\Python27\lib\site-packages\pywinauto\application.py", line 252, in
__getattr__
ctrls = _resolve_control(self.criteria)
File "C:\Python27\lib\site-packages\pywinauto\application.py", line 758, in _resolve_control
raise e.original_exception
pywinauto.findwindows.WindowNotFoundError
</code></pre>
<p>I have googled, but could not find any helpful solution.</p>
<p>Where am I going wrong?</p>
| 3 | 2016-08-10T06:55:42Z | 38,872,473 | <p>To add to what Vasily said:</p>
<p>There might be another problem here.</p>
<p>If your Chrome is too slow to start, the connection might miss it.</p>
<p>I think this is somehow regulated in start method, but as chrome starts more than one process it may cause the problem.</p>
<p>I advise you to use Python's module "webbrowser" to start Chrome, then try Connecting to it with pywinauto.</p>
<p>There is an option, if I remember correctly, to wait until the window appears. Just specify the timeout. Otherwise try connect in a definite loop with some sleeping inbetween tries.</p>
<p>It may work, or it may not, depends whether UIA support is needed. If it is, you have to start Chrome with UIA support.</p>
| 0 | 2016-08-10T11:41:56Z | [
"python",
"pywinauto"
] |
the program stop run is caused by python udp stay in a place | 38,866,491 | <p>I have one question about <code>socket</code> in python.
I use <code>udp-protocol</code> in my program. There is the following error usually happening in the program. My program stay in a point. Using <code>pstack pid</code>, the detail message is as followsï¼</p>
<pre><code>$ pstack 12776
#0 0x000000318b20e9a3 in __recvfrom_nocancel () from /lib64/libpthread.so.0
#1 0x00007f2fbc14fad1 in sock_recvfrom_guts () from /home/work/local/lib/python2.7/lib-dynload/_socket.so
#2 0x00007f2fbc14fd82 in sock_recvfrom () from /home/work/local/lib/python2.7/lib-dynload/_socket.so
#3 0x000000000049bdc0 in PyEval_EvalFrameEx ()
#4 0x000000000049c83e in PyEval_EvalFrameEx ()
#5 0x000000000049c83e in PyEval_EvalFrameEx ()
#6 0x000000000049d93e in PyEval_EvalCodeEx ()
#7 0x000000000049da52 in PyEval_EvalCode ()
#8 0x00000000004bd2f0 in PyRun_FileExFlags ()
#9 0x00000000004bd4bc in PyRun_SimpleFileExFlags ()
#10 0x000000000041608c in Py_Main ()
#11 0x000000318ae1ecdd in __libc_start_main () from /lib64/libc.so.6
#12 0x0000000000415019 in _start ()
</code></pre>
<p>I think <code>upd-protocol</code> should be no problem. I really don't understand why the condition happens. There is no one can help me, thank youï¼The python's version is 2.7.3.My code follows:</p>
<pre><code>address = (server_ip, server_port);
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.sendto(send_buf, address)
response, addr = s.recvfrom(2048)
if response:
real_body = self.parse_response(response)
</code></pre>
| 0 | 2016-08-10T07:10:01Z | 39,116,233 | <p>I found a reason.I used udp protocol in my code.Sometimes because of net problem, client can't data that server send.
Final, I solved this problem by using select function in client.</p>
| 0 | 2016-08-24T06:48:35Z | [
"python",
"sockets",
"centos",
"udp"
] |
ExternalError: TypeError: Cannot read property 'innerHTML' of null with Skulpt runit() function | 38,866,526 | <p>I am getting an:</p>
<pre><code>ExternalError: TypeError: Cannot read property 'innerHTML' of null on line 2
</code></pre>
<p>in the console log from this code...</p>
<pre><code><!DOCTYPE html>
<html>
<head>
<link href='https://fonts.googleapis.com/css?family=Raleway' rel='stylesheet' type='text/css'>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jquery/1.12.0/jquery.js"></script>
<script src="http://www.skulpt.org/static/skulpt.min.js" type="text/javascript"></script>
<script src="http://www.skulpt.org/static/skulpt-stdlib.js" type="text/javascript"></script>
<title>Python Coding Area</title>
<script type='text/javascript'>
function outf(text) {
var mypre = document.getElementById("output");
mypre.innerHTML = mypre.innerHTML + text;
}
function builtinRead(x) {
if (Sk.builtinFiles === undefined || Sk.builtinFiles["files"][x] === undefined)
throw "File not found: '" + x + "'";
return Sk.builtinFiles["files"][x];
}
function runit() {
var prog = document.getElementById("textbox").value;
var mypre = document.getElementById("dynamicframe");
mypre.innerHTML = '';
Sk.pre = "output";
Sk.configure({output:outf, read:builtinRead});
(Sk.TurtleGraphics || (Sk.TurtleGraphics = {})).target = 'canvas';
var myPromise = Sk.misceval.asyncToPromise(function() {
return Sk.importMainWithBody("<stdin>", false, prog, true);
});
myPromise.then(function(mod) {
console.log('success');
},
function(err) {
console.log(err.toString());
});
}
</script>
</head>
<body style="font-family:Raleway !important;">
<textarea id="textbox" cols="50" rows="10"></textarea><br />
<button type="button" onclick="runit()">Run</button>
</form>
<pre id="dynamicframe" ></pre>
<div id="canvas"></div>
</body>
</html>
</code></pre>
<p>when I click the run button to run the python code with skulpt. Is there a problem with using skulpt in this context? I took some of the code from the skulpt website (skulpt.org) and changed it around a bit. Why am I getting the error and how can I stop it?</p>
| 0 | 2016-08-10T07:12:15Z | 38,866,756 | <p>The 'mypre' element does not exist in your webpage.</p>
<pre><code>You should add a condition like this:
var mypre = document.getElementById("output");
if( mypre ) != null){
mypre.innerHTML = mypre.innerHTML + text; }
</code></pre>
| 1 | 2016-08-10T07:24:12Z | [
"javascript",
"jquery",
"python",
"html",
"skulpt"
] |
Convert Hexadecimal string to long python | 38,866,552 | <p>I want to get the value of 99997 in big endian which is (2642804992) and then return the answer as a long value</p>
<p>here is my code in python:</p>
<pre><code>v = 99997
ttm = pack('>i', v) # change the integer to big endian form
print ("%x"), {ttm}
r = long(ttm, 16) # convert to long (ERROR)
return r
</code></pre>
<blockquote>
<p>Output: <strong>%x set(['\x00\x01\x86\x9d'])</strong></p>
<p>Error: <strong>invalid literal for long() with base 16: '\x00\x01\x86\x9d'</strong></p>
</blockquote>
<p>As the string is already in hex form why isn't it converting to a long? How would I remove this error and what is the solution to this problem. </p>
| 1 | 2016-08-10T07:13:58Z | 38,866,710 | <p>You just converted the integer value to big endian binary bytes.</p>
<p>This is useful mostly to embed in messages addressed to big-endian machines (PowerPC, M68K,...)</p>
<p>Converting to <code>long</code> like this means parsing the <code>ttm</code> string which should be <code>0x1869D</code> as ASCII.
(and the print statement does not work either BTW)</p>
<p>If I just follow your question title: "Convert hexadecimal string to long":</p>
<p>just use <code>long("0x1869D",16)</code>. No need to serialize it.
(BTW <code>long</code> only works in python 2. In python 3, you would have to use <code>int</code> since all numbers are represented in the <code>long</code> form)</p>
<p>Well, I'm answering to explain why it's bound to fail, but I'll edit my answer when I really know what you want to do.</p>
| 0 | 2016-08-10T07:22:06Z | [
"python",
"struct",
"hex",
"long-integer",
"big-endian"
] |
Convert Hexadecimal string to long python | 38,866,552 | <p>I want to get the value of 99997 in big endian which is (2642804992) and then return the answer as a long value</p>
<p>here is my code in python:</p>
<pre><code>v = 99997
ttm = pack('>i', v) # change the integer to big endian form
print ("%x"), {ttm}
r = long(ttm, 16) # convert to long (ERROR)
return r
</code></pre>
<blockquote>
<p>Output: <strong>%x set(['\x00\x01\x86\x9d'])</strong></p>
<p>Error: <strong>invalid literal for long() with base 16: '\x00\x01\x86\x9d'</strong></p>
</blockquote>
<p>As the string is already in hex form why isn't it converting to a long? How would I remove this error and what is the solution to this problem. </p>
| 1 | 2016-08-10T07:13:58Z | 38,866,733 | <p><strong>pack</strong> will return a string representation of the data you provide.</p>
<p>The string representation is different than a <strong>base 16</strong> of a long number. Notice the <strong>\x</strong> before each number.</p>
<p>Edit:</p>
<p>try this</p>
<pre><code>ttm = pack('>I',v)
final, = unpack('<I',ttm)
print ttm
</code></pre>
<p>Notice the use of <strong>I</strong>, this so the number is treated as an unsigned value</p>
| 1 | 2016-08-10T07:23:03Z | [
"python",
"struct",
"hex",
"long-integer",
"big-endian"
] |
Convert Hexadecimal string to long python | 38,866,552 | <p>I want to get the value of 99997 in big endian which is (2642804992) and then return the answer as a long value</p>
<p>here is my code in python:</p>
<pre><code>v = 99997
ttm = pack('>i', v) # change the integer to big endian form
print ("%x"), {ttm}
r = long(ttm, 16) # convert to long (ERROR)
return r
</code></pre>
<blockquote>
<p>Output: <strong>%x set(['\x00\x01\x86\x9d'])</strong></p>
<p>Error: <strong>invalid literal for long() with base 16: '\x00\x01\x86\x9d'</strong></p>
</blockquote>
<p>As the string is already in hex form why isn't it converting to a long? How would I remove this error and what is the solution to this problem. </p>
| 1 | 2016-08-10T07:13:58Z | 38,866,774 | <p>You have to use <code>struct.unpack</code> as a reverse operation to <code>struct.pack</code>.</p>
<pre><code>r, = unpack('<i', ttm)
</code></pre>
<p>this will <code>r</code> set to <code>-1652162304</code>.</p>
| 1 | 2016-08-10T07:25:11Z | [
"python",
"struct",
"hex",
"long-integer",
"big-endian"
] |
Convert Hexadecimal string to long python | 38,866,552 | <p>I want to get the value of 99997 in big endian which is (2642804992) and then return the answer as a long value</p>
<p>here is my code in python:</p>
<pre><code>v = 99997
ttm = pack('>i', v) # change the integer to big endian form
print ("%x"), {ttm}
r = long(ttm, 16) # convert to long (ERROR)
return r
</code></pre>
<blockquote>
<p>Output: <strong>%x set(['\x00\x01\x86\x9d'])</strong></p>
<p>Error: <strong>invalid literal for long() with base 16: '\x00\x01\x86\x9d'</strong></p>
</blockquote>
<p>As the string is already in hex form why isn't it converting to a long? How would I remove this error and what is the solution to this problem. </p>
| 1 | 2016-08-10T07:13:58Z | 38,866,928 | <p>This is a nice question.</p>
<p>Here is what you are looking for.</p>
<pre><code>s = str(ttm)
for ch in r"\bx'":
s = s.replace(ch, '')
print(int(s, 16))
</code></pre>
<p>The problem is that <code>ttm</code> is similar to a string in some aspects. This is what is looks like: <code>b'\x00\x01\x86\x9d'</code>. Supplying it to <code>int</code> (or <code>long</code>) keeps all the non-hex characters. I removed them and then it worked. </p>
<p>After removing the non-hex-digit chars, you are left with <code>0001869d</code> which is indeed <code>99997</code></p>
<p><strong>Comment</strong> I tried it on Python 3. But on Python 2 it will be almost the same, you won't have the <code>b</code> attached to the string, but otherwise it's the same thing.</p>
| 0 | 2016-08-10T07:32:13Z | [
"python",
"struct",
"hex",
"long-integer",
"big-endian"
] |
Correct way to save an image in admin and showing it in a template in Django | 38,866,687 | <p>I am using MySql and Django. I need to select the image route stored in the database, I can't use the <code>url</code> property of an ImageField, It must be the route stored in the database.</p>
<p>First of all, this is my configuration in settings:</p>
<pre><code>BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
PROJECT_ROOT = os.path.realpath(os.path.dirname(__file__))
MEDIA_ROOT = PROJECT_ROOT + '/archivos/'
MEDIA_URL = '/archivos/'
</code></pre>
<p>My first try on the model was this:</p>
<pre><code>foto = models.ImageField(upload_to = settings.MEDIA_ROOT)
</code></pre>
<p>And the URL saved on the database was this:</p>
<pre><code>/home/developer/project/mysystem/archivos/hombre.png
</code></pre>
<p>Later I tried this on the model:</p>
<pre><code>foto = models.ImageField(upload_to = '')
</code></pre>
<p>And the new URL is this:</p>
<pre><code>./pantalonazul_pXNLcuF.jpg
</code></pre>
<p>In both cases the image is uploaded to the <code>MEDIA_ROOT</code> folder, but when I try to use the URL saved on the database, the image doesn't shows. I am changing the <code>src</code> with jquery, I thougth that was the problem, but no, because I putted by hand both URL's in an image, and none of them worked. Also tried this: <code>../../archivos/pantalonazul_pXNLcuF.jpg</code> but produced the same bad results.</p>
<p>When I enter to the admin, it shows this:
<a href="http://i.stack.imgur.com/zzjZd.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/zzjZd.jpg" alt="Image in admin"></a></p>
<p>And if I click on that link I get this URL on Address bar:</p>
<pre><code>http://127.0.0.1:8000/archivos/pantalonazul_pXNLcuF.jpg
</code></pre>
<p>I also tried to use that URL in the image, written by hand on the <code>src</code> property, but didn't worked.</p>
<p>As an extra, when I click on the link to get that last URL, I have an error that says that the URL is not registered on the urls.py file, shows me a list of my URL's and at the end says this:</p>
<pre><code>The current URL, archivos/pantalonazul_pXNLcuF.jpg, didn't match any of these.
</code></pre>
<p>What I'm doing wrong? Why I cant get the image? Is something in the settings or where?</p>
<p>P.S.: The folder where I save the images is outside my app folder, is on the "general" folder, or I don't know how to call it, is in the same folder where settings.py is located, the folders are something like this:</p>
<pre><code>-MyAppFolder
-MySystem
-archivos
-image1.jpg
-image2.jpg
-settings.py
-urls.py
-wsgi.py
</code></pre>
| 0 | 2016-08-10T07:20:55Z | 38,884,633 | <p>I have found a partial solution, reading this <a href="https://docs.djangoproject.com/en/1.8/ref/settings/#media-url" rel="nofollow">Settings Media URL</a> and after it redirected me to this <a href="https://docs.djangoproject.com/en/1.8/howto/static-files/#serving-files-uploaded-by-a-user-during-development" rel="nofollow">Servinge files during development</a>. </p>
<p>I'm using the last model, the one with the empty <code>uploaded_to</code> and just added the line that the docs recommend on the second link to the <code>urls.py</code> file, and also call the image on this way: <code>../../archivos/image.jpg</code> but it says that the <code>urls.py</code> solution only works for development, not for serving it as a web page/application, so, someone knows how to make it work in a real server? without using <code>DEBUG=true</code> on settings?</p>
| 0 | 2016-08-10T22:34:45Z | [
"python",
"mysql",
"django"
] |
How to set the background color of part of the text in QTreeWidgetItem? | 38,866,696 | <p>For example, the text of QTreeWidgetItem is ["Hello world"], is there any way to set the background color of 'Hello'? The method <code>setBackground</code> seems to set the whole column.</p>
| 0 | 2016-08-10T07:21:09Z | 38,867,415 | <p>Set a custom Widget as default view of your QTreeWidgetItem, its easy with QLabel. This is an example with a QListWidget and QListWidgetItem: </p>
<pre><code>QListWidgetItem* MainWindow::addColoredItem(const QString& name, const QColor& backcolor, const QColor& textcolor) {
QListWidgetItem* item = new QTreeWidgetItem(this);
QLabel* label = new QLabel(this);
label->setStyleSheet(QString("QLabel{background: %1; color %2;}").arg(backColor.name(), textColor.name()));
ui->listWidget->addItem(item);
ui->listWidget->setItemWidget(item, widget);
return item;
}
</code></pre>
<p>For QTreeWidgetItem, make the same steps.</p>
| 0 | 2016-08-10T07:57:03Z | [
"python",
"qt",
"qtreewidgetitem"
] |
GridSearchCV not working? | 38,866,705 | <p>I am trying to use grid search to figure out the best value for n_components to use in PCA:</p>
<pre><code>from sklearn.decomposition import PCA
from sklearn.grid_search import GridSearchCV
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LinearRegression
pca = PCA()
pipe_lr = Pipeline([('pca', pca),
('regr', LinearRegression())])
param_grid = [{'pca__n_components': range(2, X.shape[1])}]
gs = GridSearchCV(estimator=pipe_lr,
param_grid=param_grid,
cv=3)
gs = gs.fit(X_train, y_train)
print(gs.best_score_)
print(gs.best_params_)
for i in range(2, X.shape[1]):
pca.n_components = i
pipe_lr = pipe_lr.fit(X_train, y_train)
print i, pipe_lr.score(X_test, y_test)
</code></pre>
<p>However, the results I am seeing are very weird (the numbers I get from the for loop are completely different from the ones from the grid search):</p>
<pre><code>-0.232877626581
{'pca__n_components': 2}
2 0.0989156092429
3 0.258170750388
4 0.26328990417
5 0.263620889601
6 0.315725901097
7 0.315477694958
8 0.330445632512
9 0.328779889242
10 0.323594949214
11 0.322914495543
12 0.324050681182
13 0.334970652728
14 0.334333880177
15 0.335040376094
16 0.330876375034
17 0.335395590901
18 0.335132468578
19 0.331201691511
20 0.337244411372
21 0.337130708041
22 0.333092723232
23 0.340707011134
24 0.344046515328
25 0.337869318771
26 0.332590709621
27 0.345343677247
28 0.344728264973
29 0.343084912122
30 0.340332251028
31 0.34012312844
32 0.340290453979
33 0.340349696151
34 0.337021304382
35 0.327271480372
36 0.334423097757
37 -5.09330041094e+21
38 -5.06403949113e+21
</code></pre>
<p>According to the for loop, the best value for n_components should be around 28, but this is not even close to what I get from grid search</p>
<p>Note: I did not include the steps for setting up the train and test sets, but i used <code>train_test_split</code> from sklearn.</p>
| 0 | 2016-08-10T07:21:55Z | 38,879,833 | <p><code>GridSearchCV</code>, spits out a <strong>cross_validation</strong> score. Adding a <code>cross_validation</code> to your for loop may give you a closer result. </p>
<p>Besides you are using different data. You have mentioned that you used <code>train_test_split</code>. In your for loop, you got the scores on X_test, y_test. In <code>GridSearchCV</code> you got a mean score on X_train, y_train. You might have outliers in your test set. </p>
<p>I slightly modified your code and applied it to the Boston data set.</p>
<pre><code>from sklearn.decomposition import PCA
from sklearn.grid_search import GridSearchCV
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LinearRegression
from sklearn.datasets import load_boston
import numpy as np
from sklearn.cross_validation import cross_val_score
boston = load_boston()
X = boston.data
y = boston.target
pca = PCA()
pipe_lr = Pipeline([('pca', pca),
('regr', LinearRegression())])
param_grid = {'pca__n_components': np.arange(2, X.shape[1])}
gs = GridSearchCV(estimator=pipe_lr,
param_grid=param_grid,
cv=3)
gs = gs.fit(X, y)
print(gs.best_score_)
print(gs.best_params_)
all_scores = []
for i in range(2, X.shape[1]):
pca.n_components = i
scores = cross_val_score(pipe_lr,X,y,cv=3)
all_scores.append(np.mean(scores))
print(i,np.mean(scores))
print('Best result:',all_scores.index(max(all_scores)),max(all_scores))
</code></pre>
<p>gives:</p>
<pre><code>0.35544286032
{'pca__n_components': 9}
2 -0.419093097857
3 -0.192078129541
4 -0.24988282122
5 -0.0909566048894
6 0.197185975618
7 0.173454370084
8 0.276509863992
9 0.355148081819
10 -17.2280089182
11 -0.291804450954
12 -0.281263153468
Best result: 7 0.355148081819
</code></pre>
| 2 | 2016-08-10T17:22:38Z | [
"python",
"machine-learning",
"scikit-learn"
] |
filename.whl is not a supported wheel on this platform | 38,866,758 | <p>I saw the same question but it didn't work for me.</p>
<pre><code>pip install PyOpenGL.3.1.1-cp34-cp34m-win_amd64.whl
</code></pre>
<p>also I have the same problem for Numpy</p>
<pre><code>pip install numpy-1.11.1+mkl-cp34-cp34m-win_amd64.whl
</code></pre>
<p>Then I get: </p>
<blockquote>
<p>numpy-1.11.1+mkl-cp34-cp34m-win_amd64.whl is not a supported wheel on
this platform. Storing debug log for failure in
C://Users/myUsername/pip/pip.log</p>
</blockquote>
<p>I'm using 64-bit and Python 3.4.0</p>
<p>What is wrong?</p>
| 0 | 2016-08-10T07:24:14Z | 39,883,753 | <p>You'll probably have to rename your whl file like this <code>numpy-1.11.1+mkl-cp34-none-win_amd64.whl</code> before installing. Your <code>pip</code> has a finite number of tags it recognizes in wheel filenames.</p>
<p>See this answer for more on this: <a href="http://stackoverflow.com/a/28111899/4401501">http://stackoverflow.com/a/28111899/4401501</a></p>
| 0 | 2016-10-05T21:12:41Z | [
"python",
"numpy",
"module",
"pip",
"pyopengl"
] |
Filter column by value inside and get index | 38,866,792 | <p>I would like to get an other dataframe fill with columns which have value greater or equal to <code>1</code>.</p>
<pre><code>df = pd.DataFrame({'A': '0 1 0 0 1 2'.split(),
'B': '0.1 0.2 0 0.5 0 0.1'.split(),'C':'0.1 0.2 0 0.5 0 0.1'.split()})
A B C
0 0 0.1 0.1
1 1 0.2 0.2
2 0 0 0
3 0 0.5 0.5
4 1 0 0
5 2 0.1 0.1
</code></pre>
<p>For instance, I would to get <code>df2</code> like this:</p>
<pre><code>df2 = pd.DataFrame({'A': '0 1 0 0 1 2'.split()})
</code></pre>
<p>If I try df2=df2[df2.values.astype(float) >= 1] I keep my three columns</p>
| 3 | 2016-08-10T07:26:03Z | 38,866,922 | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.ge.html" rel="nofollow"><code>ge</code></a> what means get values <code>greater</code> or <code>equal</code>, then filter by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.any.html" rel="nofollow"><code>any</code></a> at least one <code>True</code> and last <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow"><code>boolean indexing</code></a> by columns with <code>ix</code>:</p>
<pre><code>print (df.astype(float).ge(1, axis=1))
A B C
0 False False False
1 True False False
2 False False False
3 False False False
4 True False False
5 True False False
print (df.astype(float).ge(1, axis=1).any())
A True
B False
C False
dtype: bool
#sample data are strings, so first cast to float
df2 = df.ix[:, df.astype(float).ge(1, axis=1).any()]
print (df2)
A
0 0
1 1
2 0
3 0
4 1
5 2
</code></pre>
<p>It also works with:</p>
<pre><code>df2 = df.ix[:, (df.astype(float) >= 1).any()]
print (df2)
A
0 0
1 1
2 0
3 0
4 1
5 2
</code></pre>
| 3 | 2016-08-10T07:32:01Z | [
"python",
"pandas",
"dataframe",
"filter",
"multiple-columns"
] |
Filter column by value inside and get index | 38,866,792 | <p>I would like to get an other dataframe fill with columns which have value greater or equal to <code>1</code>.</p>
<pre><code>df = pd.DataFrame({'A': '0 1 0 0 1 2'.split(),
'B': '0.1 0.2 0 0.5 0 0.1'.split(),'C':'0.1 0.2 0 0.5 0 0.1'.split()})
A B C
0 0 0.1 0.1
1 1 0.2 0.2
2 0 0 0
3 0 0.5 0.5
4 1 0 0
5 2 0.1 0.1
</code></pre>
<p>For instance, I would to get <code>df2</code> like this:</p>
<pre><code>df2 = pd.DataFrame({'A': '0 1 0 0 1 2'.split()})
</code></pre>
<p>If I try df2=df2[df2.values.astype(float) >= 1] I keep my three columns</p>
| 3 | 2016-08-10T07:26:03Z | 38,867,200 | <p>I create a boolean mask where at least some value in a column is >= 1. Then I use this mask on both the data and the columns to produce a new dataframe.</p>
<p>I utilize numpy for the masking.</p>
<pre><code># convert to floats and define mask
v = df.values.astype(float)
mask = (v >= 1).any(0)
# assign new dataframe with masked data and masked columns
# just incase there where multiple columns that satisfied.
df2 = pd.DataFrame(v.T[mask].T, columns=df.columns[mask])
df2
</code></pre>
<p><a href="http://i.stack.imgur.com/xl5Dw.png" rel="nofollow"><img src="http://i.stack.imgur.com/xl5Dw.png" alt="enter image description here"></a></p>
<hr>
<h3>Timing</h3>
<p><a href="http://i.stack.imgur.com/MqbU7.png" rel="nofollow"><img src="http://i.stack.imgur.com/MqbU7.png" alt="enter image description here"></a></p>
<p><strong><em>df 1000 times as long</em></strong></p>
<pre><code>df = pd.concat([df.T for _ in range(1000)], ignore_index=True).T
</code></pre>
<p><a href="http://i.stack.imgur.com/XsTyj.png" rel="nofollow"><img src="http://i.stack.imgur.com/XsTyj.png" alt="enter image description here"></a></p>
| 3 | 2016-08-10T07:46:23Z | [
"python",
"pandas",
"dataframe",
"filter",
"multiple-columns"
] |
python - Return value in different functions | 38,866,886 | <p>I am working on a Roomba robot (cleaning robot) and I have to print each time the robot bumps into something. I also have to take pictures every 10 seconds thanks to the Picamera. I would like to be able to print that a bump happens between pictures n and pictures n+1.
When a picture is taken, I increment the number of pictures taken and the same when a bump happens (increment the number of bumps).
For example, if bump 1 appears between pictures number 1 and 2, my code will print "Bump 1 between pictures 1 and picture 2".
The problem is that if picture 2 is taken, my code will print "Bump 1 between picture 2 and picture 3". But it is false, Bump 1 is still between picture 1 and picture 2.
I can't find a solution to be able to stay between the same pictures even if a another one has been taken.</p>
<pre><code>count = 0
PicturesNumber = 0
def takePictures():
global PicturesNumber
for i in range(10):
sleep(5)
PicturesNumber += 1
print(("Picture %i taken" % (i + 1,)))
camera.capture(('/home/pi/Project/image%s.jpg') % (i,))
camera.close()
return PicturesNumber
def reactSensors():
global count
threading.Timer(1, reactSensors).start()
array = r.getSensor('BUMPS_AND_WHEEL_DROPS') # get information from the roomba sensors
if array[3] == 1 or array[4] == 1:
count += 1
#print(("Bump %i" % (count,)))
return count
def displayBumpings():
threading.Timer(1, displayBumpings).start()
print(("Bump %i between picture %i and picture %i\n" (count + 1, PicturesNumber, PicturesNumber + 1,)))
if __name__ == '__main__':
r = create.Create(SERIAL_PORT)
settime = time.time()
resp = input("Ready to roll? ")
if resp[0] != 'y':
r.shutdown()
if resp[0] == 'y':
print("Let's go\n")
# I am using threading to run each function at the same time
Thread(target=reactSensors).start()
Thread(target=takePictures).start()
Thread(target=displayBumpings).start()
</code></pre>
<p>I know that there is a problem with the DisplayBumpings print line because PicturesNumber updates is value each time a picture is taken.</p>
<p>This is what I get in the shell</p>
<pre><code>Picture 1 taken
Bump 1 between picture 1 and picture 2
Picture 2 taken
Bump 1 between picture 2 and picture 3
</code></pre>
<p>Thank you very much for any answer !</p>
| 0 | 2016-08-10T07:30:11Z | 38,867,000 | <p>Add a variable that is only updated when count is?
What I mean is, in reactSensor(): </p>
<pre><code>reactSensor():
...
if array[3] == 1 or array[4] == 1:
count +=1
newvariable = PicturesNumber
global newvariable
def displayBumpings():
threading.Timer(1, displayBumpings).start()
print(("Bump %i between picture %i and picture %i\n" (count + 1,newvariable, newvariable+ 1,)))
</code></pre>
<p>and then you use newvariable when bumping.</p>
| 0 | 2016-08-10T07:35:57Z | [
"python",
"count"
] |
import another program as module | 38,866,980 | <p>i searched my problem on stack and i didt find the solution so i come here to asking u about that .im learnin python with the book 'OReilly.Introducing.Python' and in chapter 5 in module section .the author says u can save a program and use in in another program as module when the 2 programs are saved in 1 directory. this is the fist program using as module.
report.py</p>
<pre><code>def get_description(): # see the docstring below?
"""Return random weather, just like the pros"""
from random import choice
possibilities = ['rain', 'snow', 'sleet', 'fog', 'sun', 'who knows']
return choice(possibilities)
</code></pre>
<p>and the main program is this :</p>
<pre><code>import report
description = report.get_description()
print("Today's weather:", description)
</code></pre>
<p>its a simple program i know when i want to import that it apears with this error:</p>
<p>Traceback (most recent call last):
File "H:\python\Lib\weather.py", line 1, in
import report
File "H:\python\Lib\report.py", line 2
"""Return random weather, just like the pros"""
^
IndentationError: expected an indented block</p>
<p>i tried to change directory and copy that to lib folder or scripts and this is my sys.path:
H:\python\Lib
C:\Windows\System32
H:\python\Lib\idlelib
H:\python\python35.zip
H:\python\DLLs
H:\python\lib
H:\python
H:\python\lib\site-packages</p>
| 0 | 2016-08-10T07:34:49Z | 38,867,024 | <p>Just as the error says, you must ident the docstring:</p>
<pre><code>def get_description(): # see the docstring below?
"""Return random weather, just like the pros"""
from random import choice
possibilities = ['rain', 'snow', 'sleet', 'fog', 'sun', 'who knows']
return choice(possibilities)
</code></pre>
| 0 | 2016-08-10T07:37:07Z | [
"python"
] |
how to search for string inside chrome internal pages, using python and\or selenium | 38,867,008 | <p>I'm trying to write script, that would allow me to search for a string inside Chrome's internal pages (for example: "chrome://help").<br>
is there a simple way to do it, or does it require special tools, (like the Selenium webdriver API)?<br>
i know it's possible to use it for "normal" web pages, but what about "internal" ones?</p>
| 0 | 2016-08-10T07:36:12Z | 38,868,139 | <p>You can use selenium Webdriver to easily achieve this task, and in this case we will extract the version number of Google Chrome.</p>
<p>Here is the sample code with comments explaining every step:</p>
<pre><code>from selenium import webdriver
# executable path should be the place where chrome driver is on the computer
driver = webdriver.Chrome(executable_path= '/users/user/Downloads/Chromedriver')
# This line tells the driver to go to the help section of chrome
driver.get('chrome://help')
# Because certain elements are stored in another Iframe, you must switch to this particular Iframe which is called 'help' in this case.
driver.switch_to.frame(driver.find_element_by_name('help'))
# retrive the text of the element and store it's text in a variable.
version_string = driver.find_element_by_id('version-container').text
# Now you can easily print it.
print version_string
</code></pre>
| 1 | 2016-08-10T08:34:02Z | [
"python",
"google-chrome",
"selenium-webdriver"
] |
How to find neighbors in binary image with given horizontal and vertical distance (Python) | 38,867,092 | <p>I have an Image (or several hundreds of them) that need to be analyzed. The goal is to find all black spots close to each other.</p>
<p>For example all black spots with a Horizontal distance of 160 pixel and vertical 40 pixel.</p>
<p><a href="http://i.stack.imgur.com/hyKGh.png" rel="nofollow"><img src="http://i.stack.imgur.com/hyKGh.png" alt="Just a small part of an image"></a></p>
<p>For now I just look at each Pixel and if there is a black pixel I call a recursive Method to find its neighbours (i can post the code too if you want to)</p>
<p>It works, but its very slow. At the moment the script runs about 3-4 minutes depending on image size.</p>
<p>Is there some easy/fast way to accomplish this (best would be a scikit-image method to help out here) I'm using Python.</p>
<p>edit: I tried to use <code>scikit.measure.find_contours</code>, now i have an array with arrays containing the contours of the black spots. Now I only need to find the contours in the neighbourhood of these contours.</p>
| 2 | 2016-08-10T07:40:08Z | 38,871,169 | <p><em>Disclaimer</em>: I'm not proficient with the scikit image library at all, but I've tackled similar problems using MATLAB so I've searched for the equivalent methods in scikit, and I hope my findings below help you.</p>
<p>First you can use <a href="http://scikit-image.org/docs/dev/api/skimage.measure.html#skimage.measure.label" rel="nofollow">skimage.measure.label</a> which returns <code>label_image</code>, i.e. an image where all connected regions are labelled with the same number. I believe you should call this function with <code>background=255</code> because from your description it seems that the background in your images is the while region (hence the value 255).</p>
<p>This is essentially an image where the <code>background</code> pixels are assigned the value <code>0</code> and the pixels that make up each (connected) spot are assigned the value of an integer label, so all the pixels of one spot will be labelled with the value <code>1</code>, the pixels of another spot will be labelled with the value <code>2</code>, and so on. Below I'll refer to "spots" and "labelled regions" interchangeably.</p>
<p>You can then call <a href="http://scikit-image.org/docs/dev/api/skimage.measure.html#skimage.measure.regionprops" rel="nofollow">skimage.measure.regionprops</a>, that takes as input the <code>label_image</code> obtained in the previous step. This function returns a list of <code>RegionProperties</code> (one for each labelled region), which is a summary of properties of a labelled region.</p>
<p>Depending on your definition of</p>
<blockquote>
<p>The goal is to find all black spots close to each other.</p>
</blockquote>
<p>there are different fields of the <code>RegionProperties</code> that you can use to help solve your problem:</p>
<ul>
<li><code>bbox</code> gives you the set of coordinates of the bounding box that contains that labelled region,</li>
<li><code>centroid</code> gives you the coordinates of the centroid pixel of that labelled region,</li>
<li><code>local_centroid</code> gives you the centroid relative to the bounding box <code>bbox</code></li>
</ul>
<p>(Note there are also <code>area</code> and <code>bbox_area</code> properties which you can use to decide whether to throw away very small spots that you might not be interested in, thus reducing computation time when it comes to comparing proximity of each pair of spots)</p>
<p>If you're looking for a coarse comparison, then comparing the <code>centroid</code> or <code>local_centroid</code> between each pair of labelled regions might be enough.</p>
<p>Otherwise you can use the <code>bbox</code> coordinates to measure the exact distance between the outer bounds of any two regions.</p>
<p>If you want to base the decision on the <em>precise</em> distance between the pixel(s) of each pair of regions that are closest to each other, then you'll likely have to use the <code>coords</code> property.</p>
| 1 | 2016-08-10T10:43:40Z | [
"python",
"scikit-image",
"neighbours"
] |
How to find neighbors in binary image with given horizontal and vertical distance (Python) | 38,867,092 | <p>I have an Image (or several hundreds of them) that need to be analyzed. The goal is to find all black spots close to each other.</p>
<p>For example all black spots with a Horizontal distance of 160 pixel and vertical 40 pixel.</p>
<p><a href="http://i.stack.imgur.com/hyKGh.png" rel="nofollow"><img src="http://i.stack.imgur.com/hyKGh.png" alt="Just a small part of an image"></a></p>
<p>For now I just look at each Pixel and if there is a black pixel I call a recursive Method to find its neighbours (i can post the code too if you want to)</p>
<p>It works, but its very slow. At the moment the script runs about 3-4 minutes depending on image size.</p>
<p>Is there some easy/fast way to accomplish this (best would be a scikit-image method to help out here) I'm using Python.</p>
<p>edit: I tried to use <code>scikit.measure.find_contours</code>, now i have an array with arrays containing the contours of the black spots. Now I only need to find the contours in the neighbourhood of these contours.</p>
| 2 | 2016-08-10T07:40:08Z | 38,876,149 | <p>When you get the coordinates of the different black spots, rather than computing all distances between all pairs of black pixels, you can use a cKDTree (in scipy.spatial, <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.cKDTree.html#scipy.spatial.cKDTree" rel="nofollow">http://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.cKDTree.html#scipy.spatial.cKDTree</a>). The exact method of cKDTree to use depends on your exact criterion (you can for example use cKDTree.query_ball_tree to know whether there exists a pair of points belonging to two different labels, with a maximal distance that you give).</p>
<p>KDTrees are a great method to reduce the complexity of problems based on neighboring points. If you want to use KDTrees, you'll need to rescale the coordinates so that you can use one of the classical norms to compute the distance between points.</p>
| 2 | 2016-08-10T14:23:52Z | [
"python",
"scikit-image",
"neighbours"
] |
How to find neighbors in binary image with given horizontal and vertical distance (Python) | 38,867,092 | <p>I have an Image (or several hundreds of them) that need to be analyzed. The goal is to find all black spots close to each other.</p>
<p>For example all black spots with a Horizontal distance of 160 pixel and vertical 40 pixel.</p>
<p><a href="http://i.stack.imgur.com/hyKGh.png" rel="nofollow"><img src="http://i.stack.imgur.com/hyKGh.png" alt="Just a small part of an image"></a></p>
<p>For now I just look at each Pixel and if there is a black pixel I call a recursive Method to find its neighbours (i can post the code too if you want to)</p>
<p>It works, but its very slow. At the moment the script runs about 3-4 minutes depending on image size.</p>
<p>Is there some easy/fast way to accomplish this (best would be a scikit-image method to help out here) I'm using Python.</p>
<p>edit: I tried to use <code>scikit.measure.find_contours</code>, now i have an array with arrays containing the contours of the black spots. Now I only need to find the contours in the neighbourhood of these contours.</p>
| 2 | 2016-08-10T07:40:08Z | 38,890,177 | <p>If your input image is binary, you could separate your regions of interest as follows:</p>
<ol>
<li>"grow" all the regions by the expected distance (actually half of it, as you grow from "both sides of the gap") with <code>binary_dilation</code>, where the <code>structure</code> is a kernel (e.g. rectangular: <a href="http://scikit-image.org/docs/dev/api/skimage.morphology.html#skimage.morphology.rectangle" rel="nofollow">http://scikit-image.org/docs/dev/api/skimage.morphology.html#skimage.morphology.rectangle</a>) of, let's say, 20x80pixels;</li>
<li>use the resulting mask as an input to <code>skimage.measure.label</code> to assign different values for different regions' pixels;</li>
<li>multiply your input image by the mask created above to zero dilated pixels.</li>
</ol>
<p>Here are the results of proposed method on your image and <code>kernel = rectange(5,5)</code>:</p>
<p>Dilated binary image (output of step 1):</p>
<p><a href="http://i.stack.imgur.com/ZtQNf.png" rel="nofollow"><img src="http://i.stack.imgur.com/ZtQNf.png" alt="enter image description here"></a></p>
<p>Labeled version of the above (output of step 2):</p>
<p><a href="http://i.stack.imgur.com/DOnYV.png" rel="nofollow"><img src="http://i.stack.imgur.com/DOnYV.png" alt="enter image description here"></a></p>
<p>Multiplication results (output of step 3):</p>
<p><a href="http://i.stack.imgur.com/zpLnR.png" rel="nofollow"><img src="http://i.stack.imgur.com/zpLnR.png" alt="enter image description here"></a></p>
| 1 | 2016-08-11T07:39:46Z | [
"python",
"scikit-image",
"neighbours"
] |
Not able to switch between two subprocess | 38,867,149 | <p>I am trying to work with two subprocess.
I open the first one and send him something, then i open the second one and send him something. In both cases I send with stdin.write</p>
<pre><code>process1 = subprocess.Popen([path], stdin = subprocess.PIPE,)
process1.stdin.write('some string1')
process2 = subprocess.Popen([path], stdin = subprocess.PIPE,)
process2.stdin.write('some string 2')
</code></pre>
<p>But when i want to send again to process1 , I do the same thing but it doesn't do nothing.
How can I communicate with process 1 again?</p>
| 1 | 2016-08-10T07:44:10Z | 38,867,514 | <p>It should just work.</p>
<p>For example:</p>
<pre><code>$ cat 1.py
import subprocess
process1 = subprocess.Popen("cat > file1", shell=True, stdin=subprocess.PIPE)
process1.stdin.write('some string1\n')
process2 = subprocess.Popen("cat > file2", shell=True, stdin=subprocess.PIPE)
process2.stdin.write('some string 2\n')
process1.stdin.write('some string3\n')
</code></pre>
<p>Afther that running the program and checking the result:</p>
<pre><code>$ python 1.py
$ cat file1
some string1
some string3
$ cat file2
some string 2
</code></pre>
<p>So, as you can see, it just works.</p>
| 0 | 2016-08-10T08:03:03Z | [
"python",
"python-2.7",
"subprocess"
] |
Django.core.validators MinMaxValueValidator ignored from shell | 38,867,167 | <p>I'm using django 1.10, created </p>
<pre><code>from django.core.validators import MinValueValidator
from django.core.validators import MaxValueValidator
class B(models.Model):
address = models.PositiveSmallIntegerField(validators=[MinValueValidator(0), MaxValueValidator(63)], blank=True, null=True)
</code></pre>
<p>when I get in shell_plus and do:</p>
<pre><code>x=B()
x.address='1973'
x.save()
</code></pre>
<p>the row has been recorded. Triyng the same from admin web interface the form give an error, why the shell allow to save the record?</p>
| -2 | 2016-08-10T07:44:52Z | 38,867,392 | <p>This is correct.</p>
<p>From the <a href="https://docs.djangoproject.com/en/1.9/ref/validators/#how-validators-are-run" rel="nofollow">docs for How validators are run</a></p>
<blockquote>
<p>...Note that validators will not be run automatically when you save a model, but if you are using a ModelForm, it will run your validators on any fields that are included in your form....</p>
</blockquote>
| 1 | 2016-08-10T07:55:32Z | [
"python",
"django",
"custom-validators"
] |
Is there any way to know current url is in a specific blueprint in flask? | 38,867,248 | <p>in my flask app I can use a blueprint to register lots of routes..</p>
<pre><code>@myblueprint.route('/first')
@myblueprint.route('/two')
@myblueprint.route('/three')
</code></pre>
<p>my problem is that I need to know current url in in a specific blueprint.so I can give it a <code>class='active'</code> css effect in jinja template?
So is there any way I can do using flask 0.10.0?</p>
| 1 | 2016-08-10T07:48:39Z | 38,875,225 | <p><a href="http://flask.pocoo.org/docs/0.11/api/#flask.Request.blueprint" rel="nofollow"><code>request.blueprint</code></a> will be the current blueprint name if the request is being handled by a blueprint.</p>
| 1 | 2016-08-10T13:44:50Z | [
"python",
"url",
"flask",
"jinja2"
] |
How to retrieve wav file from API? | 38,867,272 | <p>I am working on Python3.4.4
I tried to use a Merriam-Webster API, and here is an example link:
<a href="http://www.dictionaryapi.com/api/v1/references/collegiate/xml/purple?key=bf534d02-bf4e-49bc-b43f-37f68a0bf4fd" rel="nofollow">http://www.dictionaryapi.com/api/v1/references/collegiate/xml/purple?key=bf534d02-bf4e-49bc-b43f-37f68a0bf4fd</a></p>
<p>There is a file under the tag, you will see after you open the url.</p>
<p>And I am wondering that how can I retrieve that wav file......</p>
<p>Because it is kind of just a string to me......</p>
<p>Thank you very much!</p>
| 0 | 2016-08-10T07:50:04Z | 38,868,684 | <p>Okay, I just sort it out.
Usually you need to look at the instructions for the API, I look it up on the official website and it tells you that how you are going to retrieve that. In this case you are going to another url, and then wala</p>
| 0 | 2016-08-10T09:00:22Z | [
"python",
"xml",
"api",
"audio",
"wav"
] |
'NoneType' object has no attribute 'sendall' PYTHON | 38,867,346 | <p>My current python script:</p>
<pre><code>import os
import ftplib
import hashlib
import glob
hashing = "123"
m = hashlib.md5()
m.update(hashing)
dd = m.hexdigest()
ftp = ftplib.FTP('localhost','kevin403','S$ip1234')
ftp.cwd('/var/www/html/image')
for image in glob.glob(os.path.join('Desktop/images/test*.png')):
with open(image, 'rb') as file:
ftp.storbinary('STOR '+dd+ '.png', file)
ftp.close()
ftp.quit()
</code></pre>
<p>Anybody know this error? I trying to send file over to another folder via ftp.</p>
<p>The error i got when running the script:</p>
<pre><code>Traceback (most recent call last):
File "/home/kevin403/wwq.py", line 21, in <module>
ftp.quit()
File "/usr/lib/python2.7/ftplib.py", line 591, in quit
resp = self.voidcmd('QUIT')
File "/usr/lib/python2.7/ftplib.py", line 253, in voidcmd
self.putcmd(cmd)
File "/usr/lib/python2.7/ftplib.py", line 181, in putcmd
self.putline(line)
File "/usr/lib/python2.7/ftplib.py", line 176, in putline
self.sock.sendall(line)
AttributeError: 'NoneType' object has no attribute 'sendall'
</code></pre>
| 2 | 2016-08-10T07:53:06Z | 38,867,653 | <blockquote>
<p><strong>FTP.quit()</strong>
Send a QUIT command to the server and close the connection. This is the âpoliteâ way to close a connection, but it may raise an exception if the server responds with an error to the QUIT command. This implies a call to the close() method which renders the FTP instance useless for subsequent calls (see below).</p>
<p><strong>FTP.close()</strong>
Close the connection unilaterally. This should not be applied to an already closed connection such as after a successful call to quit(). After this call the FTP instance should not be used any more (after a call to close() or quit() you cannot reopen the connection by issuing another login() method).</p>
</blockquote>
<p>Just erase <code>ftp.close()</code>, since <code>ftp.quit()</code> implies call <code>.close()</code> function you're telling to close two times, and then quit falls because socket was already closed.</p>
<p><a href="https://docs.python.org/2/library/ftplib.html" rel="nofollow">FTPlib Documentation</a></p>
| 1 | 2016-08-10T08:09:28Z | [
"python",
"python-2.7",
"ftp"
] |
Let telegram bot react while a document is sent to a group chat | 38,867,473 | <p>I want my bot to send a message when it detect documents is sent in a chat.<br>
I add a message handler with document filter.<br>
The code works for chat to the bot directly,<br>
but if I add the bot into a group,
the bot has no response if I sent a document in the group.</p>
<p>The code is:</p>
<pre class="lang-py prettyprint-override"><code>def test(bot, update):
bot.sendMessage(update.message.chat_id, text='OK!')
print "OK"
def main():
token = 'xxxxxxyyyyy'
updater = Updater(token, workers=10)
dp = updater.dispatcher
dp.add_handler(CommandHandler("start", start))
dp.add_handler(CommandHandler("help", help))
dp.add_handler(MessageHandler([Filters.document], test))
updater.start_polling(timeout=10)
updater.idle()
</code></pre>
<p>Why the bot has no response when I send a file in a group?
Thanks!</p>
| 1 | 2016-08-10T08:01:10Z | 38,876,257 | <p>If code is working in private chat but not working( not receiving messages sent) in a group , the reason is you do NOT set <code>/setprivacy</code> in <code>BotFather</code>.</p>
<blockquote>
<p>Go to <code>BotFather</code> and disable <code>/setprivacy</code> for your bot. In this
state, your bot will receive all messages not just does start with
slash(/) in GROUPS.</p>
</blockquote>
| 1 | 2016-08-10T14:28:29Z | [
"python",
"telegram",
"telegram-bot"
] |
Sequential task execution in Celery | 38,867,489 | <p>I have some "heavy" requests to the database that I'm going to execute using Celery. Taking into account that they are "heavy" I want to execute them sequentially (one by one). One possible solution is to specify <code>--concurrency=1</code> in the command line to Celery. And it works. But there is a problem: while the tasks are being executed all the following requests return <code>None</code>:</p>
<pre><code>from celery.task.control import inspect
# Inspect all nodes.
i = inspect()
print(i.scheduled()) # None
print(i.active()) # None
print(i.reserved()) # None
print(i.registered()) # None
</code></pre>
<p>Also, running <code>celery inspect ping</code> returns <code>Error: No nodes replied within time constraint.</code> So that I can't receive any information on the Celery queue state.</p>
<p>There are my test python modules:</p>
<p><strong>celeryconfig.py</strong></p>
<pre><code>#BROKER_URL = 'redis://localhost:6379/0'
BROKER_URL = 'amqp://'
#CELERY_RESULT_BACKEND = "redis"
CELERY_RESULT_BACKEND = "amqp://"
# for php
CELERY_TASK_RESULT_EXPIRES = None
CELERY_TASK_SERIALIZER = 'json'
CELERY_RESULT_SERIALIZER = 'json'
CELERY_ACKS_LATE = True
</code></pre>
<p><strong>tasks.py</strong></p>
<pre><code>from celery import Celery
from time import sleep
app = Celery('hello')
app.config_from_object('celeryconfig')
@app.task
def add(x, y):
sleep(30)
return x + y
</code></pre>
<p><strong>client.py</strong></p>
<pre><code>from tasks import add
result=add.delay(4, 4)
result=add.delay(4, 4)
result=add.delay(4, 4)
result=add.delay(4, 4)
result=add.delay(4, 4)
result=add.delay(4, 4)
</code></pre>
<p>So, the question is, how to run the tasks one by one AND be able to check the state of the queue?</p>
| 1 | 2016-08-10T08:01:49Z | 38,871,139 | <p>Celery's inspections are performed by broadcasting a query to anything that listens and then gathering the responses. Any worker that does not respond within the timeout (which I think is 1 second by default), is going to be ignored. It is as if it did not exist.</p>
<p>The fact that you use <code>--concurrency=1</code> should not be an issue. I've just tried it and it worked fine here. Even with a concurrency of 1, a Celery worker will normally have an extra thread of execution for communications. (I say "normally" because I'm sure there are ways to configure Celery to shoot itself in the foot. What I say holds with the defaults.) When I tried <code>--concurrency=1</code> there were actually <em>two threads per worker</em>. So even if the worker is busy computing a task, there should be a thread able to respond to the broadcast.</p>
<p>This being said, if the machine is under heavy load, then it may take too long for the worker to respond. The way I've worked around this is to retry calls like <code>i.scheduled()</code> until I get an answer from everyone. In my projects, I know how many workers should be up and running and so I have a list I can use to know whether everyone has responded.</p>
| 1 | 2016-08-10T10:42:00Z | [
"python",
"celery"
] |
Storing and using a trained neural network | 38,867,587 | <p>I am trying to develop a neural network to predict timeseries.</p>
<p>As far as I have understood, I am training my neural network with a training set and validate it with a test set.</p>
<p>When I am satisfied with my results, I can use my neural network to predict new values, and the neural network itself is basically just all the weights I have adjusted using my training sets.</p>
<p>Is this correct?</p>
<p>If so, I should only train my network once, and then just use my network (the weights) to predict future values. How do you normally avoid re-computing the entire network? Should I save all the weights in a database or something, so I can always access it without having to train it again?</p>
<p>If my understanding is correct, I can benefit from making the heavy computation on a dedicated computer (e.g. a supercomputer) and then just use my network on a webserver, an iPhone app or something like that, but I don't know how to store it.</p>
| 2 | 2016-08-10T08:06:20Z | 38,867,857 | <p>To make your Neural Network <em>persistent</em>, you can <a href="https://docs.python.org/2/library/pickle.html" rel="nofollow"><code>pickle</code></a> it. You would not need to recompute the weights of the <em>trained-pickled</em> network, and all you need do is unpickle the network and use it to make new predictions.</p>
<p>There are libraries like <a href="http://scikit-learn.org/stable/modules/model_persistence.html" rel="nofollow"><code>joblib</code></a> that can be used for more efficient <em>serialization/pickling</em>.</p>
<p>The question of whether to retrain a NN is not trivial. That depends on what exactly you're using the network for; say <a href="https://en.wikipedia.org/wiki/Reinforcement_learning#Algorithms_for_control_learning" rel="nofollow">Reinforcement learning</a> may require that you retrain with new beliefs. But in some cases, and probably in this, it may be sufficient to use a trained network once and always, or to retrain in a future where you have more field data.</p>
| 0 | 2016-08-10T08:20:09Z | [
"python",
"machine-learning",
"neural-network",
"recurrent-neural-network",
"heavy-computation"
] |
how can I make the celery task call back to flask when it is finished | 38,867,608 | <p>When integrating celery with a Flask app, i have a longtime task that needs to callback to flask when the task is finished</p>
<pre><code>@celery_app.task(bind=True)
def doSth(self):
rv = long_time_job()
return rv
@task_success.connect(sender=doSth)
def on_add_success(sender, result, **kwargs):
#tell flask that a task has been done
pass
</code></pre>
<p>but i have no idea</p>
| 1 | 2016-08-10T08:07:09Z | 38,867,829 | <p>A celery task is run indepently from the Flask server through a worker, they are two different process communicated with a message broker (rabbitmq?). So, when the task ends, that callback function should be done having the former in mind, two different process.</p>
<p>Here I give you two solutions:</p>
<ul>
<li>Webhook: define an HTTP URL in the Flask server and do a GET with the task id at the end of the task so Flask knows.</li>
<li>Database: use a thread-safe database and keep the status of the task there. Flask will never know the task is ended until it queries the database (i.e. polling), not realtime but still an option. </li>
</ul>
| 1 | 2016-08-10T08:18:45Z | [
"python",
"celery"
] |
How to create permission for specific rules in Django Rest Framework? | 38,867,688 | <p>I want to arrange permission like that each user can edit his own profile. Just super user can edit all profile. What I need to add <strong>permissions.py</strong> ? Thank you.</p>
<p><strong>views.py</strong></p>
<pre><code>class UserViewSet(mixins.ListModelMixin,
mixins.RetrieveModelMixin,
mixins.UpdateModelMixin,
mixins.DestroyModelMixin,
generics.GenericAPIView):
queryset = User.objects.all()
serializer_class = UserSerializer
permission_classes = [IsAuthenticated]
authentication_classes = (JSONWebTokenAuthentication, )
</code></pre>
<p><strong>permissions.py</strong></p>
<pre><code>class IsOwnerOrReadOnly(BasePermission):
message = '!!'
my_safe_method = ['GET', 'PUT']
def has_permission(self, request, view):
if request.method in self.my_safe_method:
return True
return False
def has_object_permission(self, request, view, obj):
# member .0 Membership.objects.get(user=request.user)
# member.is_active
if request.method in SAFE_METHODS:
return True
return obj.user == request.user
</code></pre>
| 0 | 2016-08-10T08:11:39Z | 38,873,561 | <p>Write your own permission</p>
<pre><code>class IsObjectOwner(BasePermission):
message = "You must be the owner of this object."
my_safe_methods = ['GET', 'PUT', 'PATCH', 'DELETE']
def has_permission(self, request, view):
if request.method in self.my_safe_methods:
return True
return False
def has_object_permission(self, request, view, obj):
if request.user.is_superuser:
return obj
else:
return obj == request.user
</code></pre>
<p>and then in the <code>view</code> add it in <code>permission_classes</code></p>
<pre><code>class UserDetailView(RetrieveUpdateDestroyAPIView):
permission_classes = [IsObjectOwner, permissions.IsAuthenticated]
</code></pre>
| 1 | 2016-08-10T12:32:57Z | [
"python",
"django",
"django-rest-framework"
] |
A faster discrete Laplacian than scipy.ndimage.filters.laplace for small arrays | 38,867,689 | <p>My spends the vast bulk of its computational time in <a href="http://docs.scipy.org/doc/scipy-0.16.0/reference/generated/scipy.ndimage.filters.laplace.html" rel="nofollow"><code>scipy.ndimage.filters.laplace()</code></a></p>
<p>The main advantage of <code>scipy</code> and <code>numpy</code> is vectorised calculation in <code>C/C++</code> wrapped in <code>python</code>.
<a href="http://docs.scipy.org/doc/scipy-0.16.0/reference/generated/scipy.ndimage.filters.laplace.html" rel="nofollow"><code>scipy.ndimage.filters.laplace()</code></a> is derived from <code>_nd_image.correlate1d</code> which is
part of the optimised library <a href="https://github.com/scipy/scipy/blob/v0.14.0/scipy/ndimage/src/nd_image.h" rel="nofollow"><code>nd_image.h
</code></a></p>
<p>Is there any faster method of doing this across an array of size <code>10-100</code>?</p>
<p><strong>Definition</strong> <em>Laplace Filter</em> - ignoring division</p>
<ul>
<li><code>a[i-1] - 2*a[i] + a[i+1]</code></li>
<li><em>Optional</em> Can ideally wrap around boundary <code>a[n-1] - 2*a[n-1] + a[0]</code> for <code>n=a.shape[0]</code></li>
</ul>
| 1 | 2016-08-10T08:11:43Z | 38,872,821 | <p>The problem was rooted in <code>scipy</code>'s excellent error handling and debugging. However, in the instance the user knows what they're doing it just provides excess overhead.</p>
<p>This code below strips all the <code>python</code> clutter in the back end of <code>scipy</code> and directly accesses the <code>C++</code> function to get a <code>~6x</code> speed up!</p>
<pre><code>laplace == Mine ? True
testing timings...
array size 10
100000 loops, best of 3: 12.7 µs per loop
100000 loops, best of 3: 2.3 µs per loop
array size 100
100000 loops, best of 3: 12.7 µs per loop
100000 loops, best of 3: 2.5 µs per loop
array size 100000
1000 loops, best of 3: 413 µs per loop
1000 loops, best of 3: 404 µs per loop
</code></pre>
<h2>Code</h2>
<pre><code>from scipy import ndimage
from scipy.ndimage import _nd_image
import numpy as np
laplace_filter = np.asarray([1, -2, 1], dtype=np.float64)
def fastLaplaceNd(arr):
output = np.zeros(arr.shape, 'float64')
if arr.ndim > 0:
_nd_image.correlate1d(arr, laplace_filter, 0, output, 1, 0.0, 0)
if arr.ndim == 1: return output
for ax in xrange(1, arr.ndim):
output += _nd_image.correlate1d(arr, laplace_filter, ax, output, 1, 0.0, 0)
return output
if __name__ == '__main__':
arr = np.random.random(10)
test = (ndimage.filters.laplace(arr, mode='wrap') == fastLaplace(arr)).all()
assert test
print "laplace == Mine ?", test
print 'testing timings...'
print "array size 10"
%timeit ndimage.filters.laplace(arr, mode='wrap')
%timeit fastLaplace(arr)
print 'array size 100'
arr = np.random.random(100)
%timeit ndimage.filters.laplace(arr, mode='wrap')
%timeit fastLaplace(arr)
print "array size 100000"
arr = np.random.random(100000)
%timeit ndimage.filters.laplace(arr, mode='wrap')
%timeit fastLaplace(arr)
</code></pre>
| 1 | 2016-08-10T11:58:20Z | [
"python",
"c++",
"numpy",
"filter"
] |
Tough time understanding the below Python Script | 38,867,706 | <p>I am new to coding and I am having a hard understanding the below code which prints all the prime numbers below 10.</p>
<pre><code>N = 10
primes = []
for n in range(2,N+1):
for p in primes:
if n % p == 0: break
else:
primes.append(n)
print(primes)
</code></pre>
<p>My question is- what is the value of p during the first iteration? Isn't it 0? If so, n%p is always 0 right? Please help me understand.</p>
| -3 | 2016-08-10T08:12:21Z | 38,867,895 | <p>A <code>for..in</code> loop over an empty list basically does nothing; it says "for each element in this list, do something", and since there is nothing in the list, it does nothing. So on the first iteration of the outer loop, the <code>for p in primes</code> does nothing at all, and the <code>else</code> clause is invoked. </p>
<p>On subsequent iterations there <em>is</em> something in <code>primes</code>, so the loop will get invoked and <code>p</code> will be populated with values.</p>
<p>The <code>else</code> clause of a <code>for..in</code> loop will be executed at the end of the loop, <strong>unless the loop is interrupted by <code>break</code>.</strong> That's exactly what is happening on your code: if the loop finds a divisible number, it <code>break</code>s the loop and nothing happens, otherwise the number will get added to <code>primes</code>.</p>
<p>The algorithm in a nutshell is: for numbers from 2â¦10, if the number is not a multiple of an already discovered prime, it's a prime.</p>
| 0 | 2016-08-10T08:22:25Z | [
"python",
"python-3.x"
] |
How to create image from numpy float32 array? | 38,867,869 | <p>I have a <code>numpy.ndarray</code> array which contains values of <code>float32</code>. The images should be dimensions 226×226. I tried to use <code>PIL.Image</code> to create the image but I got an error. I read that <code>PIL.Image.fromarray</code> require an object and mode, and for float I need to call <code>fromarray</code> with <code>'F'</code> as I tried.</p>
<p>This is what I tried to do:</p>
<pre><code>from PIL import Image
img = Image.fromarray(slice56, mode='F')
#type(slice56) = <type 'numpy.ndarray'>
#slice56 = array([ 0., 0., 0., ..., 0., 0., 0.], dtype=float32)
</code></pre>
<p>and I get this error:</p>
<pre><code>Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib64/python2.6/site-packages/PIL/Image.py", line 1860, in fromarray
return frombuffer(mode, size, obj, "raw", mode, 0, 1)
File "/usr/lib64/python2.6/site-packages/PIL/Image.py", line 1805, in frombuffer
return apply(fromstring, (mode, size, data, decoder_name, args))
File "/usr/lib64/python2.6/site-packages/PIL/Image.py", line 1743, in fromstring
im = new(mode, size)
File "/usr/lib64/python2.6/site-packages/PIL/Image.py", line 1710, in new
return Image()._new(core.fill(mode, size, color))
TypeError: argument 2 must be sequence of length 2, not 1
</code></pre>
<p>Can anyone suggest an idea how to do it? Or how to solve this error?</p>
| 2 | 2016-08-10T08:20:34Z | 38,869,210 | <p>I would agree with DavidG's answer being the a quick solution to plot image from numpy array. However, if you have some very good reason for sticking with <code>PIL.Image</code>. The closest approach to what you have already done would be something like this:</p>
<pre><code>from PIL import Image
import numpy as np
slice56 = np.random.random((226, 226))
# convert values to 0 - 255 int8 format
formatted = (slice56 * 255 / np.max(slice56)).astype('uint8')
img = Image.fromarray(formatted)
img.show()
</code></pre>
<p>I will then produce something like below given random numbers:</p>
<p><a href="http://i.stack.imgur.com/yJwUD.png" rel="nofollow"><img src="http://i.stack.imgur.com/yJwUD.png" alt="PIL Image"></a></p>
| 0 | 2016-08-10T09:21:36Z | [
"python",
"numpy",
"python-imaging-library"
] |
How to create image from numpy float32 array? | 38,867,869 | <p>I have a <code>numpy.ndarray</code> array which contains values of <code>float32</code>. The images should be dimensions 226×226. I tried to use <code>PIL.Image</code> to create the image but I got an error. I read that <code>PIL.Image.fromarray</code> require an object and mode, and for float I need to call <code>fromarray</code> with <code>'F'</code> as I tried.</p>
<p>This is what I tried to do:</p>
<pre><code>from PIL import Image
img = Image.fromarray(slice56, mode='F')
#type(slice56) = <type 'numpy.ndarray'>
#slice56 = array([ 0., 0., 0., ..., 0., 0., 0.], dtype=float32)
</code></pre>
<p>and I get this error:</p>
<pre><code>Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib64/python2.6/site-packages/PIL/Image.py", line 1860, in fromarray
return frombuffer(mode, size, obj, "raw", mode, 0, 1)
File "/usr/lib64/python2.6/site-packages/PIL/Image.py", line 1805, in frombuffer
return apply(fromstring, (mode, size, data, decoder_name, args))
File "/usr/lib64/python2.6/site-packages/PIL/Image.py", line 1743, in fromstring
im = new(mode, size)
File "/usr/lib64/python2.6/site-packages/PIL/Image.py", line 1710, in new
return Image()._new(core.fill(mode, size, color))
TypeError: argument 2 must be sequence of length 2, not 1
</code></pre>
<p>Can anyone suggest an idea how to do it? Or how to solve this error?</p>
| 2 | 2016-08-10T08:20:34Z | 38,871,070 | <p>Thanks to <code>John Titus Jungao</code> the problem solved. The array was 1D so I did the following:</p>
<pre><code>from PIL import Image
import numpy as np
slice56 = slice56.reshape((226,226))
formatted = (slice56 * 255 / np.max(slice56)).astype('uint8')
img = Image.fromarray(formatted)
img.save('slice56.png')
</code></pre>
<p>and that's it.</p>
| 0 | 2016-08-10T10:38:25Z | [
"python",
"numpy",
"python-imaging-library"
] |
How can I sum collection.Counter objects in a Python Pandas Dataframe using the update() method? | 38,867,901 | <p>I'm dealing with semi-structured data that doesn't fully fit into a pandas dataframe, so I have some columns containing collections.Counter objects (i.e. dictionaries) of vastly varying lengths.</p>
<p>I need to apply a groupby on another column and need to sum up these Counters, however without dropping zeros or ignoring negative values. That means I can not use the sum() method on these columns.</p>
<p>The method of choice would be the update() method, however it can't be simply applied like the sum() method as it needs an argument which would be another Counter which however sits in another row and not another column.</p>
<p>Example:</p>
<pre><code>import pandas as pd
import collections as cc
A = [cc.Counter({'A': 1,'B':-1,'C': 1}),\
cc.Counter({'A':-1,'B': 1, 'D': 0,'E': 1}),\
cc.Counter({'A': 0, 'E': 0,'F': 1}),\
cc.Counter({ 'B': 0,'C':-1, 'E':-1,'F':-1})]
B = ['N','N','N','N']
S1 = pd.Series(B,index=['W','X','Y','Z'],name='K',dtype=str)
S2 = pd.Series(A,index=['W','X','Y','Z'],name='L',dtype=dict)
F = pd.merge(S1.to_frame(),S2.to_frame(),left_index=True,right_index=True)
print F
</code></pre>
<p>This leads to the output</p>
<pre><code> K L
W N {u'A': 1, u'C': 1, u'B': -1}
X N {u'A': -1, u'B': 1, u'E': 1, u'D': 0}
Y N {u'A': 0, u'E': 0, u'F': 1}
Z N {u'C': -1, u'B': 0, u'E': -1, u'F': -1}
</code></pre>
<p>Doing this:</p>
<pre><code>G = F.groupby('K')
print G.sum()
</code></pre>
<p>Leads to this output:</p>
<pre><code> L
K
N {}
</code></pre>
<p>But what I want is this:</p>
<pre><code>Counter({'A': 0, 'C': 0, 'B': 0, 'E': 0, 'D': 0, 'F': 0})
</code></pre>
<p>which can be manually done with the update method like this:</p>
<pre><code>for i in range(1,4):
A[0].update(A[i])
print A[0]
</code></pre>
<p>So I either need a technique to apply update() to a groupby object either by creating an appropriate function or by changing the grouped rows into columns (something that seems rather inefficient and time-consuming to do), or I will have to restructure my data in a way that omits zeros and negative values in the Counters.</p>
<p>Any ideas are welcome.</p>
<p>EDIT:
I still fail to apply the proposed solution to the grouped DataFrame in my example:</p>
<pre><code>G.apply(lambda x: pd.DataFrame(x).sum().to_dict())
</code></pre>
<p>gives the result:</p>
<pre><code>K
N {u'K': u'NNNN', u'L': {}}
dtype: object
</code></pre>
<p>The problem is that I don't quite understand how apply on groupby objects works.</p>
<p>Like when I'm doing this:</p>
<pre><code>F.groupby('K').apply(lambda x: list(x))
</code></pre>
<p>The result is:</p>
<pre><code>K
N [K, L]
dtype: object
</code></pre>
<p>And I don't understand why and how.</p>
<p>EDIT 2 (SOLUTION):</p>
<p>After @piRSquared answers helped me to solve the problem I'm adding the full solution to not only get the dictionary but to get the dictionary back into a DataFrame as well:</p>
<pre><code>pd.DataFrame.from_dict([to_dict_dropna(pd.concat([F.K, F.L.apply(pd.Series)], axis=1)\
.groupby('K').sum())]).T.reset_index()
</code></pre>
<p>The function to_dict_dropna() is taken from "<a href="https://stackoverflow.com/questions/26033301">make pandas DataFrame to a dict and dropna</a>" and neccessary if there keys without values in the summed dictionaries.
I'm transposing the frame and resetting the index because I need the initial index as a column. Then I merge this with other frames to get the final format I need.</p>
<p>PS: This method is extremely memory-consuming and should not be used to larger datasets.</p>
| 2 | 2016-08-10T08:22:37Z | 38,868,104 | <p>consider the list of dicts <code>A</code></p>
<pre><code>A = [{'A': 1,'B':-1,'C': 1},
{'A':-1,'B': 1, 'D': 0,'E': 1},
{'A': 0, 'E': 0,'F': 1},
{ 'B': 0,'C':-1, 'E':-1,'F':-1}]
pd.DataFrame(A).stack().groupby(level=1).sum().to_dict()
{'A{'A': 0.0, 'B': 0.0, 'C': 0.0, 'D': 0.0, 'E': 0.0, 'F': 0.0}
</code></pre>
<hr>
<p>I'll keep that original answer alone. But it was based on my incorrect assumption that you wanted the last value. The answer then evolved when I realized <code>sum</code> is what you needed.</p>
<p>Given that, this is a better solution</p>
<pre><code>pd.DataFrame(A).sum().to_dict()
</code></pre>
<p>To apply this directly to the dataframe <code>F</code> you've defined:</p>
<pre><code>pd.concat([F.K, F.L.apply(pd.Series)], axis=1).groupby('K').sum()
</code></pre>
<p><a href="http://i.stack.imgur.com/qZSiH.png" rel="nofollow"><img src="http://i.stack.imgur.com/qZSiH.png" alt="enter image description here"></a></p>
| 3 | 2016-08-10T08:32:35Z | [
"python",
"python-2.7",
"pandas",
"dataframe",
"counter"
] |
Socket.io POST Requests from Socket.IO-Client-Swift | 38,868,061 | <p>I am running socket.io on an Apache server through Python Flask. We're integrating it into an iOS app (using the <a href="https://github.com/socketio/socket.io-client-swift" rel="nofollow">Socket.IO-Client-Swift</a> library) and we're having a weird issue.</p>
<p>From the client side code in the app (written in Swift), I can view the actual connection log (client-side in XCode) and see the connection established from the client's IP and the requests being made. The client never receives the information back (or any information back; even when using a global event response handler) from the socket server.</p>
<p>I wrote a very simple test script in Javascript on an HTML page and sent requests that way and received the proper responses back. With that said, it seems to likely be an issue with iOS. I've found these articles (but none of them helped fix the problem):</p>
<p><a href="https://github.com/nuclearace/Socket.IO-Client-Swift/issues/95" rel="nofollow">https://github.com/nuclearace/Socket.IO-Client-Swift/issues/95</a>
<a href="https://github.com/socketio/socket.io-client-swift/issues/359" rel="nofollow">https://github.com/socketio/socket.io-client-swift/issues/359</a></p>
<p>My next thought is to extend the logging of socket.io to find out exact what data is being POSTed to the socket namespace. Is there a way to log exactly what data is coming into the server (bear in mind that the 'on' hook on the server side that I've set up is not getting any data; I've tried to log it from there but it doesn't appear to even get that far).</p>
<p>I found mod_dumpio for Linux to log all POST requests but I'm not sure how well it will play with multi-threading and a socket server.</p>
<p>Any ideas on how to get the exact data being posted so we can at least troubleshoot the syntax and make sure the data isn't being malformed when it's sent to the server?</p>
<p>Thanks!</p>
<h2>Update</h2>
<p>When testing locally, we got it working (it was a setting in the Swift code where the namespace wasn't being declared properly). This works fine now on localhost but we are having the exact same issues when emitting to the Apache server.</p>
<p>We are not using mod_wsgi (as far as I know; I'm relatively new to mod_wsgi, apologies for any ignorance). We used to have a .wsgi file that called the main app script to run but we had to change that because mod_wsgi is not compatible with Flask SocketIO (as stated in the uWSGI Web Server section <a href="https://flask-socketio.readthedocs.io/en/latest/" rel="nofollow">here</a>). The way I am running the script now is by using <a href="http://supervisord.org/" rel="nofollow" title="supervisord">supervisord</a> to run the .py file as a daemon (using that specifically so it will autostart in the event of a server crash).</p>
<p>Locally, it worked great once we installed the eventlet module through pip. When I ran <code>pip freeze</code> on my virtual environment on the server, eventlet was installed. I uninstalled and reinstalled it just to see if that cleared anything up and that did nothing. No other Python modules that are on my local copy seem to be something that would affect this.</p>
<p>One other thing to keep in mind is that in the function that initializes the app, we change the port to port 80:</p>
<pre><code>socketio.run(app,host='0.0.0.0',port=80)
</code></pre>
<p>because we have other API functions that run through a domain that is pointing to the server in this app. I'm not sure if that would affect anything but it doesn't seem to matter on the local version.</p>
<p>I'm at a dead end again and am trying to find anything that could help. Thanks for your assistance!</p>
<h2>Another Update</h2>
<p>I'm not exactly sure what was happening yet but we went ahead and rewrote some of the code, making sure to pay extra special attention to the namespace declarations within each socket event <code>on</code> function. It's working fine now. As I get more details, I will post them here as I figure this will be something useful for other who have the same problem. This thread also has some really valuable information on how to go about debugging/logging these types of issues although we never actually fully figured out the answer to the original question.</p>
| 27 | 2016-08-10T08:30:41Z | 38,944,170 | <p>Are you using flask-socketio on the server side? If you are, there is a lot of debugging available in the constructor. </p>
<p>socketio = SocketIO(app, async_mode=async_mode, logger=True, engineio_logger=True)</p>
| 3 | 2016-08-14T16:22:57Z | [
"python",
"ios",
"linux",
"sockets",
"flask"
] |
Socket.io POST Requests from Socket.IO-Client-Swift | 38,868,061 | <p>I am running socket.io on an Apache server through Python Flask. We're integrating it into an iOS app (using the <a href="https://github.com/socketio/socket.io-client-swift" rel="nofollow">Socket.IO-Client-Swift</a> library) and we're having a weird issue.</p>
<p>From the client side code in the app (written in Swift), I can view the actual connection log (client-side in XCode) and see the connection established from the client's IP and the requests being made. The client never receives the information back (or any information back; even when using a global event response handler) from the socket server.</p>
<p>I wrote a very simple test script in Javascript on an HTML page and sent requests that way and received the proper responses back. With that said, it seems to likely be an issue with iOS. I've found these articles (but none of them helped fix the problem):</p>
<p><a href="https://github.com/nuclearace/Socket.IO-Client-Swift/issues/95" rel="nofollow">https://github.com/nuclearace/Socket.IO-Client-Swift/issues/95</a>
<a href="https://github.com/socketio/socket.io-client-swift/issues/359" rel="nofollow">https://github.com/socketio/socket.io-client-swift/issues/359</a></p>
<p>My next thought is to extend the logging of socket.io to find out exact what data is being POSTed to the socket namespace. Is there a way to log exactly what data is coming into the server (bear in mind that the 'on' hook on the server side that I've set up is not getting any data; I've tried to log it from there but it doesn't appear to even get that far).</p>
<p>I found mod_dumpio for Linux to log all POST requests but I'm not sure how well it will play with multi-threading and a socket server.</p>
<p>Any ideas on how to get the exact data being posted so we can at least troubleshoot the syntax and make sure the data isn't being malformed when it's sent to the server?</p>
<p>Thanks!</p>
<h2>Update</h2>
<p>When testing locally, we got it working (it was a setting in the Swift code where the namespace wasn't being declared properly). This works fine now on localhost but we are having the exact same issues when emitting to the Apache server.</p>
<p>We are not using mod_wsgi (as far as I know; I'm relatively new to mod_wsgi, apologies for any ignorance). We used to have a .wsgi file that called the main app script to run but we had to change that because mod_wsgi is not compatible with Flask SocketIO (as stated in the uWSGI Web Server section <a href="https://flask-socketio.readthedocs.io/en/latest/" rel="nofollow">here</a>). The way I am running the script now is by using <a href="http://supervisord.org/" rel="nofollow" title="supervisord">supervisord</a> to run the .py file as a daemon (using that specifically so it will autostart in the event of a server crash).</p>
<p>Locally, it worked great once we installed the eventlet module through pip. When I ran <code>pip freeze</code> on my virtual environment on the server, eventlet was installed. I uninstalled and reinstalled it just to see if that cleared anything up and that did nothing. No other Python modules that are on my local copy seem to be something that would affect this.</p>
<p>One other thing to keep in mind is that in the function that initializes the app, we change the port to port 80:</p>
<pre><code>socketio.run(app,host='0.0.0.0',port=80)
</code></pre>
<p>because we have other API functions that run through a domain that is pointing to the server in this app. I'm not sure if that would affect anything but it doesn't seem to matter on the local version.</p>
<p>I'm at a dead end again and am trying to find anything that could help. Thanks for your assistance!</p>
<h2>Another Update</h2>
<p>I'm not exactly sure what was happening yet but we went ahead and rewrote some of the code, making sure to pay extra special attention to the namespace declarations within each socket event <code>on</code> function. It's working fine now. As I get more details, I will post them here as I figure this will be something useful for other who have the same problem. This thread also has some really valuable information on how to go about debugging/logging these types of issues although we never actually fully figured out the answer to the original question.</p>
| 27 | 2016-08-10T08:30:41Z | 38,968,504 | <p>I assume you have verified that Apache does get the POST requests. That should be your first test, if Apache does not log the POST requests coming from iOS, then you have a different kind of problem.</p>
<p>If you do get the POST requests, then you can add some custom code in the middleware used by Flask-SocketIO and print the request data forwarded by Apache's mod_wsgi. The this is in file <a href="https://github.com/miguelgrinberg/Flask-SocketIO/blob/master/flask_socketio/__init__.py#L35-L38" rel="nofollow">flask_socketio/<strong>init</strong>.py</a>. The relevant portion is this:</p>
<pre><code>class _SocketIOMiddleware(socketio.Middleware):
# ...
def __call__(self, environ, start_response):
# log what you need from environ here
environ['flask.app'] = self.flask_app
return super(_SocketIOMiddleware, self).__call__(environ, start_response)
</code></pre>
<p>You can find out what's in <code>environ</code> in the <a href="http://legacy.python.org/dev/peps/pep-3333/" rel="nofollow">WSGI specification</a>. In particular, the body of the request is available in <code>environ['wsgi.input']</code>, which is a file-like object you read from.</p>
<p>Keep in mind that once you read the payload, this file will be consumed, so the WSGI server will not be able to read from it again. Seeking the file back to the position it was before the read may work on some WSGI implementations. A safer hack I've seen people do to avoid this problem is to read the whole payload into a buffer, then replace <code>environ['wsgi.input']</code> with a brand new <code>StringIO</code> or <code>BytesIO</code> object.</p>
| 3 | 2016-08-16T07:02:31Z | [
"python",
"ios",
"linux",
"sockets",
"flask"
] |
Picking a random element from a non-empty defaultdict | 38,868,130 | <p>Say I do:</p>
<pre><code>import collections, random
d = collections.defaultdict(list)
d['foo'].append('bar')
</code></pre>
<p>Then I pick a random element:</p>
<pre><code>random.choice(d)
</code></pre>
<p>Now let's print <code>d</code>:</p>
<pre><code>defaultdict(list, {0: [], 'foo': ['bar']})
</code></pre>
<p>Why did <code>random.choice</code> add <code>0</code> as a key?</p>
| 3 | 2016-08-10T08:33:42Z | 38,868,252 | <p>Internally this is what <a href="https://hg.python.org/cpython/file/2.7/Lib/random.py#l273"><code>random.choice</code></a> does:</p>
<pre><code>def choice(self, seq):
"""Choose a random element from a non-empty sequence."""
return seq[int(self.random() * len(seq))]
</code></pre>
<p>As in your case the length was 1, after multiplication it would result in an number in range <code>[0.0, 1.0)</code> and after applying <code>int()</code>to it you will get 0.</p>
<p>Note that <code>defaultdict</code> will add any key to the dict that was accessed on it:</p>
<pre><code>>>> d = collections.defaultdict(list)
>>> d['i dont exist']
[]
>>> d
defaultdict(<type 'list'>, {'i dont exist': []})
</code></pre>
<p>Hence, your dict ended up with <code>0</code>.</p>
| 6 | 2016-08-10T08:39:50Z | [
"python",
"python-3.x",
"defaultdict"
] |
Picking a random element from a non-empty defaultdict | 38,868,130 | <p>Say I do:</p>
<pre><code>import collections, random
d = collections.defaultdict(list)
d['foo'].append('bar')
</code></pre>
<p>Then I pick a random element:</p>
<pre><code>random.choice(d)
</code></pre>
<p>Now let's print <code>d</code>:</p>
<pre><code>defaultdict(list, {0: [], 'foo': ['bar']})
</code></pre>
<p>Why did <code>random.choice</code> add <code>0</code> as a key?</p>
| 3 | 2016-08-10T08:33:42Z | 38,868,488 | <p>I think the behavior is actually <em>undefined</em>, because according to the document(emphasis mine):</p>
<blockquote>
<p><code>random.choice(seq)</code> </p>
<p>Return a random element from the non-empty
<strong>sequence</strong> seq. If seq is empty, raises IndexError.</p>
</blockquote>
<p><code>seq</code> need to be a <strong>sequence</strong> type, such as <code>list</code>, <code>tuple</code> and <code>range</code>. However, <code>defaultdict</code> is a subclass of the built-in <code>dict</code> class, and thus it's a <strong>mapping</strong> type.</p>
<p>And since sequence types can only have integers as their "keys", it's not strange why <code>random.choice</code> would lookup <code>d[x]</code>, where <code>x</code> is an integer in <code>range(0, len(d))</code>.</p>
| 1 | 2016-08-10T08:50:32Z | [
"python",
"python-3.x",
"defaultdict"
] |
pandas fillna inplace with multiindex | 38,868,269 | <p>I have a dataframe with multiindex</p>
<pre><code> values observations
time x1 x2 x3 x4 ... x1 x2 x3 x4 ...
t1 v1_1 nan v3_1 v4_1 ... o1_1 nan o3_1 o4_1 ...
t2 v1_2 v2_2 nan v4_2 ... o1_2 o2_2 nan o4_2 ...
</code></pre>
<p>I am trying to fillna the observations frame with 0s</p>
<pre><code>df.loc[:,('observations')].fillna(value=0, inplace=True)
</code></pre>
<p>But this does not fill the df. When I take a slice and apply fillna, it works</p>
<pre><code>dfx = df.loc[:,('observations')].fillna(value=0)
</code></pre>
<p>dfx has its nans replaced by 0s and I can replace the original part</p>
<pre><code>df.observations = dfx
</code></pre>
<p>It is not clear to me why the first approach would not work. Seems odd. Could anyone enlighten me here?</p>
| 2 | 2016-08-10T08:40:37Z | 38,868,399 | <p>For me works:</p>
<pre><code>df['observations'] = df['observations'].fillna(0)
print (df)
values observations
time x1 x2 x3 x4 x1 x2 x3
t1 v1_1 NaN v3_1 v4_1 o1_1 0 o3_1 o4_1
t2 v1_2 v2_2 NaN v4_2 o1_2 o2_2 0 o4_2
</code></pre>
<p><strong>I think problem is <code>loc</code> doesnt work inplace.</strong> So you can use:</p>
<pre><code>df1 = df.loc[:,('observations')]
df1.fillna(value=0, inplace=True)
</code></pre>
<p>Another solution is selecting by <code>slicing</code>, but need first sort columns names by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sort_index.html" rel="nofollow"><code>sort_index</code></a>:</p>
<pre><code>df.sort_index(inplace=True, axis=1)
idx = pd.IndexSlice
df.loc[:, idx['observations',:]] = df.loc[:, idx['observations',:]].fillna(0)
print (df)
observations values
time x1 x2 x3 x4 x1 x2 x3 x4
t1 o1_1 0 o3_1 o4_1 v1_1 NaN v3_1 v4_1
t2 o1_2 o2_2 0 o4_2 v1_2 v2_2 NaN v4_2
</code></pre>
| 2 | 2016-08-10T08:46:42Z | [
"python",
"pandas"
] |
How to access global variables from a thread in Python | 38,868,341 | <p>Consider the following code: </p>
<pre><code>from threading import Thread
def main():
number = 5
class my_thread(Thread):
def __init__(self, range):
Thread.__init__(self)
self.range = range
def run(self):
global number
for i in self.range:
number += 1
t1 = my_thread(range(4))
t1.start()
t1.join()
print number
main()
</code></pre>
<p>The output from this program is </p>
<pre><code>Exception in thread Thread-1:
Traceback (most recent call last):
File "C:\Tools\Python27\lib\threading.py", line 801, in __bootstrap_inner
self.run()
File "C:\Dev\Workspace\Hello World\Hello.py", line 14, in run
number += 1
NameError: global name 'number' is not defined
5
</code></pre>
<p>Evidently, <code>my_thread</code> does not have access to <code>number</code>. Why is this, and how can I access it correctly? </p>
| 0 | 2016-08-10T08:44:06Z | 38,868,438 | <p>You need to make <code>number</code> a global at its first definition, like this:</p>
<pre><code>def main():
global number
number = 5
...etc...
</code></pre>
| 2 | 2016-08-10T08:48:50Z | [
"python",
"multithreading",
"thread-safety"
] |
How to pass two same arguments via python subprocess? | 38,868,461 | <p>I wanted to pass two parameter in the subprocess call... like this...</p>
<pre><code>./buildbot sendchange --branch=poky --property=buildname:nice --property=machine:qemux86
</code></pre>
<p>So I wrote the below program...</p>
<pre><code># property_name = {'key': 'value'}
y = ['--property={}:{}'.format(key, value) for key, value in property_name.items()]
cmd = [
'./buildbot', 'sendchange',
'--branch={}'.format(
branch),
y
]
</code></pre>
<p>And above command throws error by subprocess!</p>
<pre><code>Traceback (most recent call last):
File "/home/iaskin/Workspace/latest/local/lib/python2.7/site-packages/django/core/handlers/exception.py", line 39, in inner
response = get_response(request)
File "/home/iaskin/Workspace/latest/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 249, in _legacy_get_response
response = self._get_response(request)
File "/home/iaskin/Workspace/latest/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 187, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/home/iaskin/Workspace/latest/local/lib/python2.7/site-packages/channels/handler.py", line 227, in process_exception_by_middleware
return super(AsgiHandler, self).process_exception_by_middleware(exception, request)
File "/home/iaskin/Workspace/latest/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 185, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/iaskin/Workspace/latest/local/lib/python2.7/site-packages/django/contrib/auth/decorators.py", line 23, in _wrapped_view
return view_func(request, *args, **kwargs)
File "/home/iaskin/Workspace/buildsys/build_app/views.py", line 93, in home
property_name=property_name
File "/home/iaskin/Workspace/buildsys/build_app/helper/build_agent.py", line 50, in submit_buildbot
output = subprocess.Popen(cmd, cwd=bb_master_dir)
File "/usr/lib/python2.7/subprocess.py", line 711, in __init__
errread, errwrite)
File "/usr/lib/python2.7/subprocess.py", line 1343, in _execute_child
raise child_exception
TypeError: execv() arg 2 must contain only strings
</code></pre>
<p>So I changed the above code to this</p>
<pre><code>y = ['--property={}:{}'.format(key, value) for key, value in property_name.items()]
cmd = [
'./buildbot', 'sendchange', '--master=bsp-buildvm:9999',
'--branch={}'.format(
branch),
"{}".format(' '.join(y))
]
</code></pre>
<p>And this is I don't want ...</p>
<pre><code>./buildbot sendchange --branch=poky "--property=buildname:nice --property=machine:qemux86"
</code></pre>
<p>So am I doing anything wrong ? Or Is <code>subprocess</code> really doesn't allow this then what are the other alternatives ?</p>
| 0 | 2016-08-10T08:49:37Z | 38,868,826 | <p>In parent process save argument as environment variables. Child process can access it.</p>
| 0 | 2016-08-10T09:06:40Z | [
"python",
"django",
"subprocess",
"buildbot"
] |
Python: Pandas: Save Index of DataFrames in textfile as columns | 38,868,490 | <p>I have a list of DataFrames df_list. I want to write a tab delimited textfile: The first row is the index of the list. Each column is then the values in the DataFrame index. The index.values have not the same lenght.</p>
<pre><code>0 1 2 3
i i i i
n n n .
d d . .
e . . .
x . .
. .
v
a
l
u
e
s
</code></pre>
<p>I tried:</p>
<pre><code>arrays = []
for i in range(len(df_list)):
arrays.append(df_list[i].index.values)
np.savetxt('clusters.txt', np.transpose(arrays))
</code></pre>
<p>But I get: <code>TypeError: Mismatch between array dtype ('object') and format specifier ('%.18e')</code></p>
<p>When I use (piRSquared´s answer):</p>
<pre><code>df_master = pd.DataFrame({i: df.index.to_series() for i, df in enumerate(df_list)})
sorted_cols = df_master.notnull().sum().sort_values()[::-1].index
df_master[sorted_cols].to_csv('clusters.txt', sep='\t', index=None, float_format='%0.0f')
</code></pre>
<p>I get for example:</p>
<pre><code> 7 21
D0EX67
E1MTY0
P00350
P00363
P00370
P00452
P00490
</code></pre>
<p>Is there a way to get rid of the empty cells?</p>
| 1 | 2016-08-10T08:50:36Z | 38,869,139 | <pre><code>df_list = [pd.DataFrame(range(i)) for i in range(10, 15)]
df_master = pd.DataFrame({i: df.index.to_series() for i, df in enumerate(df_list)})
sorted_cols = df_master.notnull().sum().sort_values()[::-1].index
print df_master[sorted_cols].to_csv(sep='\t', index=None, float_format='%0.0f')
</code></pre>
<p><a href="http://i.stack.imgur.com/QFQ1W.png" rel="nofollow"><img src="http://i.stack.imgur.com/QFQ1W.png" alt="enter image description here"></a></p>
<p>To save to a file:</p>
<pre><code>df_master.to_csv('mytextfile.txt', sep='\t')
</code></pre>
| 2 | 2016-08-10T09:19:08Z | [
"python",
"pandas"
] |
from OpenGLContext import testingcontext i cant import testingcontext | 38,868,564 | <p>When i do this:</p>
<pre><code>import OpenGLContext
</code></pre>
<p>its importing, there is no problem. But when i write</p>
<pre><code>from OpenGLContext import testingcontext
</code></pre>
<p>its giving an error:</p>
<pre><code> Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
from OpenGLContext import testingcontext
File "C:\Python34\lib\site-packages\OpenGLContext\testingcontext.py", line 10, in <module>
from OpenGLContext import plugins, context, contextdefinition
File "C:\Python34\lib\site-packages\OpenGLContext\context.py", line 33, in <module>
from OpenGLContext import texturecache,plugins
File "C:\Python34\lib\site-packages\OpenGLContext\texturecache.py", line 3, in <module>
from OpenGLContext import atlas
File "C:\Python34\lib\site-packages\OpenGLContext\atlas.py", line 4, in <module>
from OpenGLContext.arrays import zeros, array, dot, ArrayType
File "C:\Python34\lib\site-packages\OpenGLContext\arrays.py", line 2, in <module>
from vrml.arrays import *
ImportError: No module named 'vrml'
</code></pre>
<p>Whats wrong?</p>
| 0 | 2016-08-10T08:54:20Z | 38,871,406 | <p>The <code>vrml</code> phython module is missing. So the first step would be installing that.</p>
| 0 | 2016-08-10T10:54:10Z | [
"python",
"opengl",
"openglcontext"
] |
<FloatField'> is not JSON serializable | 38,868,583 | <p>I am currently learning Django, i tried creating a simple model and expose it in an API.</p>
<blockquote>
<p>FloatField' is not JSON serializable</p>
</blockquote>
<p>it only works if i change the float to string.</p>
<p>When i call the api to retreive the model object i receive error: </p>
<p>I defined the model as follows:</p>
<pre><code>class RunSession(models.Model):
name = models.CharField(max_length=100, blank=True, default='')
miles = models.FloatField
duration = models.FloatField
created= models.DateTimeField(auto_now_add=True, blank=True)
</code></pre>
<p>Serializer:</p>
<pre><code>class RunSessionSerializer(serializers.ModelSerializer):
class Meta:
model = RunSession
fields = ('created', 'name', 'miles', 'duration', )
</code></pre>
<p>ViewSet:</p>
<pre><code>class RunSessionViewSet(viewsets.ModelViewSet):
queryset = RunSession.objects.order_by('created')
serializer_class = RunSessionSerializer
</code></pre>
| 0 | 2016-08-10T08:55:09Z | 38,868,617 | <p>You are passing the original field objects and not instantiating them. Do instantiate them:</p>
<pre><code>miles = models.FloatField(...)
# ^^^^^
</code></pre>
| 4 | 2016-08-10T08:56:40Z | [
"python",
"django",
"rest",
"django-rest-framework"
] |
Modify pandas group | 38,868,682 | <p>I have a DataFrame, which I group.
I would like to add another column to the data frame, that is a result of function diff, per group. Something like:</p>
<pre><code>df = pd.DataFrame({'A' : ['foo', 'bar', 'foo', 'bar',
'foo', 'bar', 'foo', 'foo'],
'B' : ['one', 'one', 'two', 'three',
'two', 'two', 'one', 'three'],
'C' : np.random.randn(8),
'D' : np.random.randn(8)})
df_grouped = df.groupby('B')
for name, group in df_grouped:
new_df["D_diff"] = group["D"].diff()
</code></pre>
<p>I would like to get per each group the differnece of column D, and have a DF that include a new column with the diff calculation. </p>
| 5 | 2016-08-10T09:00:19Z | 38,868,729 | <p>IIUC you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.DataFrameGroupBy.diff.html"><code>DataFrameGroupBy.diff</code></a>:</p>
<pre><code>df['D_diff'] = df.groupby('B')['D'].diff()
print (df)
A B C D D_diff
0 foo one 1.996084 0.580177 NaN
1 bar one 1.782665 0.042979 -0.537198
2 foo two -0.359840 1.952692 NaN
3 bar three -0.909853 0.119353 NaN
4 foo two -0.478386 -0.970906 -2.923598
5 bar two -1.289331 -1.245804 -0.274898
6 foo one -1.391884 -0.555056 -0.598035
7 foo three -1.270533 0.183360 0.064007
</code></pre>
| 5 | 2016-08-10T09:02:31Z | [
"python",
"pandas",
"dataframe",
"group-by",
"difference"
] |
Calculate difference of two layers | 38,868,771 | <p>I want to merge two keras layers such that the merged layer has the difference of the two layers. For example if layer1 output is [0,1,2] and layer2 output is [1,2,3] the merged layer should be [-1,-1,-1]. I tried using the following</p>
<pre><code>from keras.layers import Input, merge
from keras.models import Model
import numpy as np
input_a = np.reshape([1, 2, 3], (1, 1, 3))
input_b = np.reshape([4, 5, 6], (1, 1, 3))
a = Input(shape=(1, 3))
b = Input(shape=(1, 3))
diff = merge([a, b], mode=lambda x, y: x - y)
diff_model = Model(input=[a, b], output=diff)
print(diff_model.predict([input_a, input_b]))
</code></pre>
<p>which resulted in the following error,</p>
<pre><code> File "/usr/local/lib/python2.7/dist-packages/keras/engine/topology.py", line 1464, in merge â self.add_inbound_node(layers, node_indices, tensor_indices)
name=name) â File "/usr/local/lib/python2.7/dist-packages/keras/engine/topolog
File "/usr/local/lib/python2.7/dist-packages/keras/engine/topology.py", line 1123, in __init__ ây.py", line 543, in add_inbound_node
self.add_inbound_node(layers, node_indices, tensor_indices) â Node.create_node(self, inbound_layers, node_indices, tensor_ind
File "/usr/local/lib/python2.7/dist-packages/keras/engine/topology.py", line 543, in add_inbound_node âices)
Node.create_node(self, inbound_layers, node_indices, tensor_indices) â File "/usr/local/lib/python2.7/dist-packages/keras/engine/topolog
File "/usr/local/lib/python2.7/dist-packages/keras/engine/topology.py", line 153, in create_node ây.py", line 155, in create_node
output_tensors = to_list(outbound_layer.call(input_tensors, mask=input_masks)) â output_shapes = to_list(outbound_layer.get_output_shape_for(inp
File "/usr/local/lib/python2.7/dist-packages/keras/engine/topology.py", line 1200, in call âut_shapes))
return self.mode(inputs, **arguments) â File "/usr/local/lib/python2.7/dist-packages/keras/engine/topolog
TypeError: <lambda>() takes exactly 2 arguments (1 given)
</code></pre>
<p>How can I perform the merge operation?</p>
| 1 | 2016-08-10T09:04:06Z | 38,872,680 | <p>I was able to merge the layers in the above way using,</p>
<pre><code>diff = merge([a, b], mode=lambda (x, y): x - y, output_shape=(3,))
</code></pre>
| 1 | 2016-08-10T11:52:16Z | [
"python",
"theano",
"keras"
] |
How to use split from regex in python and keep your split word? | 38,868,800 | <p>Is there a way to use split function without losing the word or char, that you using to split with?</p>
<p>for example:</p>
<pre><code>import re
x = '''\
1.
abcde.
2.
fgh 2.5 ijk.
3.
lmnop
'''
print(x)
listByNum = re.split(r'\d\.\D', x)
print(listByNum)
</code></pre>
<p><a href="http://i.stack.imgur.com/5es14.png" rel="nofollow"><img src="http://i.stack.imgur.com/5es14.png" alt="the output"></a>
I want to keep the digit in the list</p>
<p>An other example:</p>
<pre><code>import re
x = '''\
I love stackoverflow. I love food.\nblah blah blah.
'''
print(x)
listBySentences = re.split(r'\.', x)
print(listBySentences)
</code></pre>
<p><a href="http://i.stack.imgur.com/jgjnJ.png" rel="nofollow"><img src="http://i.stack.imgur.com/jgjnJ.png" alt="output for example 2"></a></p>
| 0 | 2016-08-10T09:05:28Z | 38,868,882 | <p>Not very well documented, but you can use parentheses around the expression in question:</p>
<pre><code>import re
x = '''\
1.
abcde.
2.
fgh 2.5 ijk.
3.
lmnop
'''
print(x)
listByNum = re.split(r'(\d\.\D)', x)
print(listByNum)
# ['', '1.\n', 'abcde.\n', '2.\n', 'fgh 2.5 ijk.\n', '3.\n', 'lmnop\n ']
</code></pre>
<p><hr>
To even <em>clean</em> your data afterwards, you can use a list comprehension, like so:</p>
<pre><code>listByNum = [num.strip() for num in re.split(r'(\d\.\D)', x) if num]
# ['1.', 'abcde.', '2.', 'fgh 2.5 ijk.', '3.', 'lmnop']
</code></pre>
<p><hr>
To keep the digits within the splitted elements, you can use the newer <a href="https://pypi.python.org/pypi/regex" rel="nofollow"><strong>regex</strong></a> module which supports splitting on empty strings:</p>
<pre><code>import regex as re
x = same string as above
listByNum = [num.strip() for num in re.split(r'(?V1)(?=\d\.\D)', x) if num]
# ['1.\nabcde.', '2.\nfgh 2.5 ijk.', '3.\nlmnop']
</code></pre>
| 2 | 2016-08-10T09:08:32Z | [
"python",
"regex",
"string",
"split"
] |
Python TripleDES decryption | 38,869,018 | <p>I'm trying to decrypt a string in python encrypted using 3DES. It is encrypted by VB.net by my formal mate. I have no idea what is going on. The partial code in VB.net is</p>
<pre><code>Private key() As Byte = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24}
Private iv() As Byte = {65, 110, 68, 26, 69, 178, 200, 219}
Private objTripleDES As New clsTripleDES(key, iv)
</code></pre>
<p>The code is similar is to <a href="https://www.planet-source-code.com/vb/scripts/ShowCode.asp?txtCodeId=1564&lngWId=10" rel="nofollow">https://www.planet-source-code.com/vb/scripts/ShowCode.asp?txtCodeId=1564&lngWId=10</a></p>
<p>Is it possible to decrypt in python? Do I need to use bytearray?</p>
| 0 | 2016-08-10T09:14:30Z | 38,908,168 | <p>How about something like this:</p>
<pre><code>from Crypto.Cipher import DES3
key = [
1, 2, 3, 4, 5, 6, 7, 8,
9, 10, 11, 12, 13, 14, 15, 16,
17, 18, 19, 20, 21, 22, 23, 24
]
iv = [65, 110, 68, 26, 69, 178, 200, 219]
keyStr = ""
ivStr = ""
for i in key:
keyStr += chr(i)
for i in iv:
ivStr += chr(i)
encr = DES3.new(keyStr, DES3.MODE_CBC, ivStr)
decr = DES3.new(keyStr, DES3.MODE_CBC, ivStr)
#Outputs "1234567891234567"
print decr.decrypt(encr.encrypt("1234567891234567"))
</code></pre>
<p>You should investigate what mode was used for encryption in VB code. CBC is the default mode, according to <a href="https://msdn.microsoft.com/en-us/library/system.security.cryptography.symmetricalgorithm.mode(v=vs.110).aspx" rel="nofollow">this</a>, but you can't be sure.
See <a href="https://www.dlitz.net/software/pycrypto/api/2.6/" rel="nofollow">this</a> when you figure out what mode was used.</p>
| 0 | 2016-08-12T00:43:06Z | [
"python",
"vb.net",
"bytearray",
"tripledes"
] |
Empty file json as output in Scrapy | 38,869,099 | <p>I state that I've already read some answers about the same problem but the I couldn't solve my issue.
I'm new in Python, I'm trying to extract data from Aptoide about apps and stores, and I want an output result as .json file (or csv), but the file I get is empty, I don't know the reason.</p>
<p>This is my code:</p>
<pre><code> import scrapy
from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor
from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.selector import HtmlXPathSelector
class ApptoideItem(scrapy.Item):
app_name = scrapy.Field()
rating = scrapy.Field()
security_status = scrapy.Field()
good_flag = scrapy.Field()
licence_flag = scrapy.Field()
fake_flag = scrapy.Field()
freeze_flag = scrapy.Field()
virus_flag = scrapy.Field()
five_stars = scrapy.Field()
four_stars = scrapy.Field()
three_stars = scrapy.Field()
two_stars = scrapy.Field()
one_stars = scrapy.Field()
info = scrapy.Field()
download = scrapy.Field()
version = scrapy.Field()
size = scrapy.Field()
link = scrapy.Field()
store = scrapy.Field()
class AppSpider(CrawlSpider):
name = "second"
allowed_domains = ["aptoide.com"]
start_urls = [ "http://www.aptoide.com/page/morestores/type:top" ]
rules = (
Rule(LinkExtractor(allow=(r'\w+\.store\.aptoide\.com$'))),
Rule(LinkExtractor(allow=(r'\w+\.store\.aptoide\.com/app/market')), callback='parse_item')
)
def parse_item(self, response):
item = ApptoideItem()
item['app_name']= str(response.css(".app_name::text").extract()[0])
item['rating']= str(response.css(".app_rating_number::text").extract()[0])
item['security_status']= str(response.css("#show_app_malware_data::text").extract()[0])
item['good_flag']= int(response.css(".good > div:nth-child(3)::text").extract()[0])
item['licence_flag']= int(response.css(".license > div:nth-child(3)::text").extract()[0])
item['fake_flag']= int(response.css(".fake > div:nth-child(3)::text").extract()[0])
item['freeze_flag']= int(response.css(".freeze > div:nth-child(3)::text").extract()[0])
item['virus_flag']= int(response.css(".virus > div:nth-child(3)::text").extract()[0])
item['five_stars']= int(response.css("div.app_ratting_bar_holder:nth-child(1) > div:nth-child(3)::text").extract()[0])
item['four_stars']= int(response.css("div.app_ratting_bar_holder:nth-child(2) > div:nth-child(3)::text").extract()[0])
item['three_stars']= int(response.css("div.app_ratting_bar_holder:nth-child(3) > div:nth-child(3)::text").extract()[0])
item['two_stars']= int(response.css("div.app_ratting_bar_holder:nth-child(4) > div:nth-child(3)::text").extract()[0])
item['link']= response.url
item['one_stars']= int(response.css("div.app_ratting_bar_holder:nth-child(5) > div:nth-child(3)::text").extract()[0])
item['download']= int(response.css("p.app_meta::text").re('(\d[\w\.]*)')[0].replace('.', ''))
item['version']= str(response.css("p.app_meta::text").re('(\d[\w\.]*)')[1])
item['size']= str(response.css("p.app_meta::text").re('(\d[\w\.]*)')[2])
item['store_name']= str(response.css(".sec_header_txt::text").extract()[0])
item['info_store']= str(response.css(".ter_header2::text").extract()[0])
yield item
</code></pre>
<p>I'm pretty sure that the problema is that parse_item method never invoked, and I don't know the reason. The first rule follows the stores, while the second one follows apps in stores. I think the syntax of regular expressions is right.</p>
<p>Setting are:</p>
<pre><code>CLOSESPIDER_PAGECOUNT = 1000
CLOSESPIDER_ITEMCOUNT = 500
CONCURRENT_REQUESTS = 1
CONCURRENT_ITEMS = 1
BOT_NAME = 'nuovo'
SPIDER_MODULES = ['nuovo.spiders']
NEWSPIDER_MODULE = 'nuovo.spiders'
</code></pre>
<p>Could anyone find the problem and suggest me a solution?</p>
| 0 | 2016-08-10T09:17:25Z | 38,872,644 | <p>Your code is full of errors, when you run the spider you can save the log and go through it with grep:</p>
<pre><code>scrapy crawl spidername 2>&1 | tee crawl.log
</code></pre>
<p>Few errors that I found:</p>
<ul>
<li>your <code>ApptoideItem</code> is missing fields like <code>store_name</code> and few others.</li>
<li>your whole <code>int()</code> conversion is insecure, meaning if your <code>response.css</code> returns None, which it does if it finds nothing, you get an error.</li>
</ul>
<p>To resolve the second point I suggest looking into <a href="http://doc.scrapy.org/en/latest/topics/loaders.html" rel="nofollow">scrapy ItemLoaders</a> which will allow you to specify default behaviour for some fields, like turn items in fields <code>_flag</code> to boolean etc.<br>
Also as @Jan mentioned in the comments, you should use <code>extract_first()</code> method instead of <code>extract()[0]</code>, extract_first allows you to specify default attribute for when nothing is found, i.e. <code>.extract_first(default=0)</code></p>
| 0 | 2016-08-10T11:50:46Z | [
"python",
"json",
"regex",
"scrapy",
"rule"
] |
converting tuples to lists in list | 38,869,124 | <p>I am attempting to convert tuples in lists of a list to lists. More accurately, I just would like to remove the tuples in lists. The original dataset looks like</p>
<pre><code>collections = [[None], [(u'John Demsey ', u' Cornelia Guest')], [(u'Andres White ', u' Margherita Missoni')], [(u'Bibi Monahan, Tuki Br', u'o, ')], [(u'W$
</code></pre>
<p>What I would like to achivee is:</p>
<pre><code>collections = [[None], [u'John Demsey ', u' Cornelia Guest'], [u'Andres White ', u' Margherita Missoni']...]
</code></pre>
<p>Nevertheless, with the following code, I fail to achieve my goal.</p>
<pre><code>def conv():
for i in range(len(collections)):
if collections[i] != None:
collections[i] = list(collections[i])
else:
collections[i][0] = list(collections[i][0])
return collections[i]
conv = conv()
print(conv)
</code></pre>
<p>In the code, I attempted to convert tuples to lists. However, this does not look work. Could someone help me identify the problem and help me correct this? Thank you!!</p>
| 0 | 2016-08-10T09:18:40Z | 38,869,357 | <p>Rather go for <code>chain</code> in <code>itertools</code> and list comprehension:</p>
<pre><code>from itertools import chain
[list(i) if i else [i] for i in chain.from_iterable(collections)]
#Out[110]:
#[[None],
# [u'John Demsey ', u' Cornelia Guest'],
# [u'Andres White ', u' Margherita Missoni']]
</code></pre>
| 1 | 2016-08-10T09:28:18Z | [
"python",
"list",
"tuples"
] |
converting tuples to lists in list | 38,869,124 | <p>I am attempting to convert tuples in lists of a list to lists. More accurately, I just would like to remove the tuples in lists. The original dataset looks like</p>
<pre><code>collections = [[None], [(u'John Demsey ', u' Cornelia Guest')], [(u'Andres White ', u' Margherita Missoni')], [(u'Bibi Monahan, Tuki Br', u'o, ')], [(u'W$
</code></pre>
<p>What I would like to achivee is:</p>
<pre><code>collections = [[None], [u'John Demsey ', u' Cornelia Guest'], [u'Andres White ', u' Margherita Missoni']...]
</code></pre>
<p>Nevertheless, with the following code, I fail to achieve my goal.</p>
<pre><code>def conv():
for i in range(len(collections)):
if collections[i] != None:
collections[i] = list(collections[i])
else:
collections[i][0] = list(collections[i][0])
return collections[i]
conv = conv()
print(conv)
</code></pre>
<p>In the code, I attempted to convert tuples to lists. However, this does not look work. Could someone help me identify the problem and help me correct this? Thank you!!</p>
| 0 | 2016-08-10T09:18:40Z | 38,869,425 | <p>Try to do it this way:</p>
<pre><code>def conv():
return [list(c[0]) if isinstance(c[0], tuple) else c for c in collections]
</code></pre>
<p>In your code you also return just the last element of list.</p>
| 2 | 2016-08-10T09:30:46Z | [
"python",
"list",
"tuples"
] |
Îpposite of any() function | 38,869,155 | <p>The Python built-in function <code>any(iterable)</code> can help to quickly check if any <code>bool(element)</code> is <code>True</code> in a iterable type.</p>
<pre><code>>>> l = [None, False, 0]
>>> any(l)
False
>>> l = [None, 1, 0]
>>> any(l)
True
</code></pre>
<p>But is there an elegant way or function in Python that could achieve the opposite effect of <code>any(iterable)</code>? That is, if any <code>bool(element) is False</code> then return <code>True</code>, like the following example:</p>
<pre><code>>>> l = [True, False, True]
>>> any_false(l)
>>> True
</code></pre>
| 56 | 2016-08-10T09:19:40Z | 38,869,220 | <p>Write a generator expression which tests your custom condition. You're not bound to only the default <em>truthiness</em> test:</p>
<pre><code>any(not i for i in l)
</code></pre>
| 41 | 2016-08-10T09:21:59Z | [
"python",
"python-3.x",
"iterable"
] |
Îpposite of any() function | 38,869,155 | <p>The Python built-in function <code>any(iterable)</code> can help to quickly check if any <code>bool(element)</code> is <code>True</code> in a iterable type.</p>
<pre><code>>>> l = [None, False, 0]
>>> any(l)
False
>>> l = [None, 1, 0]
>>> any(l)
True
</code></pre>
<p>But is there an elegant way or function in Python that could achieve the opposite effect of <code>any(iterable)</code>? That is, if any <code>bool(element) is False</code> then return <code>True</code>, like the following example:</p>
<pre><code>>>> l = [True, False, True]
>>> any_false(l)
>>> True
</code></pre>
| 56 | 2016-08-10T09:19:40Z | 38,869,246 | <p>There is also the <code>all</code> function which does the opposite of what you want, it returns <code>True</code> if all are <code>True</code> and <code>False</code> if any are <code>False</code>. Therefore you can just do:</p>
<pre><code>not all(l)
</code></pre>
| 102 | 2016-08-10T09:23:14Z | [
"python",
"python-3.x",
"iterable"
] |
Îpposite of any() function | 38,869,155 | <p>The Python built-in function <code>any(iterable)</code> can help to quickly check if any <code>bool(element)</code> is <code>True</code> in a iterable type.</p>
<pre><code>>>> l = [None, False, 0]
>>> any(l)
False
>>> l = [None, 1, 0]
>>> any(l)
True
</code></pre>
<p>But is there an elegant way or function in Python that could achieve the opposite effect of <code>any(iterable)</code>? That is, if any <code>bool(element) is False</code> then return <code>True</code>, like the following example:</p>
<pre><code>>>> l = [True, False, True]
>>> any_false(l)
>>> True
</code></pre>
| 56 | 2016-08-10T09:19:40Z | 38,870,927 | <p>Well, the implementation of <code>any</code> is <a href="https://docs.python.org/3/library/functions.html#any"><em>equivalent</em></a> to:</p>
<pre><code>def any(iterable):
for element in iterable:
if element:
return True
return False
</code></pre>
<p>So, just switch the condition from <code>if element</code> to <code>if not element</code>:</p>
<pre><code>def reverse_any(iterable):
for element in iterable:
if not element:
return True
return False
</code></pre>
<p>Yes, <em>of course</em> this doesn't leverage the speed of the built-ins <code>any</code> or <code>all</code> like the other answers do, but it's a nice readable alternative.</p>
| 14 | 2016-08-10T10:33:00Z | [
"python",
"python-3.x",
"iterable"
] |
Îpposite of any() function | 38,869,155 | <p>The Python built-in function <code>any(iterable)</code> can help to quickly check if any <code>bool(element)</code> is <code>True</code> in a iterable type.</p>
<pre><code>>>> l = [None, False, 0]
>>> any(l)
False
>>> l = [None, 1, 0]
>>> any(l)
True
</code></pre>
<p>But is there an elegant way or function in Python that could achieve the opposite effect of <code>any(iterable)</code>? That is, if any <code>bool(element) is False</code> then return <code>True</code>, like the following example:</p>
<pre><code>>>> l = [True, False, True]
>>> any_false(l)
>>> True
</code></pre>
| 56 | 2016-08-10T09:19:40Z | 38,884,821 | <p>You can do:</p>
<pre><code>>>> l = [True, False, True]
>>> False in map(bool, l)
True
</code></pre>
<p>Recall that <code>map</code> in Python 3 is a generator. For Python 2, you probably want to use <code>imap</code> </p>
<hr>
<p>Mea Culpa: After timing these, the method I offered is hands down <strong>the slowest</strong></p>
<p>The fastest is <code>not all(l)</code> or <code>not next(filterfalse(bool, it), True)</code> which is just a silly itertools variant. Use Jack Aidleys <a href="http://stackoverflow.com/a/38869246/298607">solution</a>.</p>
<p>Timing code:</p>
<pre><code>from itertools import filterfalse
def af1(it):
return not all(it)
def af2(it):
return any(not i for i in it)
def af3(iterable):
for element in iterable:
if not element:
return True
return False
def af4(it):
return False in map(bool, it)
def af5(it):
return not next(filterfalse(bool, it), True)
if __name__=='__main__':
import timeit
for i, l in enumerate([[True]*1000+[False]+[True]*999, # False in the middle
[False]*2000, # all False
[True]*2000], # all True
start=1):
print("case:", i)
for f in (af1, af2, af3, af4, af5):
print(" ",f.__name__, timeit.timeit("f(l)", setup="from __main__ import f, l", number=100000), f(l) )
</code></pre>
<p>Results:</p>
<pre><code>case: 1
af1 0.45357259700540453 True
af2 4.538436588976765 True
af3 1.2491040650056675 True
af4 8.935278153978288 True
af5 0.4685744970047381 True
case: 2
af1 0.016299808979965746 True
af2 0.04787631600629538 True
af3 0.015038023004308343 True
af4 0.03326922300038859 True
af5 0.029870904982089996 True
case: 3
af1 0.8545824179891497 False
af2 8.786235476000002 False
af3 2.448748088994762 False
af4 17.90895140200155 False
af5 0.9152941330103204 False
</code></pre>
| 9 | 2016-08-10T22:52:17Z | [
"python",
"python-3.x",
"iterable"
] |
Why is condition.notify_all wakes only one waiter? | 38,869,205 | <p>I've tried to create a python async version of java's <code>CountDownLatch</code></p>
<pre><code>class CountDownLatch:
def __init__(self, count=1):
if count == 0:
raise ValueError('count should be more than zero')
self.count = count
self.countdown_over = aio.Condition()
async def countdown(self):
with await self.countdown_over:
print('decrementing counter')
self.count -= 1
print('count {}'.format(self.count))
if self.count == 0:
print('count is zero no more waiting')
await aio.sleep(1)
self.countdown_over.notify_all()
async def wait(self):
with await self.countdown_over:
await self.countdown_over.wait()
</code></pre>
<p>Now I'm trying it.</p>
<pre><code>In [2]: async def g(latch):
...: await latch.wait()
...: print('g')
...:
In [3]: async def f(latch):
...: print('counting down')
...: await latch.countdown()
...: await g(latch)
...:
In [4]: def run():
...: latch = CountDownLatch(2)
...: loop = aio.get_event_loop()
...: loop.run_until_complete(aio.wait((f(latch), f(latch))))
...:
In [5]: import asyncio as aio
In [6]: from new.tests.test_turnovers import CountDownLatch
</code></pre>
<p>And here's the output</p>
<pre><code>counting down
decrementing counter
count 1
counting down
decrementing counter
count 0
count is zero no more waiting
g
</code></pre>
<p>I can't understand what I'm doing wrong here. The counter is created and decremented just fine. One coroutine even is notified and proceeded with it's task, but the second one is not for some reason.</p>
| 0 | 2016-08-10T09:21:25Z | 38,891,331 | <p>Let <code>f1</code> be <code>f</code> called as the first one and let <code>f2</code> be <code>f</code> called as the second. The thing that should be noted is that even though you've used <code>async</code> keyword <code>f</code> function is <strong>synchronous</strong> until it hits <code>latch.wait()</code>. So we can actually easily debug what's going on:</p>
<ol>
<li><code>f1</code> fires.</li>
<li><code>count</code> is decreased by <code>1</code></li>
<li><code>f1</code> enters <code>await self.countdown_over.wait()</code> and <em>context switch</em> happens</li>
<li><code>f2</code> fires</li>
<li><code>count</code> is decreased by <code>1</code>, <code>f2</code> enters <code>if</code> condition</li>
<li><code>self.countdown_over.notify_all()</code> fires. All waiters are notified (note that at that point it is only <code>f1</code>).</li>
<li><code>f2</code> enters <code>await self.countdown_over.wait()</code> and <em>context switch</em> happens</li>
<li><code>f1</code> wakes up and leaves <code>.wait()</code> call</li>
</ol>
<p>Note that step 7 happens <strong>after</strong> step 6. Thus <code>f2</code> is never notified. </p>
<p>Generally if you have multiple (green or not) threads that do notify and wait (in this order, synchronously) then at least one of them will always fail to proceed.</p>
| 1 | 2016-08-11T08:38:32Z | [
"python",
"coroutine",
"python-asyncio"
] |
How to get time from Properties | 38,869,256 | <p>My python script:</p>
<pre><code>import ftplib
import hashlib
import httplib
import pytz
import datetime
import urllib
import os
import glob
def ftphttp():
localtime = datetime.datetime.now(tz=pytz.utc).isoformat()
cam = "002"
lscam = localtime + cam
ftp = ftplib.FTP('localhost','kevin403','S$ip1234')
ftp.cwd('/var/www/html/image')
m=hashlib.md5()
m.update(lscam)
dd=m.hexdigest()
for image in glob.glob(os.path.join('Desktop/images/*.png')):
with open(image, 'rb') as file:
ftp.storbinary('STOR '+dd+ '.png', file)
x = httplib.HTTPConnection('localhost', 8086)
x.connect()
f = {'ts' : localtime}
x.request('GET','/camera/store?cam='+cam+'&'+urllib.urlencode(f)+'&fn='+dd)
y = x.getresponse()
z=y.read()
x.close()
ftp.quit()
</code></pre>
<p>I wanted to get the time from the file properties because i do not want it from the time that i send. Anybody can help me with this?</p>
| 0 | 2016-08-10T09:23:46Z | 38,893,497 | <p>@Alvin, You cannot get <strong>ISOdatetime</strong> from <em>getmtime</em> directly, if you want to convert the output date from <em>getmtime</em>, you can do it in following manner:</p>
<pre><code>import os.path, time
from datetime import datetime
from pytz import timezone
import pytz
ts = os.path.getmtime(file_path)
dt = datetime.fromtimestamp(ts, pytz.utc)
timeZone= timezone('supported_timezone')
#converting the timestamp in ISOdatetime format
dt.astimezone(timeZone).isoformat()
</code></pre>
<p>Output e.g.: '2016-02-16T23:32:06.260088-05:00' for 'US/Eastern' timezone</p>
| 0 | 2016-08-11T10:15:05Z | [
"python",
"python-2.7"
] |
Flask, and valid json - ValueError: dictionary update sequence element #0 has length 3; 2 is required | 38,869,273 | <p>Here is my flask code using restful.</p>
<pre><code>def get(self):
data = [{"id": "2", "lags": [{"id": "GBPQ1"}, {"id": "GBPQ2"},{"id": "GBPQ3"}, {"id": "BPQ4"}], "name": "GBP"}]
return jsonify(data)
</code></pre>
<p>Here is my error: Why? Its valid json per jsoinlint. How do I resolve?</p>
<p>curl <a href="http://0.0.0.0:5000/test/model/exposure/currencies/" rel="nofollow">http://0.0.0.0:5000/test/model/exposure/currencies/</a></p>
<pre><code>curl http://0.0.0.0:5000/test/model/exposure/currencies/111111
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>ValueError: dictionary update sequence element #0 has length 3; 2 is required // Werkzeug Debugger</title>
<link rel="stylesheet" href="?__debugger__=yes&amp;cmd=resource&amp;f=style.css" type="text/css">
<!-- We need to make sure this has a favicon so that the debugger does not by
accident trigger a request to /favicon.ico which might change the application
state. -->
<link rel="shortcut icon" href="?__debugger__=yes&amp;cmd=resource&amp;f=console.png">
<script type="text/javascript" src="?__debugger__=yes&amp;cmd=resource&amp;f=jquery.js"></script>
<script type="text/javascript" src="?__debugger__=yes&amp;cmd=resource&amp;f=debugger.js"></script>
<script type="text/javascript">
var TRACEBACK = 140493007176848,
CONSOLE_MODE = false,
EVALEX = true,
SECRET = "hIZ55a7qO5d1PpF7ILd6";
</script>
</head>
<body>
<div class="debugger">
<h1>ValueError</h1>
<div class="detail">
<p class="errormsg">ValueError: dictionary update sequence element #0 has length 3; 2 is required</p>
</div>
<h2 class="traceback">Traceback <em>(most recent call last)</em></h2>
<div class="traceback">
<ul><li><div class="frame" id="frame-140493007176784">
<h4>File <cite class="filename">"/usr/local/lib/python2.7/dist-packages/flask/app.py"</cite>,
line <em class="line">1836</em>,
in <code class="function">__call__</code></h4>
<pre>return self.wsgi_app(environ, start_response)</pre>
</div>
<li><div class="frame" id="frame-140493007177104">
<h4>File <cite class="filename">"/usr/local/lib/python2.7/dist-packages/flask/app.py"</cite>,
line <em class="line">1820</em>,
in <code class="function">wsgi_app</code></h4>
<pre>response = self.make_response(self.handle_exception(e))</pre>
</div>
<li><div class="frame" id="frame-140493007177168">
<h4>File <cite class="filename">"/usr/local/lib/python2.7/dist-packages/Flask_RESTful-0.3.5-py2.7.egg/flask_restful/__init__.py"</cite>,
line <em class="line">271</em>,
in <code class="function">error_router</code></h4>
<pre>return original_handler(e)</pre>
</div>
<li><div class="frame" id="frame-140493007176912">
<h4>File <cite class="filename">"/usr/local/lib/python2.7/dist-packages/Flask_RESTful-0.3.5-py2.7.egg/flask_restful/__init__.py"</cite>,
line <em class="line">271</em>,
in <code class="function">error_router</code></h4>
<pre>return original_handler(e)</pre>
</div>
<li><div class="frame" id="frame-140493007176976">
<h4>File <cite class="filename">"/usr/local/lib/python2.7/dist-packages/flask_cors/extension.py"</cite>,
line <em class="line">188</em>,
in <code class="function">wrapped_function</code></h4>
<pre>return cors_after_request(app.make_response(f(*args, **kwargs)))</pre>
</div>
<li><div class="frame" id="frame-140493007177296">
<h4>File <cite class="filename">"/usr/local/lib/python2.7/dist-packages/flask/app.py"</cite>,
line <em class="line">1403</em>,
in <code class="function">handle_exception</code></h4>
<pre>reraise(exc_type, exc_value, tb)</pre>
</div>
<li><div class="frame" id="frame-140493007177424">
<h4>File <cite class="filename">"/usr/local/lib/python2.7/dist-packages/Flask_RESTful-0.3.5-py2.7.egg/flask_restful/__init__.py"</cite>,
line <em class="line">268</em>,
in <code class="function">error_router</code></h4>
<pre>return self.handle_error(e)</pre>
</div>
<li><div class="frame" id="frame-140493007177360">
<h4>File <cite class="filename">"/usr/local/lib/python2.7/dist-packages/flask/app.py"</cite>,
line <em class="line">1817</em>,
in <code class="function">wsgi_app</code></h4>
<pre>response = self.full_dispatch_request()</pre>
</div>
<li><div class="frame" id="frame-140493007177552">
<h4>File <cite class="filename">"/usr/local/lib/python2.7/dist-packages/flask/app.py"</cite>,
line <em class="line">1477</em>,
in <code class="function">full_dispatch_request</code></h4>
<pre>rv = self.handle_user_exception(e)</pre>
</div>
<li><div class="frame" id="frame-140493007177616">
<h4>File <cite class="filename">"/usr/local/lib/python2.7/dist-packages/Flask_RESTful-0.3.5-py2.7.egg/flask_restful/__init__.py"</cite>,
line <em class="line">271</em>,
in <code class="function">error_router</code></h4>
<pre>return original_handler(e)</pre>
</div>
<li><div class="frame" id="frame-140493007177232">
<h4>File <cite class="filename">"/usr/local/lib/python2.7/dist-packages/Flask_RESTful-0.3.5-py2.7.egg/flask_restful/__init__.py"</cite>,
line <em class="line">271</em>,
in <code class="function">error_router</code></h4>
<pre>return original_handler(e)</pre>
</div>
<li><div class="frame" id="frame-140493007177488">
<h4>File <cite class="filename">"/usr/local/lib/python2.7/dist-packages/flask_cors/extension.py"</cite>,
line <em class="line">188</em>,
in <code class="function">wrapped_function</code></h4>
<pre>return cors_after_request(app.make_response(f(*args, **kwargs)))</pre>
</div>
<li><div class="frame" id="frame-140493007177744">
<h4>File <cite class="filename">"/usr/local/lib/python2.7/dist-packages/flask/app.py"</cite>,
line <em class="line">1381</em>,
in <code class="function">handle_user_exception</code></h4>
<pre>reraise(exc_type, exc_value, tb)</pre>
</div>
<li><div class="frame" id="frame-140493007177872">
<h4>File <cite class="filename">"/usr/local/lib/python2.7/dist-packages/Flask_RESTful-0.3.5-py2.7.egg/flask_restful/__init__.py"</cite>,
line <em class="line">268</em>,
in <code class="function">error_router</code></h4>
<pre>return self.handle_error(e)</pre>
</div>
<li><div class="frame" id="frame-140493007177808">
<h4>File <cite class="filename">"/usr/local/lib/python2.7/dist-packages/flask/app.py"</cite>,
line <em class="line">1475</em>,
in <code class="function">full_dispatch_request</code></h4>
<pre>rv = self.dispatch_request()</pre>
</div>
<li><div class="frame" id="frame-140493007178000">
<h4>File <cite class="filename">"/usr/local/lib/python2.7/dist-packages/flask/app.py"</cite>,
line <em class="line">1461</em>,
in <code class="function">dispatch_request</code></h4>
<pre>return self.view_functions[rule.endpoint](**req.view_args)</pre>
</div>
<li><div class="frame" id="frame-140493007178064">
<h4>File <cite class="filename">"/usr/local/lib/python2.7/dist-packages/Flask_RESTful-0.3.5-py2.7.egg/flask_restful/__init__.py"</cite>,
line <em class="line">477</em>,
in <code class="function">wrapper</code></h4>
<pre>resp = resource(*args, **kwargs)</pre>
</div>
<li><div class="frame" id="frame-140493007177680">
<h4>File <cite class="filename">"/usr/local/lib/python2.7/dist-packages/flask/views.py"</cite>,
line <em class="line">84</em>,
in <code class="function">view</code></h4>
<pre>return self.dispatch_request(*args, **kwargs)</pre>
</div>
<li><div class="frame" id="frame-140493007177936">
<h4>File <cite class="filename">"/usr/local/lib/python2.7/dist-packages/Flask_RESTful-0.3.5-py2.7.egg/flask_restful/__init__.py"</cite>,
line <em class="line">587</em>,
in <code class="function">dispatch_request</code></h4>
<pre>resp = meth(*args, **kwargs)</pre>
</div>
<li><div class="frame" id="frame-140493007178128">
<h4>File <cite class="filename">"/home/ubuntu/workspace/qtaapi/qtaapi/resources/model_exposure_currencies.py"</cite>,
line <em class="line">198</em>,
in <code class="function">get</code></h4>
<pre>return jsonify(data)</pre>
</div>
<li><div class="frame" id="frame-140493007178192">
<h4>File <cite class="filename">"/usr/local/lib/python2.7/dist-packages/flask/json.py"</cite>,
line <em class="line">237</em>,
in <code class="function">jsonify</code></h4>
<pre>return current_app.response_class(dumps(dict(*args, **kwargs),</pre>
</div>
</ul>
<blockquote>ValueError: dictionary update sequence element #0 has length 3; 2 is required</blockquote>
</div>
<div class="plain">
<form action="/?__debugger__=yes&amp;cmd=paste" method="post">
<p>
<input type="hidden" name="language" value="pytb">
This is the Copy/Paste friendly version of the traceback. <span
class="pastemessage">You can also paste this traceback into
a <a href="https://gist.github.com/">gist</a>:
<input type="submit" value="create paste"></span>
</p>
<textarea cols="50" rows="10" name="code" readonly>Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1836, in __call__
return self.wsgi_app(environ, start_response)
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1820, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "/usr/local/lib/python2.7/dist-packages/Flask_RESTful-0.3.5-py2.7.egg/flask_restful/__init__.py", line 271, in error_router
return original_handler(e)
File "/usr/local/lib/python2.7/dist-packages/Flask_RESTful-0.3.5-py2.7.egg/flask_restful/__init__.py", line 271, in error_router
return original_handler(e)
File "/usr/local/lib/python2.7/dist-packages/flask_cors/extension.py", line 188, in wrapped_function
return cors_after_request(app.make_response(f(*args, **kwargs)))
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1403, in handle_exception
reraise(exc_type, exc_value, tb)
File "/usr/local/lib/python2.7/dist-packages/Flask_RESTful-0.3.5-py2.7.egg/flask_restful/__init__.py", line 268, in error_router
return self.handle_error(e)
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1817, in wsgi_app
response = self.full_dispatch_request()
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1477, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/usr/local/lib/python2.7/dist-packages/Flask_RESTful-0.3.5-py2.7.egg/flask_restful/__init__.py", line 271, in error_router
return original_handler(e)
File "/usr/local/lib/python2.7/dist-packages/Flask_RESTful-0.3.5-py2.7.egg/flask_restful/__init__.py", line 271, in error_router
return original_handler(e)
File "/usr/local/lib/python2.7/dist-packages/flask_cors/extension.py", line 188, in wrapped_function
return cors_after_request(app.make_response(f(*args, **kwargs)))
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1381, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/usr/local/lib/python2.7/dist-packages/Flask_RESTful-0.3.5-py2.7.egg/flask_restful/__init__.py", line 268, in error_router
return self.handle_error(e)
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1475, in full_dispatch_request
rv = self.dispatch_request()
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1461, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/usr/local/lib/python2.7/dist-packages/Flask_RESTful-0.3.5-py2.7.egg/flask_restful/__init__.py", line 477, in wrapper
resp = resource(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/flask/views.py", line 84, in view
return self.dispatch_request(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/Flask_RESTful-0.3.5-py2.7.egg/flask_restful/__init__.py", line 587, in dispatch_request
resp = meth(*args, **kwargs)
File "/home/ubuntu/workspace/qtaapi/qtaapi/resources/model_exposure_currencies.py", line 198, in get
return jsonify(data)
File "/usr/local/lib/python2.7/dist-packages/flask/json.py", line 237, in jsonify
return current_app.response_class(dumps(dict(*args, **kwargs),
ValueError: dictionary update sequence element #0 has length 3; 2 is required</textarea>
</form>
</div>
<div class="explanation">
The debugger caught an exception in your WSGI application. You can now
look at the traceback which led to the error. <span class="nojavascript">
If you enable JavaScript you can also use additional features such as code
execution (if the evalex feature is enabled), automatic pasting of the
exceptions and much more.</span>
</div>
<div class="footer">
Brought to you by <strong class="arthur">DON'T PANIC</strong>, your
friendly Werkzeug powered traceback interpreter.
</div>
</div>
</body>
</html>
<!--
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1836, in __call__
return self.wsgi_app(environ, start_response)
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1820, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "/usr/local/lib/python2.7/dist-packages/Flask_RESTful-0.3.5-py2.7.egg/flask_restful/__init__.py", line 271, in error_router
return original_handler(e)
File "/usr/local/lib/python2.7/dist-packages/Flask_RESTful-0.3.5-py2.7.egg/flask_restful/__init__.py", line 271, in error_router
return original_handler(e)
File "/usr/local/lib/python2.7/dist-packages/flask_cors/extension.py", line 188, in wrapped_function
return cors_after_request(app.make_response(f(*args, **kwargs)))
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1403, in handle_exception
reraise(exc_type, exc_value, tb)
File "/usr/local/lib/python2.7/dist-packages/Flask_RESTful-0.3.5-py2.7.egg/flask_restful/__init__.py", line 268, in error_router
return self.handle_error(e)
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1817, in wsgi_app
response = self.full_dispatch_request()
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1477, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/usr/local/lib/python2.7/dist-packages/Flask_RESTful-0.3.5-py2.7.egg/flask_restful/__init__.py", line 271, in error_router
return original_handler(e)
File "/usr/local/lib/python2.7/dist-packages/Flask_RESTful-0.3.5-py2.7.egg/flask_restful/__init__.py", line 271, in error_router
return original_handler(e)
File "/usr/local/lib/python2.7/dist-packages/flask_cors/extension.py", line 188, in wrapped_function
return cors_after_request(app.make_response(f(*args, **kwargs)))
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1381, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/usr/local/lib/python2.7/dist-packages/Flask_RESTful-0.3.5-py2.7.egg/flask_restful/__init__.py", line 268, in error_router
return self.handle_error(e)
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1475, in full_dispatch_request
rv = self.dispatch_request()
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1461, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/usr/local/lib/python2.7/dist-packages/Flask_RESTful-0.3.5-py2.7.egg/flask_restful/__init__.py", line 477, in wrapper
resp = resource(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/flask/views.py", line 84, in view
return self.dispatch_request(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/Flask_RESTful-0.3.5-py2.7.egg/flask_restful/__init__.py", line 587, in dispatch_request
resp = meth(*args, **kwargs)
File "/home/ubuntu/workspace/qtaapi/qtaapi/resources/model_exposure_currencies.py", line 198, in get
return jsonify(data)
File "/usr/local/lib/python2.7/dist-packages/flask/json.py", line 237, in jsonify
return current_app.response_class(dumps(dict(*args, **kwargs),
ValueError: dictionary update sequence element #0 has length 3; 2 is required
-->
ubuntu@ubuntu:~/.ssh$
</code></pre>
| 0 | 2016-08-10T09:24:41Z | 38,869,493 | <p>Try to give a dictionary to jsonify :</p>
<pre><code>def get(self):
data = [{"id": "2", "lags": [{"id": "GBPQ1"}, {"id": "GBPQ2"},{"id": "GBPQ3"}, {"id": "BPQ4"}], "name": "GBP"}]
return jsonify({'data': data})
</code></pre>
<p>Or you can also do that if you prefer: <code>return jsonify(data=data)</code></p>
| 0 | 2016-08-10T09:33:15Z | [
"python",
"flask"
] |
Store database query result in an object in Python 3 | 38,869,356 | <p>In my python application I run a query which returns me a <strong>product</strong> from my product table. When I get the result and assign it in a variable, it is stored in a <strong>list</strong>. But I want to create a <strong>product class</strong> and want to store query result in an object of my product class which matches with my database table.</p>
<p>But I dont want to do it in this way which is one by one getting values from list and setting object variables and so on. </p>
<p>I want to do this because my database table is large and list does not store variable's field names. It comes like following; so I cant use something like this; <code>getProductName()</code></p>
<pre><code>[5,"strawberry",011023234,10.5]
</code></pre>
<p>so I should remember in which position my product barcode code is stored when it is needed.</p>
<p>Retrieve data from database;</p>
<pre><code>vt = sqlite3.connect("vt.sqlite")
im = vt.cursor()
im.execute("SELECT * FROM Products WHERE barcode='{}'".format(barcode))
veriler = im.fetchall()
</code></pre>
<p>Here is <code>veriler = [5,"starberry",001]</code>. </p>
<p>My database table will be large. Then my veriler will be a long list.</p>
<p>When I want to get some attribute of retrieved data I have to access it like veriler[0], veriler[25] etc. I should remember indexes for each attribute.</p>
<p>Is it possible if I had product class which has all attributes in my database table and create a product object and when I assigned the database result to my product object I have set all attributes in product object and can access attributes of my product object using get methods. </p>
<p>Thanks in advance.</p>
| 0 | 2016-08-10T09:28:15Z | 38,871,880 | <p>Okay I think found out how to do it with some more searching.</p>
<p>Not sure it is the best way but it worked for me. </p>
<p><a href="http://stackoverflow.com/a/3287775/5528870">Convert database result into json</a> and than <a href="http://stackoverflow.com/a/15882054/5528870">convert json to python object.</a></p>
| 0 | 2016-08-10T11:13:30Z | [
"python",
"database",
"sqlite",
"python-3.x"
] |
Pandas: replace values in strings | 38,869,372 | <p>I have data frame and I try to replace it from other df</p>
<p>I use:</p>
<pre><code>df['term_code'] = df.search_term.map(rep_term.set_index('search_term')['code_action'])
</code></pre>
<p>But I get an error:</p>
<pre><code>File "C:/Users/����� �����������/Desktop/projects/find_time_before_buy/graph (2).py", line 36, in <module>
df['term_code'] = df.search_term.map(rep_term.set_index('search_term')['code_action'])
File "C:\Python27\lib\site-packages\pandas\core\series.py", line 2101, in map
indexer = arg.index.get_indexer(values)
File "C:\Python27\lib\site-packages\pandas\indexes\base.py", line 2082, in get_indexer
raise InvalidIndexError('Reindexing only valid with uniquely'
pandas.indexes.base.InvalidIndexError: Reindexing only valid with uniquely valued Index objects
</code></pre>
<p>What should I change?
Where <code>search_term</code> is</p>
<pre><code>729948 None
729949 None
729950 None
729951 панÑÐ¸Ð¾Ð½Ð°Ñ Ð´Ð¶ÐµÐ¼ÐµÑе оÑдÑÑ
2016 ÑенÑ
729952 None
729953 None
729954 кÑпиÑÑ ÑелеÑон
729955 None
729956 вк
729957 None
729958 ÑндекÑ
</code></pre>
<p>And <code>rep_term</code> looks like</p>
<pre><code>search_term code_action
авиÑо 6
вк 9
ÑÐ½Ð´ÐµÐºÑ 12
мÑÑ 7
ÑвÑзной 8
ÑиÑилинк 8
</code></pre>
| 4 | 2016-08-10T09:28:53Z | 38,869,500 | <p>There is problem with duplicates in <code>DataFrame</code> <code>rep_term</code> column <code>search_term</code>.</p>
<p>I simulate it:</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'search_term':[1,2,3]})
print (df)
search_term
0 1
1 2
2 3
</code></pre>
<p>For value <code>1</code> in <code>search_term</code> you have <code>2</code> values in <code>code_action</code>:</p>
<pre><code>rep_term = pd.DataFrame({'search_term':[1,2,1], 'code_action':['ss','dd','gg']})
print (rep_term)
code_action search_term
0 ss 1
1 dd 2
2 gg 1
df['term_code'] = df.search_term.map(rep_term.set_index('search_term')['code_action'])
print (df)
#InvalidIndexError: Reindexing only valid with uniquely valued Index objects
</code></pre>
<p>So first identify rows where are duplicated vaues by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.duplicated.html" rel="nofollow"><code>duplicated</code></a>:</p>
<pre><code>print (rep_term[rep_term.duplicated(subset=['search_term'], keep=False)])
code_action search_term
0 ss 1
2 gg 1
</code></pre>
<p>Then you can drop duplicity with keeping last or first values by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.drop_duplicates.html" rel="nofollow"><code>drop_duplicates</code></a></p>
<pre><code>rep_term1 = rep_term.drop_duplicates(subset=['search_term'], keep='first')
print (rep_term1)
code_action search_term
0 ss 1
1 dd 2
rep_term2 = rep_term.drop_duplicates(subset=['search_term'], keep='last')
print (rep_term2)
code_action search_term
1 dd 2
2 gg 1
</code></pre>
| 4 | 2016-08-10T09:33:40Z | [
"python",
"string",
"pandas",
"dataframe",
"duplicates"
] |
Python convert xml to list | 38,869,381 | <p>I have the following xml dataset:</p>
<pre><code><cnode desc="" name="xyz">
<pnode name="word1"/>
<pnode name="word2"/>
<pnode name="word3"/>
...
<cnode desc="" name="abc">
<pnode name="word4"/>
<pnode name="word5"/>
<pnode name="word6"/>
...
</code></pre>
<p>I want to get a list of all words after the name='xyz' and 'abc' respectively, e.g. xyz=[word1, word2, word3,...] and abc=[word4, word5, word6, ...]</p>
<p>I tried the follwing solution:</p>
<pre><code>import xml.etree.ElementTree as etree
xyz=[]
abc=[]
tree = etree.parse('data.xml')
root = tree.getroot()
for child in root:
words.append(child.findall(?!))
print(words)
</code></pre>
<p>But I can't figure out how to reference to the parent with name=xyz and then extract the words of the children.</p>
<p>Thanks for your help!!</p>
| 1 | 2016-08-10T09:29:24Z | 38,869,712 | <p>firstly you should fix your demo xml there is a missing close quote</p>
<p>I would use xpath</p>
<pre><code>from lxml import etree
tree = etree.parse('data.xml')
root = tree.getroot()
xyzpnodes = root.xpath(".//cnode[@name='xyz']/pnode")
xyz = [p.attrib["name"] for p in xyzpnodes]
print xyz
</code></pre>
| 0 | 2016-08-10T09:42:31Z | [
"python",
"xml",
"list"
] |
Python convert xml to list | 38,869,381 | <p>I have the following xml dataset:</p>
<pre><code><cnode desc="" name="xyz">
<pnode name="word1"/>
<pnode name="word2"/>
<pnode name="word3"/>
...
<cnode desc="" name="abc">
<pnode name="word4"/>
<pnode name="word5"/>
<pnode name="word6"/>
...
</code></pre>
<p>I want to get a list of all words after the name='xyz' and 'abc' respectively, e.g. xyz=[word1, word2, word3,...] and abc=[word4, word5, word6, ...]</p>
<p>I tried the follwing solution:</p>
<pre><code>import xml.etree.ElementTree as etree
xyz=[]
abc=[]
tree = etree.parse('data.xml')
root = tree.getroot()
for child in root:
words.append(child.findall(?!))
print(words)
</code></pre>
<p>But I can't figure out how to reference to the parent with name=xyz and then extract the words of the children.</p>
<p>Thanks for your help!!</p>
| 1 | 2016-08-10T09:29:24Z | 38,869,812 | <p>You can go for:</p>
<pre><code>string = """
<nodes>
<cnode desc="" name="xyz">
<pnode name="word1"/>
<pnode name="word2"/>
<pnode name="word3"/>
</cnode>
<cnode desc="" name="abc">
<pnode name="word4"/>
<pnode name="word5"/>
<pnode name="word6"/>
</cnode>
</nodes>
"""
import xml.etree.ElementTree as etree
xyz=[]
abc=[]
tree = etree.fromstring(string)
result = {}
for node in tree.findall('cnode'):
name = node.get('name')
if name not in result.items():
result[name] = []
for child in node.findall('pnode'):
child_name = child.get('name')
result[name].append(child_name)
print(result)
# {'xyz': ['word1', 'word2', 'word3'], 'abc': ['word4', 'word5', 'word6']}
</code></pre>
<p>This traverses the tree and child nodes and adds the corresponding values to the dict <code>result</code>.<br>
It is even possible shorter with the help of <code>zip</code>:</p>
<pre><code>result = dict(zip((cnode.get('name') for cnode in tree.findall('cnode')), \
[[pnode.get('name') for pnode in cnode.findall('pnode')] \
for cnode in tree.findall('cnode')]))
print(result)
</code></pre>
| 1 | 2016-08-10T09:46:43Z | [
"python",
"xml",
"list"
] |
Execution of a Python Script from PHP | 38,869,507 | <p>I am making an android application in which I am first uploading the image to the server and on the server side, I want to execute a Python script from PHP. But I am not getting any output. When I access the Python script from the command prompt and run <code>python TestCode.py</code> it runs successfully and gives the desired output. I'm running Python script from PHP using the following command:</p>
<p><code>$result = exec('/usr/bin/python /var/www/html/Source/TestCode.py');</code></p>
<p><code>echo $result</code></p>
<p>However, if I run a simple Python program from PHP it works.</p>
<p>PHP has the permissions to access and execute the file.</p>
<p>Is there something which I am missing here?</p>
| 1 | 2016-08-10T09:34:07Z | 38,869,610 | <pre><code>exec('/usr/bin/python /var/www/html/Source/TestCode.py', $output);
var_dump($output);
</code></pre>
<p>2nd Parameter of <a href="http://php.net/manual/en/function.exec.php" rel="nofollow">exec</a> will give output</p>
<p><strong>EDIT:</strong></p>
<pre><code>exec('/usr/bin/python /var/www/html/Source/TestCode.py 2>&1', $output);
</code></pre>
<p><code>2>&1</code> - redirecting <code>stderr</code> to <code>stdout</code>. Now in case of any error too, <code>$output</code> will be populated.</p>
| 3 | 2016-08-10T09:39:05Z | [
"php",
"python",
"linux",
"exec"
] |
Execution of a Python Script from PHP | 38,869,507 | <p>I am making an android application in which I am first uploading the image to the server and on the server side, I want to execute a Python script from PHP. But I am not getting any output. When I access the Python script from the command prompt and run <code>python TestCode.py</code> it runs successfully and gives the desired output. I'm running Python script from PHP using the following command:</p>
<p><code>$result = exec('/usr/bin/python /var/www/html/Source/TestCode.py');</code></p>
<p><code>echo $result</code></p>
<p>However, if I run a simple Python program from PHP it works.</p>
<p>PHP has the permissions to access and execute the file.</p>
<p>Is there something which I am missing here?</p>
| 1 | 2016-08-10T09:34:07Z | 38,870,240 | <ol>
<li><p>First Check your python PATH using "which python" command and check result is /usr/bin/python. </p></li>
<li><p>Check your "TestCode.py" if you have written #!/usr/bin/sh than replace it with #!/usr/bin/bash.</p></li>
<li><p>Than run these commands
exec('/usr/bin/python /var/www/html/Source/TestCode.py', $result);
echo $result</p></li>
</ol>
| 1 | 2016-08-10T10:04:38Z | [
"php",
"python",
"linux",
"exec"
] |
lxml xpath get text between two nested tables | 38,869,533 | <p>I have a html that has nested tables. I wish to find the text between a outside table and inside tables. I thought this is a classic question but so far hasn't find the answer. What I have come up with is
<code>tree.xpath(//p[not(ancestor-or-self::table)])</code>. But this isn't working but because all text descends from the outside table. Also just use <code>preceding::table</code> isn't enough because the text can surrounds the inside table.</p>
<p>For an conceptual example if a table looks liek this <code>[...text1...[inside table No.1]...text2...[inside table No.2]...text3...]</code>, how can I get the <code>text1/2/3</code> only without being contaminated by texts from the <code>inside tables No.1&2</code>. Maybe this is my thought, is it possible to build a concept of table layer via xpath, so I can tell lxml or other libraries that "Give me all text between layer 0 and 1"</p>
<p>Below is a simplified sample html file. In reality, the outside table may contains many nested tables but I just want the text between the most outside table and its 1st nested tables. Thanks folks!</p>
<pre><code><table>
<tr><td>
<p> text I want </p>
<div> they can be in different types of nodes </div>
<table>
<tr><td><p> unwanted text </p></td></tr>
<tr><td>
<table>
<tr><td><u> unwanted text</u></td></tr>
</table>
</td></tr>
</table>
<p> text I also want </p>
<div> as long as they're inside the root table and outside the first-level inside tables </div>
</td></tr>
<tr><td>
<u> they can be between the first-level inside tables </u>
<table>
</table>
</td></tr>
</table>
</code></pre>
<p>And it returns <code>["text I want", "they can be in different types of nodes", "text I also want", "as long as they're inside the root table and outside the first-level inside tables", "they can be between the first-level inside tables"]</code>.</p>
| 0 | 2016-08-10T09:35:26Z | 38,870,751 | <p>One of the XPaths that could do this, if the outer most table is the root element:</p>
<pre><code>/table/descendant::table[1]/preceding::p
</code></pre>
<p>Here, you traverse to the first descendant <code>table</code> of the outermost <code>table</code>, and then select all its preceding <code>p</code> elements.</p>
<p>If not, you will have to take a different approach of accessing the <code>p</code> elements in between the <code>tables</code>, may be using <code>generate-id()</code> function.</p>
| 1 | 2016-08-10T10:26:01Z | [
"python",
"xpath",
"nested",
"lxml"
] |
Replicate CKAN instance (installation from source) to another server | 38,869,682 | <p><strong>Problem:</strong> I would like to replicate a CKAN instance which has been installed from source to another server. The aim is that the new server will be used for staging any updates developed into the development server (CKAN is already installed there) and will be pushed to the productions server to update any functionality. I couldn't find any guidelines in the CKAN documentation on how to achieve the replication although there is extensive documentation on migrating to newer CKAN versions.</p>
<p><strong>Background:</strong> Ubuntu 14.04, CKAN 2.5.2b, PostgreSQL 9.4.6. I have customized some of the python functions which I would also like to preserve.</p>
<p>Any documentation, experiences, or workflows would be more than welcome.</p>
| 0 | 2016-08-10T09:41:37Z | 38,892,330 | <p>Maybe you can check this <a href="https://github.com/govro/datagovro/blob/master/provisioning/playbook.yml" rel="nofollow">Ansible playbook</a> that sets up a new installation from source. It's based on the original docs.</p>
| 0 | 2016-08-11T09:24:45Z | [
"python",
"postgresql",
"ckan"
] |
python tkinter.ttk combobox down event on mouseclick | 38,869,807 | <p>I do not find a correct answer to my issue, despite intense research and a rather simple problem.
All I would like to do, is my comboboxes drop down when clicked on by 'Button-1'. But regardless of what I code, the combos don't behave as I wish.</p>
<p>following I prepared a simple code to demonstrate my problem:</p>
<pre><code>from tkinter import *
import tkinter.ttk
def combo_events(evt):
if int(evt.type) is 4:
w = evt.widget
w.event_generate('<Down>')
root = Tk()
li = ('row 1', 'row 2', 'row 3')
combo1 = tkinter.ttk.Combobox(root, value=li)
combo2 = tkinter.ttk.Combobox(root, value=li)
combo1.bind('<Button-1>', combo_events)
combo2.bind('<Button-1>', combo_events)
combo1.pack()
combo2.pack()
root.mainloop()
</code></pre>
<p>Well, if I try this code, the combos do dropdown, but not as expected. So, I tried to add a bind of the 'FocusIn' event but that rather complicates the situation and inhibits a 'FocusOut' ...</p>
<p>Can any1 help me to achieve my goal?</p>
<p>ps: I know, that the combo will drop down by clicking on the frame of the widget, but to be more precise I would like to drop it, when clicking into it.</p>
<p>And by the way, where do I find a rather complete list of events a combobox can trigger?</p>
<p>thx for effort and answer.</p>
| 0 | 2016-08-10T09:46:30Z | 38,870,662 | <p>Why are you using <code>int(evt.type) is 4</code> instead of <code>int(evt.type) == 4</code> ?</p>
<p>Applying this change it works for me.</p>
<p><b>Edit 1</b></p>
<p>First of all, thank you for explaining to us what you really want to have. Did not expect this from your initial question.</p>
<p>If you want to override the editing behaviour it is time to dig a little deeper.</p>
<p>The widget you click into inside the combobox is an entry widget. What you can do now is to define when your event shall be fetched inside the event chain. Will apply code soon.</p>
<p><b> Edit 2 </b></p>
<p>To get it at the first mouse click:</p>
<p><code>w.event_generate('<Down>', when='head')</code></p>
<p>Why? Because default of Event Generate is to append the generated Event to the Event Chain (put it at its end, value = 'tail'). Changing to <code>when='head'</code> gives your desired behaviour.</p>
| 0 | 2016-08-10T10:22:46Z | [
"python",
"events",
"combobox",
"tkinter",
"ttk"
] |
How to redirect to a URL binding multi routes in Flask | 38,869,853 | <p>Flask code:</p>
<pre><code>@app.route('/debug')
@app.route('/debug/sample')
def debug():
pass
</code></pre>
<p>Jinja2 code:</p>
<pre><code>{{ url_for('app.debug') }}
</code></pre>
<p>How to control the real url that Jinja2 will redirect?</p>
| 1 | 2016-08-10T09:48:27Z | 38,875,100 | <p>Give each rule a different endpoint value. The default is the name of the decorated function, so both currently have the same name and the last registered takes precedence.</p>
<pre><code>@app.route('/debug/sample', endpoint='debug_sample')
@app.route('/debug')
def debug():
pass
</code></pre>
<pre><code>url_for('debug') # /debug
url_for('debug_sample') # /debug/sample
</code></pre>
| 2 | 2016-08-10T13:39:14Z | [
"python",
"flask"
] |
Get latest object with filter in django rest framework | 38,869,894 | <p>When I request GET through DRF API, I want to return the latest object.
I tried this one in views.py: </p>
<pre><code>class ListCreateNodeConfig(generics.ListCreateAPIView):
queryset = models.NodeConfig.objects.all()
serializer_class = serializers.NodeConfigSerializer
def get_queryset(self):
return self.queryset.filter(node_id=self.kwargs.get('node_pk')).latest('timestamp')
</code></pre>
<p>But it throws error: 'NodeConfig' object is not iterable</p>
<p>models.py</p>
<pre><code>class NodeConfig(models.Model):
node_id = models.ForeignKey(Node)
timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
record_interval = models.IntegerField(default=0)
lower_frequency = models.IntegerField(default=0)
upper_frequency = models.IntegerField(default=0)
</code></pre>
<p>How to fix it? </p>
<p>Any suggestions are appreciated. </p>
| 0 | 2016-08-10T09:50:28Z | 38,879,437 | <p>The porblem here ist the <code>latest()</code> method. This does not return a queryset but a single model instance. (like <code>get(...)</code>)</p>
<p>so use:</p>
<pre><code>def get_queryset(self):
return self.queryset.filter(node_id=self.kwargs.get('node_pk')).order_by('-timestamp')
</code></pre>
<p>So if you want to have an endpoint for a single object you must not use DRF <code>List*</code> views/mixins.<br>
The listviews assume you want to work with lists (=multiple objects). And so they rely on <code>queryset</code> resp. <code>get_queryset</code>. And a queryset should obviously be a queryset and not a model instance... </p>
<p>But there is also the <code>RetrieveAPIView</code> view included:</p>
<pre><code>from rest_framework.generics import RetrieveAPIView
class LatestNodeConfigView(RetrieveAPIView):
queryset = models.NodeConfig.objects.all()
# add your serializer
serializer_class = NodeConfigDetailSerializer
def get_object(self, *args, **kwargs):
return self.queryset.filter(node_id=kwargs.get('node_pk')).latest('timestamp')
</code></pre>
| 2 | 2016-08-10T16:58:11Z | [
"python",
"django",
"django-rest-framework"
] |
How to convert list of ints into list of lists? | 38,869,937 | <p>The problem is: how to convert properly (in "pythonic way") list of ints: <code>[1, 3, 7, 6]</code> into corresponding list of lists: <code>[[1], [3], [7], [6]]</code> with ints inside of them?</p>
<p>Tried to do it like: <code>unsorted_list = [list(str(x)) for x in unsorted_list]</code> but get <code>[['1'], ['3'], ['7'], ['6']]</code>. Don't know how to perform the same on ints, they are not iterable. Using <code>for</code> afterwards can solve the problem, but not so elegant.
Thank you.</p>
| 1 | 2016-08-10T09:52:34Z | 38,869,989 | <p>us like this</p>
<pre><code>unsorted_list = [[x] for x in unsorted_list]
</code></pre>
<p>or you can use:</p>
<pre><code>unsorted_list = map(lambda x:[x], unsorted_list)
</code></pre>
| -2 | 2016-08-10T09:54:54Z | [
"python",
"list"
] |
How to convert list of ints into list of lists? | 38,869,937 | <p>The problem is: how to convert properly (in "pythonic way") list of ints: <code>[1, 3, 7, 6]</code> into corresponding list of lists: <code>[[1], [3], [7], [6]]</code> with ints inside of them?</p>
<p>Tried to do it like: <code>unsorted_list = [list(str(x)) for x in unsorted_list]</code> but get <code>[['1'], ['3'], ['7'], ['6']]</code>. Don't know how to perform the same on ints, they are not iterable. Using <code>for</code> afterwards can solve the problem, but not so elegant.
Thank you.</p>
| 1 | 2016-08-10T09:52:34Z | 38,870,013 | <p>You shouldn't transform the integers to strings. Simply:</p>
<pre><code>[[x] for x in unsorted_list]
</code></pre>
| 5 | 2016-08-10T09:56:15Z | [
"python",
"list"
] |
How to convert list of ints into list of lists? | 38,869,937 | <p>The problem is: how to convert properly (in "pythonic way") list of ints: <code>[1, 3, 7, 6]</code> into corresponding list of lists: <code>[[1], [3], [7], [6]]</code> with ints inside of them?</p>
<p>Tried to do it like: <code>unsorted_list = [list(str(x)) for x in unsorted_list]</code> but get <code>[['1'], ['3'], ['7'], ['6']]</code>. Don't know how to perform the same on ints, they are not iterable. Using <code>for</code> afterwards can solve the problem, but not so elegant.
Thank you.</p>
| 1 | 2016-08-10T09:52:34Z | 38,870,050 | <p>Another aproach, using <code>map</code>:</p>
<pre><code>map(lambda x: [x], unsorted_list)
</code></pre>
| 1 | 2016-08-10T09:57:50Z | [
"python",
"list"
] |
Consuming from multiple queues at once with aioamqp | 38,869,959 | <p>Is it possible to consume multiple queues at once using one channel with aioamqp?</p>
<p>Disclaimer: I created an <a href="https://github.com/Polyconseil/aioamqp/issues/105" rel="nofollow">issue</a> in the project issue tracker but I'm really wondering if what I'm doing makes sense at all.</p>
| 0 | 2016-08-10T09:53:34Z | 38,870,898 | <p><s>I think that this feature is not available in AMQP protocol (assuming my understanding of the protocol is correct).</p>
<p>If you wish to consume from a queue you have to issue <code>basic.consume</code> call on a channel. The required argument for this call is <code>queue_name</code> and it's a "blocking" (not blocking a connection but blocking a channel) call where response is an object from the queue.</p>
<p>Long story short: each consumer has to have an exclusive access to a channel while it's waiting for queue objects.</s></p>
<p>OK, so my initial thought was incorrect. After digging into <a href="https://www.amqp.org/resources/specifications" rel="nofollow">AMQP</a> I found out that it actually does support multiple consumers over one channel. However it does allow servers to set their limits if desired. Unfortunately I couldn't find any info about RabbitMQ specific case. So I assume that there is no such limit. All in all: this is an issue with the library.</p>
<p>However the workaround is still valid: just create a channel per consumer. It should work just fine.</p>
| 1 | 2016-08-10T10:31:46Z | [
"python",
"rabbitmq",
"python-asyncio"
] |
Why object is taking last value in list? | 38,870,007 | <p>Why object is taking last value in list </p>
<pre><code>ddd = [1,2]
master_list = []
for ridx in range(1):
row_list = [] ; row_data = {} ; header_dic = {} ;
header_dic['background-color'] = 'green'
row_list.append(header_dic)
for metric_id in range(2):
row_data['background-color'] = ddd[metric_id]
row_list.append(row_data)
master_list.append(row_list)
print(master_list)
</code></pre>
<p>Output coming :</p>
<pre><code>[[{'background-color': 'green'}, {'background-color': 2}, {'background-color': 2}]]
</code></pre>
<p>Expected output :</p>
<pre><code>[[{'background-color': 'green'}, {'background-color': 1}, {'background-color': 2}]]
</code></pre>
| 1 | 2016-08-10T09:55:34Z | 38,870,149 | <p>Just move row_data in inner loop.</p>
<pre><code>ddd = [1,2]
master_list = []
for ridx in range(1):
row_list = [] ; header_dic = {} ;
header_dic['background-color'] = 'green'
row_list.append(header_dic)
for metric_id in range(2):
row_data = {}
row_data['background-color'] = ddd[metric_id]
row_list.append(row_data)
master_list.append(row_list)
print(master_list)
</code></pre>
<p>And you will get the expected output:</p>
<pre><code>[[{'background-color': 'green'}, {'background-color': 1}, {'background-color': 2}]]
</code></pre>
| 0 | 2016-08-10T10:01:39Z | [
"python",
"list",
"loops",
"dictionary"
] |
update matrix values in python | 38,870,039 | <p>I need to update matrix values with elements in list. When i use for loop to iterate the index of matrix and include the elements in list. only the last value is updated as it is the last value of the iterator.</p>
<p>But i need the sequence of the list to be added in the matrix.
please let me know if there could be any possibilities to do this..</p>
<pre><code> >>> n
[0, 1, 2, 3]
>>> for i in range(len(m)):
for j in range(len(m)):
for k in range(len(n)):
m[i][j]=n[k]
>>> m
array([[ 3., 3.],
[ 3., 3.]])
</code></pre>
| 0 | 2016-08-10T09:57:23Z | 38,870,299 | <p>In the most inside loop:</p>
<pre><code> for k in range(len(n)):
m[i][j]=n[k]
</code></pre>
<p><code>i</code> and <code>j</code> doesn't changes, so you assign <code>n[i][j]=n[0]</code> and then <code>n[i][j]=n[1]</code>, <code>n[i][j]=n[2]</code>, <code>n[i][j]=n[3]</code> and just the last one holds.</p>
<p>A naive way to solve it is:</p>
<pre><code> k=0
for i in range(len(m)):
for j in range(len(m)):
m[i][j]=n[k]
k+=1
</code></pre>
| 0 | 2016-08-10T10:07:07Z | [
"python",
"matrix",
"iteration"
] |
Python 2.7: Extract values from same dictionary in multiple functions | 38,870,081 | <p>I have a dictionary which is going to be passed to multiple functions. In each of the functions, I need to extract all the values of the dictionary.</p>
<p>For example,</p>
<pre><code>def foo(mas_details):
# Extract mas details
if 'ip' in mas_details.keys():
mas_ip = mas_details['ip']
else:
logger_object.critical("MAS IP not provided!")
return False
if 'username' in mas_details.keys():
mas_username = mas_details['username']
else:
mas_username = 'root'
if 'password' in mas_details.keys():
mas_password = mas_details['password']
else:
mas_password = 'root'
if 'protocol' in mas_details.keys():
mas_protocol = mas_details['protocol']
else:
mas_protocol = "http"
if 'timeout' in mas_details.keys():
mas_timeout = mas_details['timeout']
else:
mas_timeout = 120
</code></pre>
<p>I have about 15 functions where I will be passing this <code>mas_details</code> dictionary. However, extracting the values in each function makes the code repetitive. </p>
<p>I want to put the extraction of the values into a function in itself. However, if I do that, the variables won't be accessible in the parent functions, unless I make all the variables <code>global</code>.</p>
<p>What is the best way of going about this?</p>
| 0 | 2016-08-10T09:58:44Z | 38,870,331 | <p>Well, if you simply need all the 6 variables in a function, you can destruct the dictionary, i.e.</p>
<pre><code>def f1(arg1, arg2, ..., arg6):
...
def f2(arg1, arg2, ..., arg6):
...
# initialize dictionary
d = {'arg1': 'val1', 'arg2': 'val2', ...}
# fill default values (or use defaultdict with appropriate factory)
d['arg1'] = d.get('arg1', 'default_arg1_value')
d['arg2'] = d.get('arg2', 'default_arg2_value')
...
f1(**d)
f2(**d)
...
</code></pre>
<p>This would give you an access to variables, without explicit extraction from a dictionary. One of the good practices is to keep the number of arguments limited, so consider initializing the dict with default values once, and then using <code>**kwargs</code> and extracting the <em>required</em> values manually, in case the number of arguments grows. </p>
<pre><code># 1. Initialize dictionary
# 2. Fill default values
# 3. Use with kwargs:
def f(**kwargs):
arg1 = kwargs['arg1'] # at this point you are SURE, that there is a value
</code></pre>
| 0 | 2016-08-10T10:08:50Z | [
"python",
"python-2.7",
"dictionary"
] |
Python 2.7: Extract values from same dictionary in multiple functions | 38,870,081 | <p>I have a dictionary which is going to be passed to multiple functions. In each of the functions, I need to extract all the values of the dictionary.</p>
<p>For example,</p>
<pre><code>def foo(mas_details):
# Extract mas details
if 'ip' in mas_details.keys():
mas_ip = mas_details['ip']
else:
logger_object.critical("MAS IP not provided!")
return False
if 'username' in mas_details.keys():
mas_username = mas_details['username']
else:
mas_username = 'root'
if 'password' in mas_details.keys():
mas_password = mas_details['password']
else:
mas_password = 'root'
if 'protocol' in mas_details.keys():
mas_protocol = mas_details['protocol']
else:
mas_protocol = "http"
if 'timeout' in mas_details.keys():
mas_timeout = mas_details['timeout']
else:
mas_timeout = 120
</code></pre>
<p>I have about 15 functions where I will be passing this <code>mas_details</code> dictionary. However, extracting the values in each function makes the code repetitive. </p>
<p>I want to put the extraction of the values into a function in itself. However, if I do that, the variables won't be accessible in the parent functions, unless I make all the variables <code>global</code>.</p>
<p>What is the best way of going about this?</p>
| 0 | 2016-08-10T09:58:44Z | 38,870,640 | <p>The code can be made a lot smaller:</p>
<pre><code>'username' in mas_details.keys():
</code></pre>
<p>The keys() is superfluous, it's equal to </p>
<pre><code>'username' in mas_details
</code></pre>
<p>But more importantly,</p>
<pre><code>if 'username' in mas_details.keys():
mas_username = mas_details['username']
else:
mas_username = 'root'
</code></pre>
<p>is equal to</p>
<pre><code>mas_username = mas_details.get('username', 'root')
</code></pre>
<p>The get function takes a default to use if the key doesn't exist.</p>
<p>But: what you have is some <em>group of variables</em> together with some <em>functionality</em> that always acts on the variables. That is what we invented the <strong>class</strong> for:</p>
<pre><code>class MasDetails(object):
def __init__(self, mas_details):
self.username = mas_details.get('username', 'root')
self.password = mas_details.get('password', 'root')
</code></pre>
<p>Et cetera. Then just pass in a <code>MasDetails</code> instance and use its <code>.username</code> property.</p>
<pre><code>mas = MasDetails(mas_details)
def foo(mas):
# use mas.username, mas.password here
</code></pre>
<p>If you have any functionality that only uses these properties, put it on this class as methods.</p>
<p>In particular, maybe your <code>foo</code> function and the 14 others should simply be methods on the <code>MasDetails</code> class, then they can use <code>self.username</code>.</p>
| 2 | 2016-08-10T10:21:26Z | [
"python",
"python-2.7",
"dictionary"
] |
filtering out some elements in matrix in python | 38,870,160 | <p>I have a list of lists (matrix). I want to filter out those lists in my matrix with even one 0 and export the results to a .txt file.</p>
<p>input example:</p>
<pre><code>[['ENSG00000137288.5', '0,803921621', '0', '0,435897439', '1,384615397', '0,894736842', '1,151515086', '1,25', '1,2'], ['ENSG00000116032.5', '1,531746311', '2,67857148', '2', '3,0250002', '1,758620722', '1,571428459', '1,028571488', '1,294117703'], ['ENSG00000167578.12', '1,615720507', '2,21323528', '3,308642104', '3,934426129', '1,843137535', '0', '3,108108197', '3,33333321']]
</code></pre>
<p>output example which would be one of the rows in .txt file:</p>
<pre><code>ENSG00000116032.5, 1,531746311, 2,67857148, 2, 3,0250002, 1,758620722, 1,571428459, 1,028571488, 1,294117703
</code></pre>
<p>thanks</p>
| -1 | 2016-08-10T10:01:59Z | 38,870,626 | <p>I found a method if helps:-</p>
<pre><code> a = [['ENSG00000137288.5', '0,803921621', '0', '0,435897439', '1,384615397', '0,894736842', '1,151515086', '1,25', '1,2'], ['ENSG00000116032.5', '1,531746311', '2,67857148', '2', '3,0250002', '1,758620722', '1,571428459', '1,028571488', '1,294117703'], ['ENSG00000167578.12', '1,615720507', '2,21323528', '3,308642104', '3,934426129', '1,843137535', '0', '3,108108197', '3,33333321']]
b = filter(lambda x : False if x.count('0') > 0 else x, a)
print "\n".join([" ".join(item) for item in b])
#op = 'ENSG00000116032.5 1,531746311 2,67857148 2 3,0250002 1,758620722 1,571428459 1,028571488 1,294117703'
</code></pre>
<p>Use this output to write in txt file.</p>
| 0 | 2016-08-10T10:20:51Z | [
"python"
] |
How can I sum integers line by line until a new line and then start again? | 38,870,200 | <p>I have a file like this:</p>
<pre><code>1
2
3
5
0
5
2
3
</code></pre>
<p>What I want to do is to sum the integers until the newline and then start to sum again, so the result would be:</p>
<pre><code>6
5
10
</code></pre>
<p>What I have so far is:</p>
<pre><code>import sys
def readText(filename):
sum = 0
data = open(filename,'r')
for line in data.readlines():
if (line[0] != '\n'):
sum+=int(line)
else:
sum = 0
continue
print sum
if len(sys.argv) == 2:
lines = readText(sys.argv[1])
else:
print("script.py inputfile")
</code></pre>
<p>But I get only the sum of the last "group" of integers, in this example 10. I would appreciate any help!</p>
| 1 | 2016-08-10T10:03:16Z | 38,870,366 | <p>move <code>print (sum)</code> before the the <code>sum = 0</code> and you'll be fine</p>
<p>Note that the line <code>sum = 0</code> in the loop makes you sum from the start (and you "forget" all previous numbers...)</p>
<p><em>print sum is for python 2 and I use 3, hence the print (sum) in the print method</em></p>
| 1 | 2016-08-10T10:10:13Z | [
"python",
"integer",
"sum"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.