title
stringlengths 10
172
| question_id
int64 469
40.1M
| question_body
stringlengths 22
48.2k
| question_score
int64 -44
5.52k
| question_date
stringlengths 20
20
| answer_id
int64 497
40.1M
| answer_body
stringlengths 18
33.9k
| answer_score
int64 -38
8.38k
| answer_date
stringlengths 20
20
| tags
list |
---|---|---|---|---|---|---|---|---|---|
Matplotlib - How to plot a high resolution graph? | 39,870,642 | <p>I've used matplotlib for plotting some experimental results (discussed it in here: <a href="http://stackoverflow.com/questions/39676294/looping-over-files-and-plotting-python/" title="Looping over files and plotting (Python)">Looping over files and plotting</a>. However, saving the picture by clicking right to the image gives very bad quality / low resolution images.</p>
<pre><code>from glob import glob
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
# loop over all files in the current directory ending with .txt
for fname in glob("./*.txt"):
# read file, skip header (1 line) and unpack into 3 variables
WL, ABS, T = np.genfromtxt(fname, skip_header=1, unpack=True)
# first plot
plt.plot(WL, T, label='BN', color='blue')
plt.xlabel('Wavelength (nm)')
plt.xlim(200,1000)
plt.ylim(0,100)
plt.ylabel('Transmittance, %')
mpl.rcParams.update({'font.size': 14})
#plt.legend(loc='lower center')
plt.title('')
plt.show()
plt.clf()
# second plot
plt.plot(WL, ABS, label='BN', color='red')
plt.xlabel('Wavelength (nm)')
plt.xlim(200,1000)
plt.ylabel('Absorbance, A')
mpl.rcParams.update({'font.size': 14})
#plt.legend()
plt.title('')
plt.show()
plt.clf()
</code></pre>
<p>Example graph of what I'm looking for: <a href="http://i.stack.imgur.com/CNSoO.png" rel="nofollow">example graph</a></p>
| 2 | 2016-10-05T09:45:40Z | 39,870,773 | <p>use <code>plt.figure(dpi=1200)</code> before all your <code>plt.plot...</code> and at the end use <code>plt.savefig(...</code> see: <a href="http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.figure" rel="nofollow">http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.figure</a>
and
<a href="http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.savefig" rel="nofollow">http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.savefig</a></p>
| 0 | 2016-10-05T09:51:33Z | [
"python",
"matplotlib"
]
|
Matplotlib - How to plot a high resolution graph? | 39,870,642 | <p>I've used matplotlib for plotting some experimental results (discussed it in here: <a href="http://stackoverflow.com/questions/39676294/looping-over-files-and-plotting-python/" title="Looping over files and plotting (Python)">Looping over files and plotting</a>. However, saving the picture by clicking right to the image gives very bad quality / low resolution images.</p>
<pre><code>from glob import glob
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
# loop over all files in the current directory ending with .txt
for fname in glob("./*.txt"):
# read file, skip header (1 line) and unpack into 3 variables
WL, ABS, T = np.genfromtxt(fname, skip_header=1, unpack=True)
# first plot
plt.plot(WL, T, label='BN', color='blue')
plt.xlabel('Wavelength (nm)')
plt.xlim(200,1000)
plt.ylim(0,100)
plt.ylabel('Transmittance, %')
mpl.rcParams.update({'font.size': 14})
#plt.legend(loc='lower center')
plt.title('')
plt.show()
plt.clf()
# second plot
plt.plot(WL, ABS, label='BN', color='red')
plt.xlabel('Wavelength (nm)')
plt.xlim(200,1000)
plt.ylabel('Absorbance, A')
mpl.rcParams.update({'font.size': 14})
#plt.legend()
plt.title('')
plt.show()
plt.clf()
</code></pre>
<p>Example graph of what I'm looking for: <a href="http://i.stack.imgur.com/CNSoO.png" rel="nofollow">example graph</a></p>
| 2 | 2016-10-05T09:45:40Z | 39,871,404 | <p>At the end of your <em>for()</em> loop, you can use the <code>savefig()</code> function instead of <em>plt.show()</em> and set the name, dpi and format of your figure. </p>
<p>E.g. 1000 dpi and eps format are quite a good quality, and if you want to save every picture at folder <em>./</em> with names 'Sample1.eps', 'Sample2.eps', etc. you can just add the following code:</p>
<pre><code>for fname in glob("./*.txt"):
# Your previous code goes here
[...]
plt.savefig("./{}.eps".format(fname), bbox_inches='tight', format='eps', dpi=1000)
</code></pre>
| 0 | 2016-10-05T10:22:09Z | [
"python",
"matplotlib"
]
|
Max, len, split Python | 39,870,749 | <p>I'm trying to find all combinations of A,B repeated 3 times.
Once I've done this I would like to count how many A's there are in a row, by splitting the string and returning the len.max value. However this is going crazy on me. I must have misunderstood the len(max(tmp.split="A")</p>
<p>Can anyone explain what this really does (len returns the length of the string, and max returns the highest integer of that string, based on my split?) I expect it to return the number of A's in a row. "A,B,A" should return 1 even though there are two A's. </p>
<p>Suggestions and clarifications would be sincerely welcome</p>
<pre><code>import itertools
list = list(itertools.product(["A", "B"], repeat=3))
count = 0;
for i in list:
count += 1;
tmp = str(i);
var = len(max(tmp.split("B")))
print(count, i, var)
</code></pre>
| 2 | 2016-10-05T09:50:33Z | 39,871,238 | <p><strong>Edit</strong>: Count only consecutive B's</p>
<pre><code>import re
import itertools
li = list(itertools.product(["A", "B"], repeat=3))
count = 0;
for i in li:
count += 1
s = ''.join(i)
if i.count('B') > 0:
var = max(len(s) for s in re.findall(r'B+', s))
else:
var = 0
print(count, i, var)
</code></pre>
| -1 | 2016-10-05T10:13:40Z | [
"python",
"itertools"
]
|
Max, len, split Python | 39,870,749 | <p>I'm trying to find all combinations of A,B repeated 3 times.
Once I've done this I would like to count how many A's there are in a row, by splitting the string and returning the len.max value. However this is going crazy on me. I must have misunderstood the len(max(tmp.split="A")</p>
<p>Can anyone explain what this really does (len returns the length of the string, and max returns the highest integer of that string, based on my split?) I expect it to return the number of A's in a row. "A,B,A" should return 1 even though there are two A's. </p>
<p>Suggestions and clarifications would be sincerely welcome</p>
<pre><code>import itertools
list = list(itertools.product(["A", "B"], repeat=3))
count = 0;
for i in list:
count += 1;
tmp = str(i);
var = len(max(tmp.split("B")))
print(count, i, var)
</code></pre>
| 2 | 2016-10-05T09:50:33Z | 39,871,549 | <p>You can use <a href="https://docs.python.org/3/library/itertools.html#itertools.groupby" rel="nofollow"><code>itertools.groupby</code></a> to find groups of identical elements in an iterable. <code>groupby</code> generates a sequence of (key, group) tuples, where <code>key</code> is the value of the elements in the group, and <code>group</code> is an iterator of that group (which shares the underlying iterable with <code>groupby</code>. To get the length of the group we need to convert it to a list. </p>
<pre><code>from itertools import product, groupby
for t in product("AB", repeat=3):
a = max([len(list(g)) for k, g in groupby(t) if k == "A"] or [0])
print(t, a)
</code></pre>
<p><strong>output</strong></p>
<pre><code>('A', 'A', 'A') 3
('A', 'A', 'B') 2
('A', 'B', 'A') 1
('A', 'B', 'B') 1
('B', 'A', 'A') 2
('B', 'A', 'B') 1
('B', 'B', 'A') 1
('B', 'B', 'B') 0
</code></pre>
<p>We need to append <code>or [0]</code> to the list comprehension to cover the situation where no "A"s are found, otherwise <code>max</code> complains that we're trying to find the maximum of an empty sequence. </p>
<h3>Update</h3>
<p>Padraic Cunningham reminded me that the Python 3 version of <code>max</code> accepts a default arg to handle the situation when you pass it an empty iterable. He also shows another way to calculate the length of an iterable that is a bit nicer since it avoids capturing the iterable into a list, so it's a bit faster and consumes less RAM, which can be handy when working with large iterables. So we can rewrite the above code as</p>
<pre><code>from itertools import product, groupby
for t in product("AB", repeat=3):
a = max((sum(1 for _ in g) for k, g in groupby(t) if k == "A"), default=0)
print(t, a)
</code></pre>
| 3 | 2016-10-05T10:30:09Z | [
"python",
"itertools"
]
|
Difference between logarithm in numpy and theano.tensor | 39,870,912 | <p>What is the difference between numpy.log and theano.tensor.log?
Do they perform the same?</p>
| 1 | 2016-10-05T09:57:48Z | 39,877,452 | <p>It is likely that <code>numpy.log</code> will be faster. You can compare them both on your CPU and your data.</p>
<pre><code>import theano
import theano.tensor as T
import numpy as
x = T.vector('x')
theano_log = theano.function([x], T.log(x))
a = np.random.rand(1000).astype(np.float32) # test data
assert np.allclose(theano_log(a), np.log(a)) # optional correctness check
</code></pre>
<p>Then measure with:</p>
<pre><code>In [6]: %timeit np.log(a)
100000 loops, best of 3: 7.89 µs per loop
In [7]: %timeit theano_log(a)
10000 loops, best of 3: 44.1 µs per loop
</code></pre>
<p>So for a vector of size 1000 <code>numpy</code> is about 5 times faster. This results might vary if you switch to run the calculations in a GPU which you can do with <code>theano</code> and not with <code>numpy</code>.</p>
<p>The main difference is the way you use each library. In theano if you want to do several operations to an array (ex: log->square->mean) you would declare first a computation graph and then evaluate the whole graph at once which might result in some optimizations. With <code>numpy</code> you would evaluate each intermediate step, creating many intermediate variables on the process that can in some cases be avoided in <code>theano</code>.</p>
| 0 | 2016-10-05T14:58:45Z | [
"python",
"numpy",
"theano"
]
|
Most elegant way to calculate completion times for a list of jobs in Python | 39,870,925 | <p>I have a list of jobs in form of <code>[(weight, length)]</code>, e.g.</p>
<pre><code>[(99, 1), (100, 3), (100, 3), (99, 2), (99, 2)]
</code></pre>
<p>But much larger. </p>
<p>And i've written a function that schedules them according to different keys that I pass as a parameter. This means that for each job I calculate its finishing time as a sum of all the previous jobs. The ultimate goal is to calculate the weighted finishing times: <code>weight[i] * completion_time[i]</code></p>
<p>Currently I don't see an elegant way to do this without separating all the lengths in a separate list, which doesn't seem very Pythonic to me.</p>
<p>Here is the code</p>
<pre><code>def schedule(jobs_list, sort_key):
sorted_jobs = sorted(jobs_list, key=sort_key, reverse=True)
lengths = [job[1] for job in sorted_jobs]
weighted_completion_times = [sum(lengths[:i + 1]) * sorted_jobs[i][0] for i in range(len(sorted_jobs))]
return sum(weighted_completion_times)
</code></pre>
<p>and here is the sample usage:</p>
<pre><code>schedule(jobs, lambda t: (t[0] - t[1], t[0]))
</code></pre>
<p>Ideally I would like the solution to be both human-readable and memory efficient (i.e. without creating another list of lengths)</p>
| 1 | 2016-10-05T09:58:43Z | 39,871,204 | <p>You want to use the <a href="https://docs.python.org/3/library/itertools.html#itertools.accumulate" rel="nofollow"><code>itertools.accumulate()</code> iterable</a> to produce the acumulative weight of your lengths:</p>
<pre><code>from itertools import accumulate
def schedule(jobs_list, sort_key):
sorted_jobs = sorted(jobs_list, key=sort_key, reverse=True)
acc_lengths = accumulate(job[1] for job in sorted_jobs)
weighted_completion_times = (al * job[0] for al, job in zip(acc_lengths, sorted_jobs))
return sum(weighted_completion_times)
</code></pre>
<p>Note that this at no point builds new lists other than the sorted list. Both by avoiding building intermediary lists as well as avoiding re-summing longer and longer sublists (making this O(N) vs your O(N^2) approach), the above is also much more efficient; just on your short sample there is a 25% improvement in timings:</p>
<pre><code>>>> from itertools import accumulate
>>> from timeit import timeit
>>> def schedule_lists(jobs_list, sort_key):
... sorted_jobs = sorted(jobs_list, key=sort_key, reverse=True)
... lengths = [job[1] for job in sorted_jobs]
... weighted_completion_times = [sum(lengths[:i + 1]) * sorted_jobs[i][0] for i in range(len(sorted_jobs))]
... return sum(weighted_completion_times)
...
>>> def schedule_acc(jobs_list, sort_key):
... sorted_jobs = sorted(jobs_list, key=sort_key, reverse=True)
... acc_lengths = accumulate(job[1] for job in sorted_jobs)
... weighted_completion_times = (al * job[0] for al, job in zip(acc_lengths, sorted_jobs))
... return sum(weighted_completion_times)
...
>>> jobs = [(99, 1), (100, 3), (100, 3), (99, 2), (99, 2)]
>>> timeit('schedule(jobs, lambda t: (t[0] - t[1], t[0]))',
... 'from __main__ import jobs, schedule_lists as schedule',
... number=100000)
0.6098654230008833
>>> timeit('schedule(jobs, lambda t: (t[0] - t[1], t[0]))',
'from __main__ import jobs, schedule_acc as schedule',
... number=100000)
0.4608557689934969
</code></pre>
<p>The difference is far more pronounced when you increase the job list size to 1000 however:</p>
<pre><code>>>> import random
>>> jobs = [(random.randrange(80, 150), random.randrange(1, 10)) for _ in range(1000)]
>>> timeit('schedule(jobs, lambda t: (t[0] - t[1], t[0]))',
... 'from __main__ import jobs, schedule_lists as schedule',
... number=1000)
5.421368871000595
>>> timeit('schedule(jobs, lambda t: (t[0] - t[1], t[0]))',
... 'from __main__ import jobs, schedule_acc as schedule',
... number=1000)
0.7538741750176996
</code></pre>
| 3 | 2016-10-05T10:12:06Z | [
"python",
"list",
"python-3.x",
"list-comprehension"
]
|
Parsing XML in Python with multiple tags | 39,870,942 | <p>I'm trying to parse an XML file.<br>
I succeeded at parsing tags at the upper layer, but now I have a tag within a tag and I'm not getting the correct output.</p>
<p><strong>XML FILE:</strong></p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<Stations>
<Station>
<Code>HT</Code>
<Type>knooppuntIntercitystation</Type>
<Namen>
<Kort>Den Bosch</Kort>
<Middel>'s-Hertogenbosch</Middel>
<Lang>'s-Hertogenbosch</Lang>
</Namen>
<Land>NL</Land>
<Synoniemen>
<Synoniem>Hertogenbosch ('s)</Synoniem>
<Synoniem>Den Bosch</Synoniem>
</Synoniemen>
</Station>
<Station>
<Code>ALMO</Code>
<Type>stoptreinstation</Type>
<Namen>
<Kort>Oostvaard</Kort>
<Middel>Oostvaarders</Middel>
<Lang>Almere Oostvaarders</Lang>
</Namen>
<Land>NL</Land>
<Synoniemen>
</Synoniemen>
</Station>
<Station>
<Code>ATN</Code>
<Type>stoptreinstation</Type>
<Namen>
<Kort>Aalten</Kort>
<Middel>Aalten</Middel>
<Lang>Aalten</Lang>
</Namen>
<Land>NL</Land>
<Synoniemen>
</Synoniemen>
</Station>
<Station>
<Code>ASA</Code>
<Type>intercitystation</Type>
<Namen>
<Kort>Amstel</Kort>
<Middel>Amsterdam Amstel</Middel>
<Lang>Amsterdam Amstel</Lang>
</Namen>
<Land>NL</Land>
<Synoniemen>
</Synoniemen>
</Station>
</Stations>
</code></pre>
<p><strong>My python function:</strong></p>
<pre><code>import xml.etree.ElementTree
e = xml.etree.ElementTree.parse('info.xml').getroot()
for stationsnamens in e.findall('Station'):
try:
syn = stationsnamens.find('Synoniemen/Synoniem').text
print(syn)
except:
print(Exception)
</code></pre>
<p>I'm trying to print every <code>Synoniemen</code> field there is, but only if it exists. Also, the 'Code' needs to be printed. </p>
<p><strong>Output Format:</strong> </p>
<pre><code>{Code}: {Synoniemen}
</code></pre>
| 1 | 2016-10-05T09:59:12Z | 39,872,817 | <p>something like this (note: I have used <code>.fromstring()</code> in this example, but you can modify this for your own use with files)</p>
<pre><code>import xml.etree.ElementTree
xmlstring = "<root><synoniemen><synoniem>A</synoniem><synoniem>B</synoniem></synoniemen></root>"
e = xml.etree.ElementTree.fromstring(xmlstring)
syn = e.find('synoniemen')
for synoniem in syn:
print(synoniem.text)
</code></pre>
<p>point is that <code>syn</code> is a iterable with a <code>for</code> as it contains multiple elements.</p>
<p>So your code will look something like this:</p>
<pre><code>for stationsnamens in e.findall('Station'):
code = stationsnames.find('Code')
try:
syn = stationsnamens.find('Synoniemen')
for synoniem in syn:
print(code.text, synoniem.text)
except:
print(Exception)
</code></pre>
| 2 | 2016-10-05T11:31:26Z | [
"python",
"python-3.x"
]
|
OpenCV/Python: Colorbar in fft magnitude | 39,870,953 | <p>I'm using opencv in python 2.7.</p>
<ol>
<li>The colormap is oversized. How to shrink it to has the same length as the image?</li>
<li>How do I explain the value/range of magnitude?</li>
</ol>
<p>This is my code:</p>
<pre><code>import numpy as np
import cv2
from matplotlib import pyplot as plt
img = cv2.imread('messi.jpg',0)
dft = cv2.dft(np.float32(img),flags = cv2.DFT_COMPLEX_OUTPUT)
dft_shift = np.fft.fftshift(dft)
magnitude_spectrum = np.log(cv2.magnitude(dft_shift[:,:,0],dft_shift[:,:,1]))
plt.subplot(131),plt.imshow(img, cmap = 'gray')
plt.title('Input Image'), plt.xticks([]), plt.yticks([])
plt.subplot(132),plt.imshow(magnitude_spectrum, cmap = 'gray'), plt.colorbar(cmap = 'gray')
plt.title('Magnitude Spectrum'), plt.xticks([]), plt.yticks([])
plt.show()
</code></pre>
<p><a href="http://i.stack.imgur.com/iNEYT.png" rel="nofollow"><img src="http://i.stack.imgur.com/iNEYT.png" alt="enter image description here"></a></p>
| 0 | 2016-10-05T09:59:50Z | 39,871,734 | <p>I found the solution.</p>
<p>To resize the <code>colorbar</code> I use <code>fraction</code> parameter and it's corresponding value in <code>colorbar</code>. Thanks to <a href="http://stackoverflow.com/questions/18195758/set-matplotlib-colorbar-size-to-match-graph/26720422#26720422">bejota's answer</a>.</p>
<p>Regarding the magnitude value, I found that as brighter are the vertices in the magnitude image the greater the contrast in brightness of the original grayscale image. Try the code below using various images.</p>
<p>This is my final code:</p>
<pre><code>import numpy as np
import cv2
from matplotlib import pyplot as plt
img = cv2.imread('messi.jpg',0)
dft = cv2.dft(np.float32(img),flags = cv2.DFT_COMPLEX_OUTPUT)
dft_shift = np.fft.fftshift(dft)
magnitude_spectrum = np.log(cv2.magnitude(dft_shift[:,:,0],dft_shift[:,:,1]))
plt.subplot(121),plt.imshow(img, cmap = 'gray')
plt.title('Input Image'), plt.xticks([]), plt.yticks([])
plt.subplot(122),plt.imshow(magnitude_spectrum, cmap = 'gray'), plt.colorbar(cmap = 'gray',fraction=0.03, pad=0.04)
plt.title('Magnitude Spectrum'), plt.xticks([]), plt.yticks([])
plt.show()
</code></pre>
<p>And this is the result:
<a href="http://i.stack.imgur.com/N1uXk.png" rel="nofollow"><img src="http://i.stack.imgur.com/N1uXk.png" alt="enter image description here"></a></p>
| 0 | 2016-10-05T10:38:32Z | [
"python",
"opencv",
"fft",
"magnitude"
]
|
Django how to send a argument in handler404? | 39,871,189 | <p>How to override <code>handler404</code> to pass arguments into view?</p>
<p>Need to pass the arguments <code>text</code> and <code>error</code></p>
<pre><code># views.py
def handler404(request, error, text):
response = render_to_response('error/40X.html', {'error': error, 'text':text})
response.status_code = error
return response
</code></pre>
<p>And the override code 404 errors:</p>
<pre><code>handler404 = 'app.views.handler404'
</code></pre>
<p>Am using Django v1.10 and Python v3.5, and do not really want to create a function for each error.</p>
<blockquote>
<p>The question was translated, and I would be grateful for corrections, <a href="http://ru.stackoverflow.com/questions/568820/django-%D0%BA%D0%B0%D0%BA-%D0%BE%D1%82%D0%BF%D1%80%D0%B0%D0%B2%D0%B8%D1%82%D1%8C-%D0%B0%D1%80%D0%B3%D1%83%D0%BC%D0%B5%D0%BD%D1%82-%D0%B2-handler404">original</a></p>
</blockquote>
| 0 | 2016-10-05T10:11:37Z | 39,871,516 | <p>I don't think you need a custom <code>handler404</code> view here. Django's <code>page_not_found</code> view does what you want.</p>
<p>In Django 1.9+, you can include <code>{{ exception }}</code> in the 404 template.</p>
<p>In your view, you could set the message when raising the exception, for example:</p>
<pre><code>from django.http import Http404
def my_view(request):
raise Http404('custom error message')
</code></pre>
<p>It doesn't make sense to set <code>response.status_code</code> in the handler - if it's handler404, then the status code should always be 404.</p>
| 0 | 2016-10-05T10:28:23Z | [
"python",
"django",
"python-3.x",
"django-views",
"python-3.5"
]
|
Is it possible to def a function with a dotted name in Python? | 39,871,227 | <p>In the question <a href="https://stackoverflow.com/questions/231767/what-does-the-yield-keyword-do"><em>What does the "yield" keyword do?</em></a>, I found a Python syntax being used that I didn't expect to be valid. The question is old and has a huge number of votes, so I'm surprised nobody at least left a comment about this function definition:</p>
<pre><code>def node._get_child_candidates(self, distance, min_dist, max_dist):
if self._leftchild and distance - max_dist < self._median:
yield self._leftchild
if self._rightchild and distance + max_dist >= self._median:
yield self._rightchild
</code></pre>
<p>What I tried to get this sort of syntax evaluated:</p>
<ul>
<li>assigning an attribute to a class or object</li>
<li>redefining a function of an imported module</li>
</ul>
<p>fails so far with </p>
<blockquote>
<p>SyntaxError: invalid syntax</p>
</blockquote>
<p>I looked up the <a href="http://well-adjusted.de/~jrschulz/mspace/">link (maybe outdated)</a> given in the question, and searched the web for the usage of <code>def</code>, but I found nothing explaining this "dotted name" pattern. I'm using Python 3, maybe this is a feature of Python 2?</p>
<p><strong>Is (or was) this syntax valid, if yes what does it mean?</strong></p>
| 7 | 2016-10-05T10:13:12Z | 39,871,459 | <p>No, the syntax is not valid. It is easy to prove by checking the documentation. In Python 2, an identifier is constructed by the following <a href="https://docs.python.org/2/reference/lexical_analysis.html#identifiers" rel="nofollow">rules</a>:</p>
<pre><code>identifier ::= (letter|"_") (letter | digit | "_")*
letter ::= lowercase | uppercase
lowercase ::= "a"..."z"
uppercase ::= "A"..."Z"
digit ::= "0"..."9"
</code></pre>
<p>In Py3 the rules are more or less the same, beside being expanded up to the range of Unicode characters.</p>
<p>It seems that the author probably meant something like</p>
<pre><code>class Node:
...
def _get_child_candidates(self, ...):
...
</code></pre>
| 4 | 2016-10-05T10:25:20Z | [
"python",
"function",
"syntax-error"
]
|
Is it possible to def a function with a dotted name in Python? | 39,871,227 | <p>In the question <a href="https://stackoverflow.com/questions/231767/what-does-the-yield-keyword-do"><em>What does the "yield" keyword do?</em></a>, I found a Python syntax being used that I didn't expect to be valid. The question is old and has a huge number of votes, so I'm surprised nobody at least left a comment about this function definition:</p>
<pre><code>def node._get_child_candidates(self, distance, min_dist, max_dist):
if self._leftchild and distance - max_dist < self._median:
yield self._leftchild
if self._rightchild and distance + max_dist >= self._median:
yield self._rightchild
</code></pre>
<p>What I tried to get this sort of syntax evaluated:</p>
<ul>
<li>assigning an attribute to a class or object</li>
<li>redefining a function of an imported module</li>
</ul>
<p>fails so far with </p>
<blockquote>
<p>SyntaxError: invalid syntax</p>
</blockquote>
<p>I looked up the <a href="http://well-adjusted.de/~jrschulz/mspace/">link (maybe outdated)</a> given in the question, and searched the web for the usage of <code>def</code>, but I found nothing explaining this "dotted name" pattern. I'm using Python 3, maybe this is a feature of Python 2?</p>
<p><strong>Is (or was) this syntax valid, if yes what does it mean?</strong></p>
| 7 | 2016-10-05T10:13:12Z | 39,871,509 | <p>As in my comment you cannot, the valid identifiers for python3 are in the <a href="https://docs.python.org/3/reference/lexical_analysis.html#identifiers" rel="nofollow">docs</a>:</p>
<p><em>Identifiers (also referred to as names) are described by the following lexical definitions.</em></p>
<p><em>The syntax of identifiers in Python is based on the Unicode standard annex UAX-31, with elaboration and changes as defined below; see also PEP 3131 for further details.</em></p>
<p><em>Within the ASCII range (U+0001..U+007F), the valid characters for identifiers are the same as in Python 2.x: the uppercase and lowercase letters A through Z, the underscore _ and, except for the first character, the digits 0 through 9.</em></p>
<p><em>Python 3.0 introduces additional characters from outside the ASCII range (see PEP 3131). For these characters, the classification uses the version of the Unicode Character Database as included in the unicodedata module.</em></p>
<p>If you examine the code you can see it is a typo in the original question:</p>
<pre><code>def node._get_child_candidates(self, distance, min_dist, max_dist):
if self._leftchild and distance - max_dist < self._median:
yield self._leftchild
if self._rightchild and distance + max_dist >= self._median:
yield self._rightchild
</code></pre>
<p>And this is the caller:</p>
<pre><code>result, candidates = list(), [self]
while candidates:
node = candidates.pop() # creates an instance
distance = node._get_dist(obj)
if distance <= max_dist and distance >= min_dist:
result.extend(node._values)
# the _get_child_candidates node is called
candidates.extend(node._get_child_candidates(distance, min_dist, max_dist))
return result
</code></pre>
<p>So the method <code>_get_child_candidates</code> is called on the instance. So really the actual code looks like:</p>
<pre><code>def _get_child_candidates(self, distance, min_dist, max_dist):
if self._leftchild and distance - max_dist < self._median:
yield self._leftchild
if self._rightchild and distance + max_dist >= self._median:
yield self._rightchild
</code></pre>
<p>And this is the caller:</p>
<pre><code>result, candidates = list(), [self]
while candidates:
node = candidates.pop() # creates an instance
distance = node._get_dist(obj)
if distance <= max_dist and distance >= min_dist:
result.extend(node._values)
# the _get_child_candidates node is called
candidates.extend(node._get_child_candidates(distance, min_dist, max_dist))
return result
</code></pre>
| 2 | 2016-10-05T10:27:50Z | [
"python",
"function",
"syntax-error"
]
|
Unordered collection for mutable objects in Python | 39,871,281 | <p>The task I have at hand is to parse a large text (several 100K rows) file and accumulate some statistics based which will be then visualized in plots. Each row contains results of some prior analysis. </p>
<p>I wrote a custom class to define the objects that are to be accumulated. The class contains 2 string fields, 3 sets and 2 integer counters. As such there is an <code>__init__(self, name)</code> which initializes a new object with name and empty fields, and a method called <code>addRow()</code> which adds information into the object. The sets accumulate data to be associated with this object and the counters keep track of a couple of conditions. </p>
<p>My original idea was to iterate over the rows of the file and call a method like <code>parseRow()</code> in <code>main</code></p>
<pre><code>reader = csv.reader(f)
acc = {} # or set()
for row in reader:
parseRow(row,acc)
</code></pre>
<p>which would look something like:</p>
<pre><code>parseRow(row, acc):
if row[id] is not in acc: # row[id] is the column where the object names/ids are
a = MyObj(row[id])
else:
a = acc.get(row[id]) # or equivalent
a.addRow(...)
</code></pre>
<p>The issue here is that the accumulating collection <code>acc</code> cannot be a <code>set</code> since sets are apparently not indexable in Python. <strong>Edit:</strong> for clarification, by <em>indexable</em> I didn't mean getting the nth element but rather being able to <strong>retrieve a specific element</strong>. </p>
<p>One workaround would be to have a <code>dict</code> that has <code>{obj_name : obj}</code> mapping but it feels like an ugly solution. Considering the elegance of the language otherwise, I guess there is a better solution to this. It's surely not a particularly rare situation...</p>
<p>Any suggestions?</p>
| -2 | 2016-10-05T10:15:40Z | 39,871,545 | <p>You could also try an <a href="https://pypi.python.org/pypi/ordered-set" rel="nofollow">ordered-set</a>. Which is a set and ordered.</p>
| 0 | 2016-10-05T10:29:51Z | [
"python",
"python-3.x",
"collections"
]
|
process Builder java cannot run some of the python code in java. How to solve? | 39,871,474 | <p>I am using java to create ProcessBuilder to run python. </p>
<p>Both of the two py can be run sucessfully in the python program. (the two py have no issue with the code)</p>
<p>input.py:</p>
<pre><code>print 'hello'
number=[3,5,2,0,6]
print number
number.sort()
print number
number.append(0)
print number
print number.count(0)
print number.index(5)
</code></pre>
<p>TESTopenBaseOnt.py:</p>
<pre><code>from rdflib import URIRef, Graph, Namespace
from rdflib.plugins.parsers.notation3 import N3Parser
from rdflib.namespace import RDF, OWL, RDFS
from rdflib import URIRef, BNode, Literal
from rdflib import Namespace
from rdflib.namespace import RDF, FOAF, RDFS
from rdflib import Graph
gUpdate = Graph()
print ".> Step....1"
gUpdate.parse("BBCOntology.rdf" )
print ".> Step....2"
print gUpdate.serialize(format='xml')
print ".> Finished......."
#
</code></pre>
<p>AS you can see the picture. </p>
<p>The code works for python:input.py
However, it does not work for python:TESTopenBaseOnt.py<br>
It might be because java cannot run the parse function in python. as the result shows that, the program stoped at step1.</p>
<pre><code>public static void main(String [] args) throws IOException
{
try
{
ProcessBuilder pb = new ProcessBuilder("C:/Python27/python","C:Desktop//searchTestJava//input.py");
// ProcessBuilder pb = new ProcessBuilder("C:/Python27/python","C:Desktop//searchTestJava//TESTopenBaseOnt.py");
Process p = pb.start();
BufferedReader bfr = new BufferedReader(new InputStreamReader(p.getInputStream()));
System.out.println(".........start process.........");
String line = "";
while ((line = bfr.readLine()) != null){
System.out.println("Python Output: " + line);
}
System.out.println("........end process.......");
}catch(Exception e){System.out.println(e);}
}
</code></pre>
<p>So how to solve the problem that the python cannot run in the java
<a href="http://i.stack.imgur.com/L0r4Z.png" rel="nofollow"><img src="http://i.stack.imgur.com/L0r4Z.png" alt="enter image description here"></a></p>
| 0 | 2016-10-05T10:26:01Z | 39,871,834 | <p>Your script runs, but it does not reach "Step 2", so </p>
<pre><code>gUpdate.parse("BBCOntology.rdf" )
</code></pre>
<p>will be the source of the problem. Possibly it is because the file <code>BBCOntology.rdf</code> is not in the current working directory of the Python process. Or it could be that the Python process does not have permission to open that file.</p>
<p>It might be worth reading the error stream from the Python process and printing that out in Java. Use <code>p.getErrorStream()</code> in the same manner that you use <code>p.getInputStream()</code>.</p>
<p>Or, easier, add an exception handler to your Python code that catches and prints exception messages to standard out:</p>
<pre><code>import traceback
try:
gUpdate = Graph()
print ".> Step....1"
gUpdate.parse("BBCOntology.rdf" )
print ".> Step....2"
print gUpdate.serialize(format='xml')
print ".> Finished......."
except Exception as exc:
traceback.print_exc()
raise exc
</code></pre>
<p>Your Java process should then print the message, which might be informative.</p>
| 2 | 2016-10-05T10:43:13Z | [
"java",
"python",
"parsing",
"rdf",
"processbuilder"
]
|
process Builder java cannot run some of the python code in java. How to solve? | 39,871,474 | <p>I am using java to create ProcessBuilder to run python. </p>
<p>Both of the two py can be run sucessfully in the python program. (the two py have no issue with the code)</p>
<p>input.py:</p>
<pre><code>print 'hello'
number=[3,5,2,0,6]
print number
number.sort()
print number
number.append(0)
print number
print number.count(0)
print number.index(5)
</code></pre>
<p>TESTopenBaseOnt.py:</p>
<pre><code>from rdflib import URIRef, Graph, Namespace
from rdflib.plugins.parsers.notation3 import N3Parser
from rdflib.namespace import RDF, OWL, RDFS
from rdflib import URIRef, BNode, Literal
from rdflib import Namespace
from rdflib.namespace import RDF, FOAF, RDFS
from rdflib import Graph
gUpdate = Graph()
print ".> Step....1"
gUpdate.parse("BBCOntology.rdf" )
print ".> Step....2"
print gUpdate.serialize(format='xml')
print ".> Finished......."
#
</code></pre>
<p>AS you can see the picture. </p>
<p>The code works for python:input.py
However, it does not work for python:TESTopenBaseOnt.py<br>
It might be because java cannot run the parse function in python. as the result shows that, the program stoped at step1.</p>
<pre><code>public static void main(String [] args) throws IOException
{
try
{
ProcessBuilder pb = new ProcessBuilder("C:/Python27/python","C:Desktop//searchTestJava//input.py");
// ProcessBuilder pb = new ProcessBuilder("C:/Python27/python","C:Desktop//searchTestJava//TESTopenBaseOnt.py");
Process p = pb.start();
BufferedReader bfr = new BufferedReader(new InputStreamReader(p.getInputStream()));
System.out.println(".........start process.........");
String line = "";
while ((line = bfr.readLine()) != null){
System.out.println("Python Output: " + line);
}
System.out.println("........end process.......");
}catch(Exception e){System.out.println(e);}
}
</code></pre>
<p>So how to solve the problem that the python cannot run in the java
<a href="http://i.stack.imgur.com/L0r4Z.png" rel="nofollow"><img src="http://i.stack.imgur.com/L0r4Z.png" alt="enter image description here"></a></p>
| 0 | 2016-10-05T10:26:01Z | 39,886,173 | <pre><code>gUpdate = Graph()
print ".> Step....1"
gUpdate.parse("D:\\Desktop\\searchTestJava\\BBCOntology.rdf" )
print ".> Step....2"
</code></pre>
<p>The BBCOntology.rdf is in the current working directory of the Python process. So the program can work in python even if I wrote as (gUpdate.parse("BBCOntology.rdf" )). </p>
<p>However, java does not know the directory BBCOntology.rdf is same as the TESTopenBaseOnt.py.
Once I add the gUpdate.parse("D:\Desktop\searchTestJava\BBCOntology.rdf" ) , Java can work. </p>
| 0 | 2016-10-06T01:38:05Z | [
"java",
"python",
"parsing",
"rdf",
"processbuilder"
]
|
Apache Spark 2.0.0 PySpark manual dataframe creation head scratcher | 39,871,496 | <p>When I assemble a one row data frame as follows my method successfully brings back the expected data frame.</p>
<pre><code>def build_job_finish_data_frame(sql_context, job_load_id, is_success):
job_complete_record_schema = StructType(
[
StructField("job_load_id", IntegerType(), False),
StructField("terminate_datetime", TimestampType(), False),
StructField("was_success", BooleanType(), False)
]
)
data = [
Row(
job_load_id=job_load_id,
terminate_datetime=datetime.now(),
was_success=is_success
)
]
return sql_context.createDataFrame(data, job_complete_record_schema)
</code></pre>
<p>If I change the "terminate_datetime" to "end_datetime" or "finish_datetime" as shown below it throws an error.</p>
<pre><code>def build_job_finish_data_frame(sql_context, job_load_id, is_success):
job_complete_record_schema = StructType(
[
StructField("job_load_id", IntegerType(), False),
StructField("end_datetime", TimestampType(), False),
StructField("was_success", BooleanType(), False)
]
)
data = [
Row(
job_load_id=job_load_id,
end_datetime=datetime.now(),
was_success=is_success
)
]
return sql_context.createDataFrame(data, job_complete_record_schema)
</code></pre>
<p>The error I receive is </p>
<pre><code>TypeError: IntegerType can not accept object datetime.datetime(2016, 10, 5, 11, 19, 31, 915745) in type <class 'datetime.datetime'>
</code></pre>
<p>I can change "terminate_datetime" to "start_datetime" and have experimented with other words.</p>
<p>I can see no reason for field name changes breaking this code as it is doing nothing more than building a manual data frame.</p>
<p>This is worrying as I am using data frames to load up a data warehouse where I have no control of the field names.</p>
<p>I am running PySpark on Python 3.3.2 on Fedora 20.</p>
| 1 | 2016-10-05T10:27:08Z | 39,873,305 | <p>Why the name changes things? The problem is that <code>Row</code> is a <code>tuple</code> <strong>sorted</strong> by <code>__fields__</code>. So the first case creates </p>
<pre><code>from pyspark.sql import Row
from datetime import datetime
x = Row(job_load_id=1, terminate_datetime=datetime.now(), was_success=True)
x.__fields__
## ['job_load_id', 'terminate_datetime', 'was_success']
</code></pre>
<p>while the second one creates:</p>
<pre><code>y = Row(job_load_id=1, end_datetime=datetime.now(), was_success=True)
y.__fields__
## ['end_datetime', 'job_load_id', 'was_success']
</code></pre>
<p>This no longer matches the schema you defined which expects <code>(IntegerType, TimestampType, Boolean)</code>.</p>
<p>Because <code>Row</code> is useful mostly for schema inference and you provide schema directly you can address that by using standard <code>tuple</code>:</p>
<pre><code>def build_job_finish_data_frame(sql_context, job_load_id, is_success):
job_complete_record_schema = StructType(
[
StructField("job_load_id", IntegerType(), False),
StructField("end_datetime", TimestampType(), False),
StructField("was_success", BooleanType(), False)
]
)
data = [tuple(job_load_id, datetime.now(), is_success)]
return sql_context.createDataFrame(data, job_complete_record_schema)
</code></pre>
<p>although creating a single element <code>DataFrame</code> looks strange if not pointless.</p>
| 1 | 2016-10-05T11:56:38Z | [
"python",
"apache-spark",
"dataframe"
]
|
Update a Value in Python | 39,871,507 | <p>Hello I am trying to write a program that reads a CSV file of different animals of various breeds. Various animals, named differently, can be of the same breed. (Imagine two cats named bob and sam)</p>
<p>The breeds are in one column and the names are in another.</p>
<p>I want to be able to go over all the animals and count the number of animals in each breed.</p>
<p>The code I have so far is like this:</p>
<pre><code>dragon = open('dragons.csv')
breed = {}
for line in dragon:
row = line.strip().split(',')
if row[4] in breed.keys():
else:
breed[row[4]] = 1 #The Breed is in the fourth column
</code></pre>
<p>How can I do this?</p>
<p>Thank you!</p>
| 0 | 2016-10-05T10:27:40Z | 39,871,692 | <p>As the comments point out, indentation matters in python. The <code>else</code> is not on the same indentation level as the <code>if</code> and thus you get an error.</p>
<p>as for the counting, the <code>+=</code> operator is useful for that, so your if/else block could be like this:</p>
<pre><code>if row[4] in breed.keys():
breed[row[4]] += 1
else:
breed[row[4]] = 1
</code></pre>
| 2 | 2016-10-05T10:37:15Z | [
"python",
"arrays",
"csv",
"dictionary"
]
|
Update a Value in Python | 39,871,507 | <p>Hello I am trying to write a program that reads a CSV file of different animals of various breeds. Various animals, named differently, can be of the same breed. (Imagine two cats named bob and sam)</p>
<p>The breeds are in one column and the names are in another.</p>
<p>I want to be able to go over all the animals and count the number of animals in each breed.</p>
<p>The code I have so far is like this:</p>
<pre><code>dragon = open('dragons.csv')
breed = {}
for line in dragon:
row = line.strip().split(',')
if row[4] in breed.keys():
else:
breed[row[4]] = 1 #The Breed is in the fourth column
</code></pre>
<p>How can I do this?</p>
<p>Thank you!</p>
| 0 | 2016-10-05T10:27:40Z | 39,871,699 | <p>Your <code>else</code> block is insufficiently indented (<code>else</code> can pair with <code>for</code>, but it's uncommon, and the logic of your code says its an error here).</p>
<p>Even if you fix that though, you can't have an empty block in Python, because Python needs at least one indented line of code to detect the indentation level of the block (to allow it to detect when the block ends). When you don't provide any body for a block (start a new block immediately, or end the outer block before providing a body), you get the "expected an indented block" error you mention. So you can either use <code>pass</code> (the no-op keyword that means "Here is something to put in a block that doesn't do anything):</p>
<pre><code>if row[4] in breed: # Don't call .keys(); much slower on Py2, a little slower on Py3
pass
else:
breed[row[4]] = 1 #The Breed is in the fourth column
</code></pre>
<p>Or just invert the <code>if</code> test to control the <code>else</code> block so you don't need both:</p>
<pre><code>if row[4] not in breed:
breed[row[4]] = 1 #The Breed is in the fourth column
</code></pre>
| 0 | 2016-10-05T10:37:29Z | [
"python",
"arrays",
"csv",
"dictionary"
]
|
Remove columns from data frame with hashing | 39,871,559 | <p>Given two pandas dataframes:</p>
<pre><code>df1 = pd.read_csv(file1, names=['col1','col2','col3'])
df2 = pd.read_csv(file2, names=['col1','col2','col3'])
</code></pre>
<p>I'd like to remove all the rows in df2 where the values of either <code>col1</code> or <code>col2</code> (or both) do not exist in df1. </p>
<p>Doing the following:</p>
<pre><code>df2 = df2[(df2['col1'] in set(df1['col1'])) & (df2['col2'] in set(df1['col2']))]
</code></pre>
<p>yields:</p>
<blockquote>
<p>TypeError: 'Series' objects are mutable, thus they cannot be hashed</p>
</blockquote>
| 1 | 2016-10-05T10:30:45Z | 39,871,596 | <p>I think you can try <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.isin.html" rel="nofollow"><code>isin</code></a>:</p>
<pre><code>df2 = df2[(df2['col1'].isin(df1['col1'])) & (df2['col2'].isin(df1['col2']))]
df1 = pd.DataFrame({'col1':[1,2,3,3],
'col2':[4,5,6,2],
'col3':[7,8,9,5]})
print (df1)
col1 col2 col3
0 1 4 7
1 2 5 8
2 3 6 9
3 3 2 5
df2 = pd.DataFrame({'col1':[1,2,3,5],
'col2':[4,7,4,1],
'col3':[7,8,9,1]})
print (df2)
col1 col2 col3
0 1 4 7
1 2 7 8
2 3 4 9
3 5 1 1
df2 = df2[(df2['col1'].isin(df1['col1'])) & (df2['col2'].isin(df1['col2'].unique()))]
print (df2)
col1 col2 col3
0 1 4 7
2 3 4 9
</code></pre>
<p>Another solution is <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.merge.html" rel="nofollow"><code>merge</code></a>, because inner join (<code>how='inner'</code>) is by default, but it works only for values with same position in both <code>DataFrames</code>:</p>
<pre><code>print (pd.merge(df1, df2))
col1 col2 col3
0 1 4 7
</code></pre>
| 2 | 2016-10-05T10:32:06Z | [
"python",
"pandas",
"indexing",
"merge",
"multiple-columns"
]
|
Is there a way to get the sonar result per class or per module | 39,871,632 | <p>I want to get the sonar result in the class wise classification or modularized format. I am using python and the sonar web API. Apart from the basic APIs are there any other APIs which give me the results per class</p>
| 1 | 2016-10-05T10:34:16Z | 39,873,031 | <p>SonarQube doesn't know the concept of "class". This is a logical element, whereas SonarQube manages only "physical" components like files or folders. The consequence is that the Web API allows you to query only components that are "physical".</p>
| 2 | 2016-10-05T11:41:58Z | [
"python",
"sonarqube"
]
|
Executing Interactive shell script in python | 39,872,088 | <p>I have a shell script with ask for the user input. Consider a below example</p>
<p>Test.sh</p>
<pre><code>#!/bin/bash
echo -n "Enter name > "
read text
echo "You entered: $text"
echo -n "Enter age > "
read text
echo "You entered: $text"
echo -n "Enter location > "
read text
echo "You entered: $text"
</code></pre>
<p>Script Execution:</p>
<pre><code>sh test.sh
Enter name> abc
You entered: abc
Enter age > 35
You entered: 35
Enter location > prop
You entered: prop
</code></pre>
<p><em>Now i called this script in python program. I am doing this using sub process module. As far as i know sub process module creates a new process. The problem is when i execute the python script i am not able to pass the parameters to underlying shell script and the scipt is in hault stage. Could some point me where i am doing wrong</em></p>
<p>python script (CHECK.PY):</p>
<pre><code>import subprocess, shlex
cmd = "sh test.sh"
proc = subprocess.Popen(shlex.split(cmd), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout,stderr = proc.communicate()
print stdout
</code></pre>
<p>Python Execution: check.py</p>
<pre><code> python check.py
</code></pre>
| -1 | 2016-10-05T10:55:42Z | 39,872,331 | <p>Your code is working, but since you mention <code>stdout=subprocess.PIPE</code> the content is going to <code>stdout</code> variable you defined in <code>stdout,stderr = proc.communicate()</code>. Remove <code>stdout=subprocess.PIPE</code> argument from your <code>Popen()</code> call and you will see the output.</p>
<p>Alternatively, you should be using <a href="https://docs.python.org/2/library/subprocess.html#subprocess.check_call" rel="nofollow"><code>subprocess.check_call()</code></a> as:</p>
<pre><code>subprocess.check_call(shlex.split(cmd))
</code></pre>
| 2 | 2016-10-05T11:07:51Z | [
"python",
"python-2.7",
"shell",
"python-3.x"
]
|
Executing Interactive shell script in python | 39,872,088 | <p>I have a shell script with ask for the user input. Consider a below example</p>
<p>Test.sh</p>
<pre><code>#!/bin/bash
echo -n "Enter name > "
read text
echo "You entered: $text"
echo -n "Enter age > "
read text
echo "You entered: $text"
echo -n "Enter location > "
read text
echo "You entered: $text"
</code></pre>
<p>Script Execution:</p>
<pre><code>sh test.sh
Enter name> abc
You entered: abc
Enter age > 35
You entered: 35
Enter location > prop
You entered: prop
</code></pre>
<p><em>Now i called this script in python program. I am doing this using sub process module. As far as i know sub process module creates a new process. The problem is when i execute the python script i am not able to pass the parameters to underlying shell script and the scipt is in hault stage. Could some point me where i am doing wrong</em></p>
<p>python script (CHECK.PY):</p>
<pre><code>import subprocess, shlex
cmd = "sh test.sh"
proc = subprocess.Popen(shlex.split(cmd), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout,stderr = proc.communicate()
print stdout
</code></pre>
<p>Python Execution: check.py</p>
<pre><code> python check.py
</code></pre>
| -1 | 2016-10-05T10:55:42Z | 39,872,483 | <p>Actually the subprocess does work - but you are not seeing the prompts because the standard out of the child process is being captured by <code>proc.communicate()</code>. You can confirm this by entering values for the 3 prompts and you should finally see the prompts and your input echoed.</p>
<p>Just remove the <code>stdout=subprocess.PIPE</code> (same for stderr) and the subprocess' stdout (stderr) will go to the terminal.</p>
<p>Or there are other functions that will start a subprocess and call <code>communicate()</code> for you, such as <a href="https://docs.python.org/2/library/subprocess.html#subprocess.call" rel="nofollow"><code>subprocess.call()</code></a> or <a href="https://docs.python.org/2/library/subprocess.html#subprocess.check_call" rel="nofollow"><code>subprocess.check_call()</code></a></p>
| 1 | 2016-10-05T11:15:41Z | [
"python",
"python-2.7",
"shell",
"python-3.x"
]
|
ttk.Widget.state() TclError: Invalid state name | 39,872,172 | <p>I try change ttk.button state (at the beggining of mainloop) in tkinter like in this <a href="http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/ttk-Widget.html" rel="nofollow">manual</a> [actualization: actually <a href="http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/ttk-state-spec.html" rel="nofollow">here</a>.]</p>
<pre><code>import tkinter
from tkinter import ttk
root = tkinter.Tk()
style = ttk.Style()
style.map("C.TButton",
foreground=[('pressed', 'red'), ('active', 'blue')],
background=[('pressed', '!disabled', 'black'), ('active', 'white')]
)
colored_btn = ttk.Button(text="Test", style="C.TButton")
colored_btn.pack()
colored_btn.state('pressed')
root.mainloop()
</code></pre>
<p>Result in error:</p>
<pre><code>in state return self.tk.splitlist(str(self.tk.call(self._w, "state", statespec))) _tkinter.TclError: Invalid state name p
</code></pre>
| 1 | 2016-10-05T10:59:50Z | 39,872,173 | <pre><code>colored_btn.state(('pressed',))
</code></pre>
<p>From <a href="https://docs.python.org/3.4/library/tkinter.ttk.html?highlight=ttk%20style#tkinter.ttk.Widget.state" rel="nofollow">Python Documentation</a>:</p>
<blockquote>
<p>statespec will usually be a list or a tuple.</p>
</blockquote>
<p>I suppose this issue comes from 8.6 vs 8.5 tkinter version difference.</p>
<p>Take notice that in manual linked in question (tkinter 8.5) there is <code>stateSpac</code> argument and in tkinter 8.6 - <code>statespec</code>. Such things should always warn you that there may be changing in versions.</p>
| 1 | 2016-10-05T10:59:50Z | [
"python",
"tkinter",
"tk",
"ttk"
]
|
Communication Loop with a GUI | 39,872,222 | <p>I am making a GUI in Python for a machine. My python program runs on a Raspberry Pi 3 and it is communicating by serial with an Arduino UNO.</p>
<p>I've made a protocol; the arduino sends a "1". The raspberry knows the "1" stands for Run/Stop, and gives back the value of the RunStop variable (which is either 0 or 1). After that the arduino sends a "2". The raspberry knows it stands for the Speed value, and sends back the Speed variable (Which is between 1 and 4).</p>
<p>I've made the 2 following programs that work, but I don't know how to implement it in the GUI. Because when I add it before the <strong>root.mainloop()</strong> , the GUI won't start. And when I put it after, the while loop never starts.</p>
<p>Arduino Code:</p>
<pre><code>int RunStop, Speed = 0;
void setup() {
Serial.begin(9600);
pinMode(13, OUTPUT);
pinMode(12, OUTPUT);
}
void loop() {
Serial.write(1);
delay(2000);
RunStop = Serial.read();
if (RunStop == 1) {
digitalWrite(13, HIGH);
} else {
digitalWrite(13, LOW);
}
delay(2000);
Serial.write(2);
delay(2000);
Speed = Serial.read();
if (Speed == 3) {
digitalWrite(12, HIGH);
} else {
digitalWrite(12, LOW);
}
delay(2000);
}
</code></pre>
<p>Python Communication Code:</p>
<pre><code>import time
import serial
# configure the serial connections (the parameters differs on the device you are connecting to)
ser = serial.Serial(
port='/dev/ttyAMA0',
baudrate=9600,
)
ser.isOpen()
##Status variabelen
RunStop = b'\x01'
Speed = b'\x03'
while 1:
uartIn = ser.read()
print (uartIn)
time.sleep(1)
if uartIn == b'\x01':
ser.write(RunStop)
print ("Run/Stop Register")
elif uartIn == b'\x02':
ser.write(Speed)
print ("Speed Register")
else:
print ("No Register Requested")
</code></pre>
<p>GUI code:</p>
<pre><code>from tkinter import *
import time
import serial
# configure the serial connections (the parameters differs on the device you are connecting to)
ser = serial.Serial(
port='/dev/ttyAMA0',
baudrate=9600,
parity=serial.PARITY_ODD,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS
)
ser.isOpen()
root = Tk()
root.title("Cutter")
## Layout
label_1 = Label(root, text="Pieces")
label_2 = Label(root, text="Length")
entry_1 = Entry(root, width=9)
entry_2 = Entry(root, width=9)
label_1.grid(row=3, sticky=W, padx=(10))
label_2.grid(row=4, sticky=W, padx=(10))
entry_1.grid(row=3, column=1, pady=(10,10))
entry_2.grid(row=4, column=1, pady=(10,15))
runStop = b'\x00'
Speed = b'\x01'
Pieces = b'\x00'
Length = b'\x00'
##pieces OK button function
def piecesOKphase():
x = entry_1.get()
print("pieces: " + x)
##length OK button function
def lengthOKphase():
x = entry_2.get()
print("length: " + x)
def runPhase():
global runStop
runStop = b'\x01'
def stopPhase():
global runStop
runStop = b'\x00'
#OK and RUN / STOP buttons
piecesOK = Button(root, text="OK", command=piecesOKphase)
piecesOK.grid(row=3, column=2)
lengthOK = Button(root, text="OK", command=lengthOKphase)
lengthOK.grid(row=4, column=2)
runButton = Button(root, text="Run", width=6, bg='#58FA58', command=runPhase)
stopButton = Button(root, text="Stop", width=6, bg='#FA5858', command=stopPhase)
runButton.grid(row=0, column=0,padx=(10,10), pady=(10,10))
stopButton.grid(row=0, column=2)
##speed container
CurrentSpeed = 1
def delSpeed():
global CurrentSpeed
global speedLabel
if CurrentSpeed > 1:
CurrentSpeed -= 1
speedLabel.config(text=str(CurrentSpeed))
speedLabel.config(text=CurrentSpeed)
else:
pass
def addSpeed():
global CurrentSpeed
if CurrentSpeed < 4:
CurrentSpeed += 1
speedLabel.config(text=CurrentSpeed)
else:
pass
speedMin = Button(root, text="Speed -", width=6, command=delSpeed)
speedLabel = Label(root, text=CurrentSpeed, font=20)
speedLabel.grid(row=1, column=1, padx=(10))
speedPlus = Button(root, text="Speed +", width=6, command=addSpeed)
speedMin.grid(row=1, column=0)
speedPlus.grid(row=1, column=2)
#Number keyboard functions
def B1phase():
try:
root.focus_get().insert(END, "1")
except AttributeError:
pass
def B2phase():
try:
root.focus_get().insert(END, "2")
except AttributeError:
pass
def B3phase():
try:
root.focus_get().insert(END, "3")
except AttributeError:
pass
def B4phase():
try:
root.focus_get().insert(END, "4")
except AttributeError:
pass
def B5phase():
try:
root.focus_get().insert(END, "5")
except AttributeError:
pass
def B6phase():
try:
root.focus_get().insert(END, "6")
except AttributeError:
pass
def B7phase():
try:
root.focus_get().insert(END, "7")
except AttributeError:
pass
def B8phase():
try:
root.focus_get().insert(END, "8")
except AttributeError:
pass
def B9phase():
try:
root.focus_get().insert(END, "9")
except AttributeError:
pass
def B0phase():
try:
root.focus_get().insert(END, "0")
except AttributeError:
pass
def clearPhase():
try:
root.focus_get().delete(0, 'end')
except AttributeError:
pass
## Number keyboard buttons
B1 = Button(root, text="1", width=6, command=B1phase)
B2 = Button(root, text="2", width=6, command=B2phase)
B3 = Button(root, text="3", width=6, command=B3phase)
B4 = Button(root, text="4", width=6, command=B4phase)
B5 = Button(root, text="5", width=6, command=B5phase)
B6 = Button(root, text="6", width=6, command=B6phase)
B7 = Button(root, text="7", width=6, command=B7phase)
B8 = Button(root, text="8", width=6, command=B8phase)
B9 = Button(root, text="9", width=6, command=B9phase)
B0 = Button(root, text="0", width=6, command=B0phase)
clearButton = Button(root, text="Clear", width=6, bg='#FA5858', command=clearPhase)
B1.grid(row=5, column=0)
B2.grid(row=5, column=1)
B3.grid(row=5, column=2, padx=(10,10))
B4.grid(row=6, column=0)
B5.grid(row=6, column=1)
B6.grid(row=6, column=2, padx=(10,10))
B7.grid(row=7, column=0)
B8.grid(row=7, column=1)
B9.grid(row=7, column=2, padx=(10,10))
B0.grid(row=8, column=1)
clearButton.grid(row=8, column=0)
## Manual
label_4 = Label(root, text="")
label_4.grid(row=2, sticky=W)
label_3 = Label(root, text="Manual")
label_3.grid(row=9, sticky=W, padx=(10), pady=(10,10))
manualCut = Button(root, text="Cut", width=4)
manualCut.grid(row=10, column=0, pady=(1,15))
manualFeed = Button(root, text="Feed", width=4)
manualFeed.grid(row=10, column=1, pady=(1,15))
# Test function
def testPhase():
print (CurrentSpeed)
manualTest = Button(root, text="Test", width=4, command=testPhase)
manualTest.grid(row=10, column=2, pady=(1,15))
## OTHER
root.mainloop()
</code></pre>
<p><strong>EDIT</strong></p>
<p>I have used the <strong>after</strong> from Tkinter.</p>
<p>The GUI starts, and the while loop runs. But I cannot click on any buttons.</p>
<pre><code>from tkinter import *
import time
import serial
# configure the serial connections (the parameters differs on the device you are connecting to)
ser = serial.Serial(
port='/dev/ttyAMA0',
baudrate=9600,
parity=serial.PARITY_ODD,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS
)
ser.isOpen()
## GUI Title
root = Tk()
root.title("Cutter")
##Communication
RunStop = b'\x01' ## 0 = OFF, 1 = ON
Speed = b'\x03' ## 1, 2, 3, 4
CurrentSpeed = 1
Pieces = b'\x00'
Pieces100 = b'\x00'
Pieces10 = b'\x00'
Pieces1 = b'\x00'
length10000 = b'\x00'
Length1000 = b'\x00'
Length100 = b'\x00'
Length10 = b'\x00'
Length1 = b'\x00'
def Communication():
while 1:
uartIn = ser.read()
print (uartIn)
time.sleep(1)
if uartIn == b'\x01':
ser.write(RunStop)
print ("Run/Stop Register")
elif uartIn == b'\x02':
ser.write(Speed)
print ("Speed Register")
else:
print ("No Register Requested")
root.after(500, Communication)
## Functions
def runBOT():
global RunStop
RunStop = b'\x01'
def stopBOT():
global RunStop
RunStop = b'\x00'
def delSpeedBOT():
global CurrentSpeed
global speedLabel
if CurrentSpeed > 1:
CurrentSpeed -= 1
speedLabel.config(text=str(CurrentSpeed))
speedLabel.config(text=CurrentSpeed)
else:
pass
def addSpeedBOT():
global CurrentSpeed
if CurrentSpeed < 4:
CurrentSpeed += 1
speedLabel.config(text=CurrentSpeed)
else:
pass
def piecesBOT():
x = entryPieces.get()
print("pieces: " + x)
def lengthBOT():
x = entryLength.get()
print("length: " + x)
## Layout
labelPieces = Label(root, text="Pieces")
labelLength = Label(root, text="Length")
entryPieces = Entry(root, width=9)
entryLength = Entry(root, width=9)
labelPieces.grid(row=3, sticky=W, padx=(10))
labelLength.grid(row=4, sticky=W, padx=(10))
entryPieces.grid(row=3, column=1, pady=(10,10))
entryLength.grid(row=4, column=1, pady=(10,15))
## Buttons
runButton = Button(root, text="Run", width=6, bg='#58FA58', command=runBOT)
runButton.grid(row=0, column=0,padx=(10,10), pady=(10,10))
stopButton = Button(root, text="Stop", width=6, bg='#FA5858', command=stopBOT)
stopButton.grid(row=0, column=2)
speedMin = Button(root, text="Speed -", width=6, command=delSpeedBOT)
speedMin.grid(row=1, column=0)
speedLabel = Label(root, text=CurrentSpeed, font=20)
speedLabel.grid(row=1, column=1, padx=(10))
speedPlus = Button(root, text="Speed +", width=6, command=addSpeedBOT)
speedPlus.grid(row=1, column=2)
piecesOK = Button(root, text="OK", command=piecesBOT)
piecesOK.grid(row=3, column=2)
lengthOK = Button(root, text="OK", command=lengthBOT)
lengthOK.grid(row=4, column=2)
#Number keyboard functions
def B1phase():
try:
root.focus_get().insert(END, "1")
except AttributeError:
pass
def B2phase():
try:
root.focus_get().insert(END, "2")
except AttributeError:
pass
def B3phase():
try:
root.focus_get().insert(END, "3")
except AttributeError:
pass
def B4phase():
try:
root.focus_get().insert(END, "4")
except AttributeError:
pass
def B5phase():
try:
root.focus_get().insert(END, "5")
except AttributeError:
pass
def B6phase():
try:
root.focus_get().insert(END, "6")
except AttributeError:
pass
def B7phase():
try:
root.focus_get().insert(END, "7")
except AttributeError:
pass
def B8phase():
try:
root.focus_get().insert(END, "8")
except AttributeError:
pass
def B9phase():
try:
root.focus_get().insert(END, "9")
except AttributeError:
pass
def B0phase():
try:
root.focus_get().insert(END, "0")
except AttributeError:
pass
def clearPhase():
try:
root.focus_get().delete(0, 'end')
except AttributeError:
pass
## Number keyboard buttons
B1 = Button(root, text="1", width=6, command=B1phase)
B2 = Button(root, text="2", width=6, command=B2phase)
B3 = Button(root, text="3", width=6, command=B3phase)
B4 = Button(root, text="4", width=6, command=B4phase)
B5 = Button(root, text="5", width=6, command=B5phase)
B6 = Button(root, text="6", width=6, command=B6phase)
B7 = Button(root, text="7", width=6, command=B7phase)
B8 = Button(root, text="8", width=6, command=B8phase)
B9 = Button(root, text="9", width=6, command=B9phase)
B0 = Button(root, text="0", width=6, command=B0phase)
clearButton = Button(root, text="Clear", width=6, bg='#FA5858', command=clearPhase)
B1.grid(row=5, column=0)
B2.grid(row=5, column=1)
B3.grid(row=5, column=2, padx=(10,10))
B4.grid(row=6, column=0)
B5.grid(row=6, column=1)
B6.grid(row=6, column=2, padx=(10,10))
B7.grid(row=7, column=0)
B8.grid(row=7, column=1)
B9.grid(row=7, column=2, padx=(10,10))
B0.grid(row=8, column=1)
clearButton.grid(row=8, column=0)
## Manual
label_4 = Label(root, text="")
label_4.grid(row=2, sticky=W)
label_3 = Label(root, text="Manual")
label_3.grid(row=9, sticky=W, padx=(10), pady=(10,10))
manualCut = Button(root, text="Cut", width=4)
manualCut.grid(row=10, column=0, pady=(1,15))
manualFeed = Button(root, text="Feed", width=4)
manualFeed.grid(row=10, column=1, pady=(1,15))
# Test function
def testPhase():
pass
manualTest = Button(root, text="Test", width=4, command=testPhase)
manualTest.grid(row=10, column=2, pady=(1,15))
## Running GUI and communication
root.after(500, Communication)
root.mainloop()
</code></pre>
<p>This doesn't work:
Communication()
root.mainloop()</p>
| -2 | 2016-10-05T11:01:56Z | 39,872,771 | <p>Use the Tkinter .after method to periodically call the code that you use to read data from the serial port.</p>
<p><a href="http://effbot.org/tkinterbook/widget.htm" rel="nofollow">http://effbot.org/tkinterbook/widget.htm</a></p>
<p><a href="http://stackoverflow.com/questions/25753632/tkinter-how-to-use-after-method">tkinter: how to use after method</a></p>
<p>Tkinter needs to be able to process the UI so placing any loop in the code means that the UI becomes un-responsive. Using .after allows you to periodically schedule tasks to run.</p>
| 1 | 2016-10-05T11:28:57Z | [
"python",
"tkinter",
"arduino",
"pyserial",
"raspberry-pi3"
]
|
Communication Loop with a GUI | 39,872,222 | <p>I am making a GUI in Python for a machine. My python program runs on a Raspberry Pi 3 and it is communicating by serial with an Arduino UNO.</p>
<p>I've made a protocol; the arduino sends a "1". The raspberry knows the "1" stands for Run/Stop, and gives back the value of the RunStop variable (which is either 0 or 1). After that the arduino sends a "2". The raspberry knows it stands for the Speed value, and sends back the Speed variable (Which is between 1 and 4).</p>
<p>I've made the 2 following programs that work, but I don't know how to implement it in the GUI. Because when I add it before the <strong>root.mainloop()</strong> , the GUI won't start. And when I put it after, the while loop never starts.</p>
<p>Arduino Code:</p>
<pre><code>int RunStop, Speed = 0;
void setup() {
Serial.begin(9600);
pinMode(13, OUTPUT);
pinMode(12, OUTPUT);
}
void loop() {
Serial.write(1);
delay(2000);
RunStop = Serial.read();
if (RunStop == 1) {
digitalWrite(13, HIGH);
} else {
digitalWrite(13, LOW);
}
delay(2000);
Serial.write(2);
delay(2000);
Speed = Serial.read();
if (Speed == 3) {
digitalWrite(12, HIGH);
} else {
digitalWrite(12, LOW);
}
delay(2000);
}
</code></pre>
<p>Python Communication Code:</p>
<pre><code>import time
import serial
# configure the serial connections (the parameters differs on the device you are connecting to)
ser = serial.Serial(
port='/dev/ttyAMA0',
baudrate=9600,
)
ser.isOpen()
##Status variabelen
RunStop = b'\x01'
Speed = b'\x03'
while 1:
uartIn = ser.read()
print (uartIn)
time.sleep(1)
if uartIn == b'\x01':
ser.write(RunStop)
print ("Run/Stop Register")
elif uartIn == b'\x02':
ser.write(Speed)
print ("Speed Register")
else:
print ("No Register Requested")
</code></pre>
<p>GUI code:</p>
<pre><code>from tkinter import *
import time
import serial
# configure the serial connections (the parameters differs on the device you are connecting to)
ser = serial.Serial(
port='/dev/ttyAMA0',
baudrate=9600,
parity=serial.PARITY_ODD,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS
)
ser.isOpen()
root = Tk()
root.title("Cutter")
## Layout
label_1 = Label(root, text="Pieces")
label_2 = Label(root, text="Length")
entry_1 = Entry(root, width=9)
entry_2 = Entry(root, width=9)
label_1.grid(row=3, sticky=W, padx=(10))
label_2.grid(row=4, sticky=W, padx=(10))
entry_1.grid(row=3, column=1, pady=(10,10))
entry_2.grid(row=4, column=1, pady=(10,15))
runStop = b'\x00'
Speed = b'\x01'
Pieces = b'\x00'
Length = b'\x00'
##pieces OK button function
def piecesOKphase():
x = entry_1.get()
print("pieces: " + x)
##length OK button function
def lengthOKphase():
x = entry_2.get()
print("length: " + x)
def runPhase():
global runStop
runStop = b'\x01'
def stopPhase():
global runStop
runStop = b'\x00'
#OK and RUN / STOP buttons
piecesOK = Button(root, text="OK", command=piecesOKphase)
piecesOK.grid(row=3, column=2)
lengthOK = Button(root, text="OK", command=lengthOKphase)
lengthOK.grid(row=4, column=2)
runButton = Button(root, text="Run", width=6, bg='#58FA58', command=runPhase)
stopButton = Button(root, text="Stop", width=6, bg='#FA5858', command=stopPhase)
runButton.grid(row=0, column=0,padx=(10,10), pady=(10,10))
stopButton.grid(row=0, column=2)
##speed container
CurrentSpeed = 1
def delSpeed():
global CurrentSpeed
global speedLabel
if CurrentSpeed > 1:
CurrentSpeed -= 1
speedLabel.config(text=str(CurrentSpeed))
speedLabel.config(text=CurrentSpeed)
else:
pass
def addSpeed():
global CurrentSpeed
if CurrentSpeed < 4:
CurrentSpeed += 1
speedLabel.config(text=CurrentSpeed)
else:
pass
speedMin = Button(root, text="Speed -", width=6, command=delSpeed)
speedLabel = Label(root, text=CurrentSpeed, font=20)
speedLabel.grid(row=1, column=1, padx=(10))
speedPlus = Button(root, text="Speed +", width=6, command=addSpeed)
speedMin.grid(row=1, column=0)
speedPlus.grid(row=1, column=2)
#Number keyboard functions
def B1phase():
try:
root.focus_get().insert(END, "1")
except AttributeError:
pass
def B2phase():
try:
root.focus_get().insert(END, "2")
except AttributeError:
pass
def B3phase():
try:
root.focus_get().insert(END, "3")
except AttributeError:
pass
def B4phase():
try:
root.focus_get().insert(END, "4")
except AttributeError:
pass
def B5phase():
try:
root.focus_get().insert(END, "5")
except AttributeError:
pass
def B6phase():
try:
root.focus_get().insert(END, "6")
except AttributeError:
pass
def B7phase():
try:
root.focus_get().insert(END, "7")
except AttributeError:
pass
def B8phase():
try:
root.focus_get().insert(END, "8")
except AttributeError:
pass
def B9phase():
try:
root.focus_get().insert(END, "9")
except AttributeError:
pass
def B0phase():
try:
root.focus_get().insert(END, "0")
except AttributeError:
pass
def clearPhase():
try:
root.focus_get().delete(0, 'end')
except AttributeError:
pass
## Number keyboard buttons
B1 = Button(root, text="1", width=6, command=B1phase)
B2 = Button(root, text="2", width=6, command=B2phase)
B3 = Button(root, text="3", width=6, command=B3phase)
B4 = Button(root, text="4", width=6, command=B4phase)
B5 = Button(root, text="5", width=6, command=B5phase)
B6 = Button(root, text="6", width=6, command=B6phase)
B7 = Button(root, text="7", width=6, command=B7phase)
B8 = Button(root, text="8", width=6, command=B8phase)
B9 = Button(root, text="9", width=6, command=B9phase)
B0 = Button(root, text="0", width=6, command=B0phase)
clearButton = Button(root, text="Clear", width=6, bg='#FA5858', command=clearPhase)
B1.grid(row=5, column=0)
B2.grid(row=5, column=1)
B3.grid(row=5, column=2, padx=(10,10))
B4.grid(row=6, column=0)
B5.grid(row=6, column=1)
B6.grid(row=6, column=2, padx=(10,10))
B7.grid(row=7, column=0)
B8.grid(row=7, column=1)
B9.grid(row=7, column=2, padx=(10,10))
B0.grid(row=8, column=1)
clearButton.grid(row=8, column=0)
## Manual
label_4 = Label(root, text="")
label_4.grid(row=2, sticky=W)
label_3 = Label(root, text="Manual")
label_3.grid(row=9, sticky=W, padx=(10), pady=(10,10))
manualCut = Button(root, text="Cut", width=4)
manualCut.grid(row=10, column=0, pady=(1,15))
manualFeed = Button(root, text="Feed", width=4)
manualFeed.grid(row=10, column=1, pady=(1,15))
# Test function
def testPhase():
print (CurrentSpeed)
manualTest = Button(root, text="Test", width=4, command=testPhase)
manualTest.grid(row=10, column=2, pady=(1,15))
## OTHER
root.mainloop()
</code></pre>
<p><strong>EDIT</strong></p>
<p>I have used the <strong>after</strong> from Tkinter.</p>
<p>The GUI starts, and the while loop runs. But I cannot click on any buttons.</p>
<pre><code>from tkinter import *
import time
import serial
# configure the serial connections (the parameters differs on the device you are connecting to)
ser = serial.Serial(
port='/dev/ttyAMA0',
baudrate=9600,
parity=serial.PARITY_ODD,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS
)
ser.isOpen()
## GUI Title
root = Tk()
root.title("Cutter")
##Communication
RunStop = b'\x01' ## 0 = OFF, 1 = ON
Speed = b'\x03' ## 1, 2, 3, 4
CurrentSpeed = 1
Pieces = b'\x00'
Pieces100 = b'\x00'
Pieces10 = b'\x00'
Pieces1 = b'\x00'
length10000 = b'\x00'
Length1000 = b'\x00'
Length100 = b'\x00'
Length10 = b'\x00'
Length1 = b'\x00'
def Communication():
while 1:
uartIn = ser.read()
print (uartIn)
time.sleep(1)
if uartIn == b'\x01':
ser.write(RunStop)
print ("Run/Stop Register")
elif uartIn == b'\x02':
ser.write(Speed)
print ("Speed Register")
else:
print ("No Register Requested")
root.after(500, Communication)
## Functions
def runBOT():
global RunStop
RunStop = b'\x01'
def stopBOT():
global RunStop
RunStop = b'\x00'
def delSpeedBOT():
global CurrentSpeed
global speedLabel
if CurrentSpeed > 1:
CurrentSpeed -= 1
speedLabel.config(text=str(CurrentSpeed))
speedLabel.config(text=CurrentSpeed)
else:
pass
def addSpeedBOT():
global CurrentSpeed
if CurrentSpeed < 4:
CurrentSpeed += 1
speedLabel.config(text=CurrentSpeed)
else:
pass
def piecesBOT():
x = entryPieces.get()
print("pieces: " + x)
def lengthBOT():
x = entryLength.get()
print("length: " + x)
## Layout
labelPieces = Label(root, text="Pieces")
labelLength = Label(root, text="Length")
entryPieces = Entry(root, width=9)
entryLength = Entry(root, width=9)
labelPieces.grid(row=3, sticky=W, padx=(10))
labelLength.grid(row=4, sticky=W, padx=(10))
entryPieces.grid(row=3, column=1, pady=(10,10))
entryLength.grid(row=4, column=1, pady=(10,15))
## Buttons
runButton = Button(root, text="Run", width=6, bg='#58FA58', command=runBOT)
runButton.grid(row=0, column=0,padx=(10,10), pady=(10,10))
stopButton = Button(root, text="Stop", width=6, bg='#FA5858', command=stopBOT)
stopButton.grid(row=0, column=2)
speedMin = Button(root, text="Speed -", width=6, command=delSpeedBOT)
speedMin.grid(row=1, column=0)
speedLabel = Label(root, text=CurrentSpeed, font=20)
speedLabel.grid(row=1, column=1, padx=(10))
speedPlus = Button(root, text="Speed +", width=6, command=addSpeedBOT)
speedPlus.grid(row=1, column=2)
piecesOK = Button(root, text="OK", command=piecesBOT)
piecesOK.grid(row=3, column=2)
lengthOK = Button(root, text="OK", command=lengthBOT)
lengthOK.grid(row=4, column=2)
#Number keyboard functions
def B1phase():
try:
root.focus_get().insert(END, "1")
except AttributeError:
pass
def B2phase():
try:
root.focus_get().insert(END, "2")
except AttributeError:
pass
def B3phase():
try:
root.focus_get().insert(END, "3")
except AttributeError:
pass
def B4phase():
try:
root.focus_get().insert(END, "4")
except AttributeError:
pass
def B5phase():
try:
root.focus_get().insert(END, "5")
except AttributeError:
pass
def B6phase():
try:
root.focus_get().insert(END, "6")
except AttributeError:
pass
def B7phase():
try:
root.focus_get().insert(END, "7")
except AttributeError:
pass
def B8phase():
try:
root.focus_get().insert(END, "8")
except AttributeError:
pass
def B9phase():
try:
root.focus_get().insert(END, "9")
except AttributeError:
pass
def B0phase():
try:
root.focus_get().insert(END, "0")
except AttributeError:
pass
def clearPhase():
try:
root.focus_get().delete(0, 'end')
except AttributeError:
pass
## Number keyboard buttons
B1 = Button(root, text="1", width=6, command=B1phase)
B2 = Button(root, text="2", width=6, command=B2phase)
B3 = Button(root, text="3", width=6, command=B3phase)
B4 = Button(root, text="4", width=6, command=B4phase)
B5 = Button(root, text="5", width=6, command=B5phase)
B6 = Button(root, text="6", width=6, command=B6phase)
B7 = Button(root, text="7", width=6, command=B7phase)
B8 = Button(root, text="8", width=6, command=B8phase)
B9 = Button(root, text="9", width=6, command=B9phase)
B0 = Button(root, text="0", width=6, command=B0phase)
clearButton = Button(root, text="Clear", width=6, bg='#FA5858', command=clearPhase)
B1.grid(row=5, column=0)
B2.grid(row=5, column=1)
B3.grid(row=5, column=2, padx=(10,10))
B4.grid(row=6, column=0)
B5.grid(row=6, column=1)
B6.grid(row=6, column=2, padx=(10,10))
B7.grid(row=7, column=0)
B8.grid(row=7, column=1)
B9.grid(row=7, column=2, padx=(10,10))
B0.grid(row=8, column=1)
clearButton.grid(row=8, column=0)
## Manual
label_4 = Label(root, text="")
label_4.grid(row=2, sticky=W)
label_3 = Label(root, text="Manual")
label_3.grid(row=9, sticky=W, padx=(10), pady=(10,10))
manualCut = Button(root, text="Cut", width=4)
manualCut.grid(row=10, column=0, pady=(1,15))
manualFeed = Button(root, text="Feed", width=4)
manualFeed.grid(row=10, column=1, pady=(1,15))
# Test function
def testPhase():
pass
manualTest = Button(root, text="Test", width=4, command=testPhase)
manualTest.grid(row=10, column=2, pady=(1,15))
## Running GUI and communication
root.after(500, Communication)
root.mainloop()
</code></pre>
<p>This doesn't work:
Communication()
root.mainloop()</p>
| -2 | 2016-10-05T11:01:56Z | 39,876,188 | <p><strong>Assuming you can do a non-blocking read on the serial port</strong>, you can write a function that reads the serial port, and then schedules itself to be called again after a delay. </p>
<p>For example:</p>
<pre><code>def poll_serial(root):
uartIn = ser.read()
if uartIn:
process_value_from_serial(uartIn)
root.after(1000, poll_serial, root)
</code></pre>
<p>In your main program, you call this immediately before starting <code>mainloop</code> and it will run every second for the life of the program.</p>
<pre><code>root = Tk()
...
poll_serial(root)
root.mainloop()
</code></pre>
<p><strong>If calling <code>ser.read()</code> blocks</strong>, you can modify the polling function to look like this<sup>1</sup>:</p>
<pre><code>def poll_serial(root):
if (ser.inWaiting()>0):
uartIn = ser.read()
if uartIn:
process_value_from_serial(uartIn)
root.after(1000, poll_serial, root)
</code></pre>
<p><sup>1</sup> Code for checking the serial port before reading came from this answer: <a href="http://stackoverflow.com/a/38758773/7432">http://stackoverflow.com/a/38758773/7432</a></p>
| 0 | 2016-10-05T14:06:38Z | [
"python",
"tkinter",
"arduino",
"pyserial",
"raspberry-pi3"
]
|
execute curl command in python | 39,872,317 | <p>I have already gone through few StackOverflow existing links for this query, did not help me.</p>
<p>I would like to run few curl command(4) and each curl commands give output. From that output, I would like to parse the few group ids for next command.</p>
<pre><code>curl --basic -u admin:admin -d \'{ "name" : "test-dev" }\' --header \'Content-Type: application/json\' http://localhost:8080/mmc/api/serverGroups
</code></pre>
<p>I have tried with as ,</p>
<pre><code>#!/usr/bin/python
import subprocess
bash_com = 'curl --basic -u admin:admin -d '{ "name" : "test-dev" }' --header 'Content-Type: application/json' http://localhost:8080/mmc/api/serverGroups'
subprocess.Popen(bash_com)
output = subprocess.check_output(['bash','-c', bash_com]) # subprocess has check_output method
</code></pre>
<p>It gives me the syntax error, though I have changed from a single quote to double quote for that curl command.</p>
<p>I have been trying with Pycurl but i have to look more into that. Is there any way we can run curl commands in python and can parse the output values and pass it to next curl command.</p>
| 0 | 2016-10-05T11:07:04Z | 39,872,990 | <p>You can use os.popen with</p>
<pre><code>fh = os.popen(bash_com, 'r')
data = fh.read()
fh.close()
</code></pre>
<p>Or you can use subprocess like this</p>
<pre><code>cmds = ['ls', '-l', ]
try:
output = subprocess.check_output(cmds, stderr=subprocess.STDOUT)
retcode = 0
except subprocess.CalledProcessError, e:
retcode = e.returncode
output = e.output
print output
</code></pre>
<p>There you have to organize your command and params in a list.</p>
<p>Or you just go the easy way and use requests.get(...).</p>
<p><strong>And do not forget:</strong> Using popen you can get shell injections via parameters of your command! </p>
| 0 | 2016-10-05T11:40:11Z | [
"python",
"curl",
"esb"
]
|
execute curl command in python | 39,872,317 | <p>I have already gone through few StackOverflow existing links for this query, did not help me.</p>
<p>I would like to run few curl command(4) and each curl commands give output. From that output, I would like to parse the few group ids for next command.</p>
<pre><code>curl --basic -u admin:admin -d \'{ "name" : "test-dev" }\' --header \'Content-Type: application/json\' http://localhost:8080/mmc/api/serverGroups
</code></pre>
<p>I have tried with as ,</p>
<pre><code>#!/usr/bin/python
import subprocess
bash_com = 'curl --basic -u admin:admin -d '{ "name" : "test-dev" }' --header 'Content-Type: application/json' http://localhost:8080/mmc/api/serverGroups'
subprocess.Popen(bash_com)
output = subprocess.check_output(['bash','-c', bash_com]) # subprocess has check_output method
</code></pre>
<p>It gives me the syntax error, though I have changed from a single quote to double quote for that curl command.</p>
<p>I have been trying with Pycurl but i have to look more into that. Is there any way we can run curl commands in python and can parse the output values and pass it to next curl command.</p>
| 0 | 2016-10-05T11:07:04Z | 39,873,420 | <p>Better output using os.open(bash_com,'r') and then fh.read()</p>
<h1>python api.py</h1>
<p>% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
199 172 0 172 0 27 3948 619 --:--:-- --:--:-- --:--:-- 4027
<strong>{"href":"<a href="http://localhost:8080/mmc/api/serverGroups/39a28908-3fae-4903-adb5-06a3b7bb06d8" rel="nofollow">http://localhost:8080/mmc/api/serverGroups/39a28908-3fae-4903-adb5-06a3b7bb06d8</a>","serverCount":0,"name":"test-dev","id":"39a28908-3fae-4903-adb5-06a3b7bb06d8"}</strong></p>
<p>trying understand that fh.read() has executed the curl command? please correct me</p>
| 0 | 2016-10-05T12:02:16Z | [
"python",
"curl",
"esb"
]
|
execute curl command in python | 39,872,317 | <p>I have already gone through few StackOverflow existing links for this query, did not help me.</p>
<p>I would like to run few curl command(4) and each curl commands give output. From that output, I would like to parse the few group ids for next command.</p>
<pre><code>curl --basic -u admin:admin -d \'{ "name" : "test-dev" }\' --header \'Content-Type: application/json\' http://localhost:8080/mmc/api/serverGroups
</code></pre>
<p>I have tried with as ,</p>
<pre><code>#!/usr/bin/python
import subprocess
bash_com = 'curl --basic -u admin:admin -d '{ "name" : "test-dev" }' --header 'Content-Type: application/json' http://localhost:8080/mmc/api/serverGroups'
subprocess.Popen(bash_com)
output = subprocess.check_output(['bash','-c', bash_com]) # subprocess has check_output method
</code></pre>
<p>It gives me the syntax error, though I have changed from a single quote to double quote for that curl command.</p>
<p>I have been trying with Pycurl but i have to look more into that. Is there any way we can run curl commands in python and can parse the output values and pass it to next curl command.</p>
| 0 | 2016-10-05T11:07:04Z | 39,909,997 | <p>I am trying to redirect the curl commands output to text file and then parse the file via JSON. All I am trying to get "id" from about output.</p>
<pre><code>fh = os.popen(bash_com,'r')
data = fh.read()
newf = open("/var/tmp/t1.txt",'w')
sys.stdout = newf
print data
with open("/var/tmp/t1.txt") as json_data:
j = json.load(json_data)
print j['id']
</code></pre>
<p>I have checked the files content in JSONlint.com and got VALID JSON on it. It is throwing "ValueError: No JSON object could be decoded" at json.load line. Is there anything need to perform before parsing the redirected file.</p>
| 0 | 2016-10-07T05:23:57Z | [
"python",
"curl",
"esb"
]
|
No module named sqlite | 39,872,465 | <p>i am a beginner i need to create a python virtual_environment for installing Django. I am using the following steps for installing python and virtualenv </p>
<pre><code>cd /usr/src/
wget http://www.python.org/ftp/python/3.5.1./Python-3.5.1.tgz
tar zxf Python-3.5.1.tgz
cd python-3.5.1
mkdir /usr/local/python-3.5
./configure --prefix=/usr/local/python'.$python.' --with-threads --enable-shared --with-zlib=/usr/include && make && make altinstall
echo "/usr/local/python3.5/lib" > python3.5.conf
mv python3.5.conf /etc/ld.so.conf.d/python3.5.conf
/sbin/ldconfig
ln -sfn /usr/local/python3.5/bin/python3.5 /usr/bin/python3.5
wget https://pypi.python.org/packages/source/s/setuptools/setuptools-11.3.1.tar.gz
tar xzf setuptools-11.3.1.tar.gz
cd setuptools-11.3.1
/usr/local/python3.5/bin/python3.5 setup.py install
/usr/local/python3.5/bin/easy_install-3.5 pip
ln -sfn /usr/local/python3.5/bin/pip3.5 /usr/bin/pip3.5
/usr/local/python3.5/bin/pip3.5 install virtualenv
</code></pre>
<p>then i am created a virtualenv based on this,
and enter into python shell and use </p>
<pre><code>import sqlite
</code></pre>
<p>i got following error</p>
<pre><code>Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named 'sqlite'
</code></pre>
<p>And i tried to run a django project installed in the virtalenv i got following errors.</p>
<pre><code>raise ImproperlyConfigured("Error loading either pysqlite2 or sqlite3 modules (tried in that order): %s" % exc)
django.core.exceptions.ImproperlyConfigured: Error loading either pysqlite2 or sqlite3 modules (tried in that order): No module named '_sqlite3'
</code></pre>
<p>I am using CentOS release 6.8 (Final).</p>
| -2 | 2016-10-05T11:14:52Z | 39,872,597 | <p>The python-bundled sqlite package is called <code>sqlite3</code>:
<a href="https://docs.python.org/3.6/library/sqlite3.html" rel="nofollow">https://docs.python.org/3.6/library/sqlite3.html</a></p>
<p>So, just do </p>
<pre><code>import sqlite3
</code></pre>
<p>and you should be good.</p>
<p><strong>EDIT</strong></p>
<p>I only now realized that you're building python yourself. So that's probably why the sqlite3 module is missing. Check the output of the configure call whether sqlite3 is mentioned.
I assume you'd have to get the development packages.</p>
| 1 | 2016-10-05T11:20:52Z | [
"python",
"django",
"virtualenv"
]
|
No module named sqlite | 39,872,465 | <p>i am a beginner i need to create a python virtual_environment for installing Django. I am using the following steps for installing python and virtualenv </p>
<pre><code>cd /usr/src/
wget http://www.python.org/ftp/python/3.5.1./Python-3.5.1.tgz
tar zxf Python-3.5.1.tgz
cd python-3.5.1
mkdir /usr/local/python-3.5
./configure --prefix=/usr/local/python'.$python.' --with-threads --enable-shared --with-zlib=/usr/include && make && make altinstall
echo "/usr/local/python3.5/lib" > python3.5.conf
mv python3.5.conf /etc/ld.so.conf.d/python3.5.conf
/sbin/ldconfig
ln -sfn /usr/local/python3.5/bin/python3.5 /usr/bin/python3.5
wget https://pypi.python.org/packages/source/s/setuptools/setuptools-11.3.1.tar.gz
tar xzf setuptools-11.3.1.tar.gz
cd setuptools-11.3.1
/usr/local/python3.5/bin/python3.5 setup.py install
/usr/local/python3.5/bin/easy_install-3.5 pip
ln -sfn /usr/local/python3.5/bin/pip3.5 /usr/bin/pip3.5
/usr/local/python3.5/bin/pip3.5 install virtualenv
</code></pre>
<p>then i am created a virtualenv based on this,
and enter into python shell and use </p>
<pre><code>import sqlite
</code></pre>
<p>i got following error</p>
<pre><code>Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named 'sqlite'
</code></pre>
<p>And i tried to run a django project installed in the virtalenv i got following errors.</p>
<pre><code>raise ImproperlyConfigured("Error loading either pysqlite2 or sqlite3 modules (tried in that order): %s" % exc)
django.core.exceptions.ImproperlyConfigured: Error loading either pysqlite2 or sqlite3 modules (tried in that order): No module named '_sqlite3'
</code></pre>
<p>I am using CentOS release 6.8 (Final).</p>
| -2 | 2016-10-05T11:14:52Z | 39,879,388 | <p>Any reason you are not using the <a href="https://fedoraproject.org/wiki/EPEL" rel="nofollow">EPEL Repository</a> to install python?</p>
| 0 | 2016-10-05T16:33:13Z | [
"python",
"django",
"virtualenv"
]
|
Convert image into 4x4 non-overlapping blocks | 39,872,556 | <p>I want to divide an image into 4x4 non-overlapping blocks in python and then convert that block into array of 16 element.</p>
| -1 | 2016-10-05T11:19:09Z | 39,872,931 | <p>I recommend using a quality-library like <a href="http://scikit-image.org/" rel="nofollow">scikit-image</a>, especially if there are more steps needed in the future. It is based on numpy/scipy.</p>
<p>A kind of minimal example (<a href="http://scikit-image.org/docs/dev/auto_examples/numpy_operations/plot_view_as_blocks.html?highlight=block" rel="nofollow">from the docs</a>) would be the following.</p>
<h3>Code:</h3>
<pre><code>from skimage import data
from skimage import color
from skimage.util import view_as_blocks
# get astronaut from skimage.data in grayscale
l = color.rgb2gray(data.astronaut())
# size of blocks
block_shape = (4, 4)
# see astronaut as a matrix of blocks (of shape block_shape)
view = view_as_blocks(l, block_shape)
# collapse the last two dimensions in one
flatten_view = view.reshape(view.shape[0], view.shape[1], -1)
print(flatten_view.shape)
</code></pre>
<h3>Output</h3>
<pre><code>(128, 128, 16) # 128x128 blocks a 16 elements each
</code></pre>
| 0 | 2016-10-05T11:36:56Z | [
"python",
"image-processing"
]
|
How to execute multi query from list at once time in Python? | 39,872,583 | <p>I'm using Tornado and Postgres, I have some queries (4 or 5) that I appended to the list during program and now I want to execute all of them at once time! </p>
<p>when I tried to execute I got error that was: </p>
<pre><code>"DummyFuture does not support blocking for results"
</code></pre>
<p>I executed this code: </p>
<pre><code> yield self.db.execute(''.join(queries)).result()
</code></pre>
<p>"queries" is list of queries! </p>
<p>This is my connection pool and also Tonado setting:</p>
<pre><code>ioloop = IOLoop.instance()
application.db = momoko.Pool(
dsn='dbname=xxx user=xxx password=xxxx host=x port=xxxx'
size=xx,
ioloop=ioloop,
)
# this is a one way to run ioloop in sync
future = application.db.connect()
ioloop.add_future(future, lambda f: ioloop.stop())
ioloop.start()
future.result() # raises exception on connection error
http_server = HTTPServer(application)
http_server.listen(8888, 'localhost')
ioloop.start()
</code></pre>
| 0 | 2016-10-05T11:20:03Z | 39,874,471 | <p>Don't call <code>result()</code> on a Future in a Tornado coroutine. Get results like this:</p>
<pre><code>@gen.coroutine
def method(self):
result = yield self.db.execute('...')
</code></pre>
<p>Also, I don't think it will work to just join your queries as strings. The outcome won't be valid SQL. Instead:</p>
<pre><code>@gen.coroutine
def method(self):
results = yield [self.db.execute(q) for q in queries]
</code></pre>
| 1 | 2016-10-05T12:51:17Z | [
"python",
"postgresql",
"tornado"
]
|
how to remove rows and count it in same file opening | 39,872,614 | <p>I am trying to open CSV file and remove some rows from it according to given list, on same progress I want to count those rows for future usage. </p>
<p>Each file opening works great on separately, how can I combine them on same open file progress? </p>
<p>My current code is : </p>
<pre><code># read latest file and count rows
with open(fileslst[-1], 'rb') as csvfile:
csvReader = csv.reader(csvfile)
for row in csvReader:
for alert in alertsCode:
if any(alert in row[11] for s in alertsCode) :
counter=counter+1
print (str(counter)+" unnecessary codes in this file")
#open and modify the latest file
with open(fileslst[-1], 'rb') as csvfile:
csvReader = csv.reader(csvfile)
clean_rows = [row for row in csvReader if not any(alert in row[11] for alert in alertsCode)]
with open(fileslst[-1], 'wb') as csvfile:
csv_writer = csv.writer(csvfile)
csv_writer.writerows(clean_rows)
</code></pre>
<p>When I run it on same script it's not working but run separately will. </p>
<p>What am I doing wrong? </p>
| -1 | 2016-10-05T11:21:44Z | 39,872,819 | <p>according to your initial description of the problem this could be one solution, although it can surely be optimized</p>
<pre><code>excluded = ['your excluded list here']
deleted_rows = 0
with open(file) as read:
with open(file2) as write:
w = csv.writer(write)
r = csv.reader(read)
for row in r:
if row not in excluded:
w.writerow(row)
else:
deleted_rows += 1
</code></pre>
| 0 | 2016-10-05T11:31:32Z | [
"python",
"csv"
]
|
How to set text into a DOM element | 39,872,860 | <p>I'm trying to set text into a DOM element. I create the element.</p>
<pre><code>svg_doc = minidom.parse('PATH_TO_SVG_FILE.svg')
category = svg_doc.createElement('category')
</code></pre>
<p>Then I try to set the <code>nodeValue</code>:</p>
<pre><code>category.nodeValue = 'Design'
</code></pre>
<p>But I get:</p>
<pre><code><category/>
</code></pre>
<p>instead of:</p>
<pre><code><category>Design<category/>
</code></pre>
<p>How to get the desired result with minidom?</p>
| 0 | 2016-10-05T11:33:47Z | 39,875,869 | <p>I think this should work:</p>
<pre><code>category.createTextNode('Design')
</code></pre>
<p>See: <a href="https://docs.python.org/2/library/xml.dom.minidom.html" rel="nofollow">https://docs.python.org/2/library/xml.dom.minidom.html</a></p>
| 1 | 2016-10-05T13:51:51Z | [
"python",
"xml",
"dom",
"svg",
"minidom"
]
|
Pass command line arguments to nose via "python setup.py test" | 39,872,880 | <h1>Package Settings</h1>
<p>I have built a Python package which uses <a href="http://nose.readthedocs.io/en/latest/" rel="nofollow">nose</a> for testing. Therefore, <a class='doc-link' href="http://stackoverflow.com/documentation/python/1381/creating-python-packages#t=201610051128088238533"><code>setup.py</code></a> contains:</p>
<pre><code>..
test_suite='nose.collector',
tests_require=['nose'],
..
</code></pre>
<p>And <code>python setup.py test</code> works as expected:</p>
<pre><code>running test
...
----------------------------------------------------------------------
Ran 3 tests in 0.065s
OK
</code></pre>
<h1>Running with XUnit output</h1>
<p>Since I'm using Jenkins CI, I would like to output the nose results to JUnit XML format:</p>
<pre><code>nosetests <package-name> --with-xunit --verbose
</code></pre>
<p>However, <code>python setup.py test</code> is far more elegant, and it installs the test requirements without having to build a virtual environment.</p>
<p><strong>Is there a way to pass the <code>--with-xunit</code> (or any other parameter) to nose, when calling nose via <code>python setup.py test</code>?</strong></p>
| 0 | 2016-10-05T11:34:51Z | 39,874,096 | <p>Nose provides its own setuptools command (<code>nosetests</code>) which accepts command line arguments:</p>
<pre><code>python setup.py nosetests --with-xunit
</code></pre>
<p>More information can be found here:
<a href="http://nose.readthedocs.io/en/latest/setuptools_integration.html" rel="nofollow">http://nose.readthedocs.io/en/latest/setuptools_integration.html</a></p>
| 1 | 2016-10-05T12:33:53Z | [
"python",
"command-line-arguments",
"nose",
"setup.py"
]
|
How to install GLPK on Alpine Linux? | 39,872,907 | <p>The installation of <code>swiglpk</code> package on Alpine Linux fails with the following trace:</p>
<pre><code>Collecting swiglpk>=1.2.14; extra == "all" (from cameo[all]==0.6.3->-r requirements.txt (line 1))
Downloading swiglpk-1.2.14.tar.gz
Complete output from command python setup.py egg_info:
which: no glpsol in (/usr/local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin)
Trying to determine glpk.h location
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/tmp/pip-build-_g57y7ed/swiglpk/setup.py", line 45, in <module>
copy_glpk_header()
File "/tmp/pip-build-_g57y7ed/swiglpk/setup.py", line 28, in copy_glpk_header
glpsol_path = os.path.dirname(subprocess.check_output(['which', 'glpsol']))
File "/usr/local/lib/python3.5/subprocess.py", line 626, in check_output
**kwargs).stdout
File "/usr/local/lib/python3.5/subprocess.py", line 708, in run
output=stdout, stderr=stderr)
subprocess.CalledProcessError: Command '['which', 'glpsol']' returned non-zero exit status 1
</code></pre>
<p>So <code>glpsol</code> is not found in the path.</p>
<p>How can <code>glpk</code>/<code>glpsol</code> be installed on Alpine Linux, if possible?</p>
| 0 | 2016-10-05T11:35:43Z | 39,892,738 | <p>Cause there is no <code>glpk</code> package for Alpine yet, it can be installed from source</p>
<pre><code>wget ftp://ftp.gnu.org/gnu/glpk/glpk-4.55.tar.gz
tar -xzvf glpk-4.55.tar.gz
cd glpk-4.55
./configure
make install
</code></pre>
<p>To make sure it worked, run <code>which glpsol</code></p>
| 0 | 2016-10-06T09:47:45Z | [
"python",
"linux",
"installation",
"glpk",
"alpine"
]
|
Efficient way for calculating selected differences in array | 39,872,981 | <p>I have two arrays as an output from a simulation script where one contains IDs and one times, i.e. something like:</p>
<pre><code>ids = np.array([2, 0, 1, 0, 1, 1, 2])
times = np.array([.1, .3, .3, .5, .6, 1.2, 1.3])
</code></pre>
<p>These arrays are always of the same size. Now I need to calculate the differences of <code>times</code>, but only for those times with the same <code>ids</code>. Of course, I can simply loop over the different <code>ids</code> an do</p>
<pre><code>for id in np.unique(ids):
diffs = np.diff(times[ids==id])
print diffs
# do stuff with diffs
</code></pre>
<p>However, this is quite inefficient and the two arrays can be very large. Does anyone have a good idea on how to do that more efficiently?</p>
| 3 | 2016-10-05T11:39:48Z | 39,873,410 | <p>You can use <code>array.argsort()</code> and ignore the values corresponding to change in ids:</p>
<pre><code>>>> id_ind = ids.argsort(kind='mergesort')
>>> times_diffs = np.diff(times[id_ind])
array([ 0.2, -0.2, 0.3, 0.6, -1.1, 1.2])
</code></pre>
<p>To see which values you need to discard, you could use a Counter to count the number of times per id (<code>from collections import Counter</code>)</p>
<p>or just sort ids, and see where its diff is nonzero: these are the indices where id change, and where you time diffs are irrelevant:</p>
<pre><code>times_diffs[np.diff(ids[id_ind]) == 0] # ids[id_ind] being the sorted indices sequence
</code></pre>
<p>and finally you can split this array with np.split and np.where:</p>
<pre><code>np.split(times_diffs, np.where(np.diff(ids[id_ind]) != 0)[0])
</code></pre>
<p>As you mentionned in your comment, <code>argsort()</code> default algorithm (quicksort) might not preserve order between equals times, so the <code>argsort(kind='mergesort')</code> option must be used.</p>
| 3 | 2016-10-05T12:01:54Z | [
"python",
"arrays",
"numpy"
]
|
Efficient way for calculating selected differences in array | 39,872,981 | <p>I have two arrays as an output from a simulation script where one contains IDs and one times, i.e. something like:</p>
<pre><code>ids = np.array([2, 0, 1, 0, 1, 1, 2])
times = np.array([.1, .3, .3, .5, .6, 1.2, 1.3])
</code></pre>
<p>These arrays are always of the same size. Now I need to calculate the differences of <code>times</code>, but only for those times with the same <code>ids</code>. Of course, I can simply loop over the different <code>ids</code> an do</p>
<pre><code>for id in np.unique(ids):
diffs = np.diff(times[ids==id])
print diffs
# do stuff with diffs
</code></pre>
<p>However, this is quite inefficient and the two arrays can be very large. Does anyone have a good idea on how to do that more efficiently?</p>
| 3 | 2016-10-05T11:39:48Z | 39,873,434 | <p>Say you <code>np.argsort</code> by <code>ids</code>:</p>
<pre><code>inds = np.argsort(ids, kind='mergesort')
>>> array([1, 3, 2, 4, 5, 0, 6])
</code></pre>
<p>Now sort <code>times</code> by this, <code>np.diff</code>, and prepend a <code>nan</code>:</p>
<pre><code>diffs = np.concatenate(([np.nan], np.diff(times[inds])))
>>> diffs
array([ nan, 0.2, -0.2, 0.3, 0.6, -1.1, 1.2])
</code></pre>
<p>These differences are correct except for the boundaries. Let's calculate those</p>
<pre><code>boundaries = np.concatenate(([False], ids[inds][1: ] == ids[inds][: -1]))
>>> boundaries
array([False, True, False, True, True, False, True], dtype=bool)
</code></pre>
<p>Now we can just do</p>
<pre><code>diffs[~boundaries] = np.nan
</code></pre>
<hr>
<p>Let's see what we got:</p>
<pre><code>>>> ids[inds]
array([0, 0, 1, 1, 1, 2, 2])
>>> times[inds]
array([ 0.3, 0.5, 0.3, 0.6, 1.2, 0.1, 1.3])
>>> diffs
array([ nan, 0.2, nan, 0.3, 0.6, nan, 1.2])
</code></pre>
| 2 | 2016-10-05T12:02:58Z | [
"python",
"arrays",
"numpy"
]
|
Efficient way for calculating selected differences in array | 39,872,981 | <p>I have two arrays as an output from a simulation script where one contains IDs and one times, i.e. something like:</p>
<pre><code>ids = np.array([2, 0, 1, 0, 1, 1, 2])
times = np.array([.1, .3, .3, .5, .6, 1.2, 1.3])
</code></pre>
<p>These arrays are always of the same size. Now I need to calculate the differences of <code>times</code>, but only for those times with the same <code>ids</code>. Of course, I can simply loop over the different <code>ids</code> an do</p>
<pre><code>for id in np.unique(ids):
diffs = np.diff(times[ids==id])
print diffs
# do stuff with diffs
</code></pre>
<p>However, this is quite inefficient and the two arrays can be very large. Does anyone have a good idea on how to do that more efficiently?</p>
| 3 | 2016-10-05T11:39:48Z | 39,874,178 | <p>I'm adding another answer, since, even though these things are possible in <code>numpy</code>, I think that the higher-level <a href="http://pandas.pydata.org/" rel="nofollow"><code>pandas</code></a> is much more natural for them.</p>
<p>In <code>pandas</code>, you could do this in one step, after creating a DataFrame:</p>
<pre><code>df = pd.DataFrame({'ids': ids, 'times': times})
df['diffs'] = df.groupby(df.ids).transform(pd.Series.diff)
</code></pre>
<p>This gives: </p>
<pre><code>>>> df
ids times diffs
0 2 0.1 NaN
1 0 0.3 NaN
2 1 0.3 NaN
3 0 0.5 0.2
4 1 0.6 0.3
5 1 1.2 0.6
6 2 1.3 1.2
</code></pre>
| 0 | 2016-10-05T12:37:11Z | [
"python",
"arrays",
"numpy"
]
|
Efficient way for calculating selected differences in array | 39,872,981 | <p>I have two arrays as an output from a simulation script where one contains IDs and one times, i.e. something like:</p>
<pre><code>ids = np.array([2, 0, 1, 0, 1, 1, 2])
times = np.array([.1, .3, .3, .5, .6, 1.2, 1.3])
</code></pre>
<p>These arrays are always of the same size. Now I need to calculate the differences of <code>times</code>, but only for those times with the same <code>ids</code>. Of course, I can simply loop over the different <code>ids</code> an do</p>
<pre><code>for id in np.unique(ids):
diffs = np.diff(times[ids==id])
print diffs
# do stuff with diffs
</code></pre>
<p>However, this is quite inefficient and the two arrays can be very large. Does anyone have a good idea on how to do that more efficiently?</p>
| 3 | 2016-10-05T11:39:48Z | 39,874,828 | <p>The <a href="https://github.com/EelcoHoogendoorn/Numpy_arraysetops_EP" rel="nofollow">numpy_indexed</a> package (disclaimer: I am its author) contains efficient and flexible functionality for these kind of grouping operations:</p>
<pre><code>import numpy_indexed as npi
unique_ids, diffed_time_groups = npi.group_by(keys=ids, values=times, reduction=np.diff)
</code></pre>
<p>Unlike pandas, it does not require a specialized datastructure just to perform this kind of rather elementary operation.</p>
| 1 | 2016-10-05T13:06:53Z | [
"python",
"arrays",
"numpy"
]
|
Offer user the option to re-run code | 39,873,002 | <pre><code>print ("Welcome to my Area Calculator")
i=raw_input("Please enter the shape whose Area you want to calculate(square/rectangle/right angled triangle/rhombus/parallelogram): ")
my_list=["square","rectangle","triangle","right angled triangle","rhombus","parallelogram"]
if i in my_list:
if i=="square":
s=float(input("What is the side of the square: "))
print "Area of the square is : ", s**2
elif i=="rectangle":
l=float(input("What is the length of the rectangle: "))
b=float(input("What is the breadth of the rectangle: "))
print "Area of the rectangle is : ", l*b
elif i=="right angled triangle":
base1=float(input("What is the base of the triangle: "))
height1=float(input("What is the height of the triangle: "))
print "Area of the triangle is : ", 0.5*base1*height1
elif i=="rhombus":
d1=float(input("What is the length of the 1st diagnol of the rhombus: "))
d2=float(input("What is the length of the 2nd diagnol of the rhombus: "))
print "Area of the rhombus is : ", 0.5*d1*d2
elif i=="parallelogram":
base=float(input("What is the length of 1 side of the parallelogram: "))
height=float(input("What is the length of the other side: "))
print "Area of the parallelogram is : ", height*base
print "Thank you so much for using my area calculator"
</code></pre>
| -6 | 2016-10-05T11:40:24Z | 39,873,070 | <p>Ask for the user if he wants to continue, put it in a boolean variable, put all your code in a while loop with this boolean as a condition<br>
Don't forget to init this boolean to true</p>
| 0 | 2016-10-05T11:43:49Z | [
"python"
]
|
Offer user the option to re-run code | 39,873,002 | <pre><code>print ("Welcome to my Area Calculator")
i=raw_input("Please enter the shape whose Area you want to calculate(square/rectangle/right angled triangle/rhombus/parallelogram): ")
my_list=["square","rectangle","triangle","right angled triangle","rhombus","parallelogram"]
if i in my_list:
if i=="square":
s=float(input("What is the side of the square: "))
print "Area of the square is : ", s**2
elif i=="rectangle":
l=float(input("What is the length of the rectangle: "))
b=float(input("What is the breadth of the rectangle: "))
print "Area of the rectangle is : ", l*b
elif i=="right angled triangle":
base1=float(input("What is the base of the triangle: "))
height1=float(input("What is the height of the triangle: "))
print "Area of the triangle is : ", 0.5*base1*height1
elif i=="rhombus":
d1=float(input("What is the length of the 1st diagnol of the rhombus: "))
d2=float(input("What is the length of the 2nd diagnol of the rhombus: "))
print "Area of the rhombus is : ", 0.5*d1*d2
elif i=="parallelogram":
base=float(input("What is the length of 1 side of the parallelogram: "))
height=float(input("What is the length of the other side: "))
print "Area of the parallelogram is : ", height*base
print "Thank you so much for using my area calculator"
</code></pre>
| -6 | 2016-10-05T11:40:24Z | 39,873,085 | <p>Make your entire program became a function, then execute it inside while loop.</p>
<pre><code>while(option != 'yes'):
Program()
userInput()
</code></pre>
| 2 | 2016-10-05T11:44:32Z | [
"python"
]
|
SQL error 1054, "Unknown column 'xxxxx' in 'field list'" in Python with placeholders | 39,873,064 | <p>I am new to mySQL with Python and I am getting the common 1054 error when I try to execute a pre-prepared SQL INSERT statement with Python friendly placeholders ('%s')</p>
<p>I understand the normal solution is to add quotes in place of back-ticks, or add them if they're missing for the inserted values, however I have run a check on the cols and vals tuples and I can see they're contained within single quotes, so I am a bit puzzled why this error occurs. </p>
<p>Below is a snippet of my code: (BTW 'cols' and 'vals' are tuples of strings (with emphasis on strings :) )</p>
<p>first I add the column names:</p>
<pre><code>for item in cols:
try:
# First add columns if not already present
query = "ALTER TABLE Parameters ADD COLUMN %s VARCHAR(200)" % (str(item))
cursor.execute(query)
connection.commit()
except:
pass
</code></pre>
<p>Then I try adding the values:</p>
<pre><code>sql = "INSERT INTO Parameters ({0}) VALUES ({1})".format(', '.join(cols), ', '.join(['%s'] * len(cols)));
try:
cursor.execute(sql, vals)
except Exception as e:
print(e)
connection.close()
</code></pre>
<p>Sometimes there is no problem, but otherwise I get this error:</p>
<pre><code>(1054, "Unknown column 'ColumnName' in 'field list'")
</code></pre>
<p>Is my Python statement completely incorrect, and are placeholders not best practice? I use placeholders as my lists are very large.</p>
<p>Here's a dumbed down version of the SQL statement print.</p>
<pre><code> INSERT INTO Parameters (TestID, Dev_Type, Version, MAC, XXXX, XXXX, XXXX, XXXX, XXXX, XXXX, XXXX, XXXX, XXXX, XXXX, XXXX, XXXX, XXXX, XXXX, XXXX, XXXX, XXXX, XXXX, XXXX, XXXX, XXXX, XXXX, XXXX, XXXX, XXXX, DayActNxtDateTime, XXXX) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
</code></pre>
<p>And error:</p>
<pre><code>(1054, "Unknown column 'DayActNxtDateTime' in 'field list'")
</code></pre>
| 0 | 2016-10-05T11:43:40Z | 39,873,521 | <p>Seems you are asking how to trouble shoot the issue?</p>
<pre><code>INSERT INTO Parameters ({0}) VALUES ({1})
</code></pre>
<p>The error reporting that in your ({0}), you has one field called "ColumnName", but it is not defined in your table Parameters.</p>
<p>Try:</p>
<pre><code>SHOW CREATE TABLE parameters;
</code></pre>
<p>And make sure your table contains the field.</p>
<p>If still has problems, then print out all the sql in your exception handler:</p>
<pre><code>print(e)
print(sql)
</code></pre>
<p>Then I'll run tcpdump to make sure the sql string is not mangled wrongly by any library</p>
<pre><code>sudo tcpdump -A -i lo0 dst port 3306
</code></pre>
<p>And then run your script.</p>
| 0 | 2016-10-05T12:06:38Z | [
"python",
"mysql",
"sql",
"mariadb",
"pymysql"
]
|
SQL error 1054, "Unknown column 'xxxxx' in 'field list'" in Python with placeholders | 39,873,064 | <p>I am new to mySQL with Python and I am getting the common 1054 error when I try to execute a pre-prepared SQL INSERT statement with Python friendly placeholders ('%s')</p>
<p>I understand the normal solution is to add quotes in place of back-ticks, or add them if they're missing for the inserted values, however I have run a check on the cols and vals tuples and I can see they're contained within single quotes, so I am a bit puzzled why this error occurs. </p>
<p>Below is a snippet of my code: (BTW 'cols' and 'vals' are tuples of strings (with emphasis on strings :) )</p>
<p>first I add the column names:</p>
<pre><code>for item in cols:
try:
# First add columns if not already present
query = "ALTER TABLE Parameters ADD COLUMN %s VARCHAR(200)" % (str(item))
cursor.execute(query)
connection.commit()
except:
pass
</code></pre>
<p>Then I try adding the values:</p>
<pre><code>sql = "INSERT INTO Parameters ({0}) VALUES ({1})".format(', '.join(cols), ', '.join(['%s'] * len(cols)));
try:
cursor.execute(sql, vals)
except Exception as e:
print(e)
connection.close()
</code></pre>
<p>Sometimes there is no problem, but otherwise I get this error:</p>
<pre><code>(1054, "Unknown column 'ColumnName' in 'field list'")
</code></pre>
<p>Is my Python statement completely incorrect, and are placeholders not best practice? I use placeholders as my lists are very large.</p>
<p>Here's a dumbed down version of the SQL statement print.</p>
<pre><code> INSERT INTO Parameters (TestID, Dev_Type, Version, MAC, XXXX, XXXX, XXXX, XXXX, XXXX, XXXX, XXXX, XXXX, XXXX, XXXX, XXXX, XXXX, XXXX, XXXX, XXXX, XXXX, XXXX, XXXX, XXXX, XXXX, XXXX, XXXX, XXXX, XXXX, XXXX, DayActNxtDateTime, XXXX) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
</code></pre>
<p>And error:</p>
<pre><code>(1054, "Unknown column 'DayActNxtDateTime' in 'field list'")
</code></pre>
| 0 | 2016-10-05T11:43:40Z | 39,891,520 | <p>Thanks @Gordon Linoff and @Shuo for all your help. It turned out my dumbed down version of the SQL statement was misleading. I played around with manually adding columns directly using SQL command line to find the answer. </p>
<p>It turned out some of my column names exceeded the 64 character limit imposed by SQL (these column names are generated programmatically), hence why the loop sometimes worked and other times it didn't. Not sure if there's a way in SQL to shorten the column title, I saw something about a COMPRESS method after a quick glance? </p>
<p>In the mean time I created a Python dictionary to capture these extra long column names on creation and mapped them to a manually created alternative value, it'll do for now I guess. Thanks again for giving me direction.</p>
| 0 | 2016-10-06T08:46:10Z | [
"python",
"mysql",
"sql",
"mariadb",
"pymysql"
]
|
max() of big nested lists | 39,873,114 | <p>I encountered a quite odd problem while dealing with the max of a long list of lists of of pairs, such as</p>
<pre><code>[
[(0, 1), (1, 1), (2, 1), (3, 4), (4, 1), (5, 1), (6, 1),...,(141,3)],
...,
[(12, 1), (36, 1), (91, 1), (92, 1), (110, 1),..., (180, 1)]
]
</code></pre>
<p>I am trying to get the maximum of the first element of all the pairs.
Pythonically, I was doing:</p>
<pre><code>max([max(x) for x in list])[0]
</code></pre>
<p>which actually returns the correct number, IF the list is shorter than 281 lists.
In fact, as soon as the list is longer than 280, I get this message</p>
<pre><code>ValueError: max() arg is an empty sequence
</code></pre>
<p>So, for a long list</p>
<pre><code>max([max(x) for x in list[0:280]])[0]
</code></pre>
<p>it's fine, while</p>
<pre><code>max([max(x) for x in list[0:281]])[0]
</code></pre>
<p>breaks.</p>
<p>Am I doing something wrong here?</p>
| -1 | 2016-10-05T11:46:07Z | 39,873,205 | <p>You have an empty list among your list of lists, at index 280. Slicing up to <code>[:280]</code> excludes it, and it is included with <code>[:281]</code>.</p>
<p>This is easily reproduced with a shorter sample:</p>
<pre><code>>>> lsts = [
... [(0, 1), (1, 1)],
... [(2, 1), (3, 4)],
... [(4, 1), (5, 1)],
... [], # empty at index 3
... ]
>>> max(max(x) for x in lsts)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in <genexpr>
ValueError: max() arg is an empty sequence
>>> max(max(x) for x in lsts[:3]) # include everything before index 3
(5, 1)
</code></pre>
<p>You can avoid the issue altogether by chaining your lists together, here using <a href="https://docs.python.org/3/library/itertools.html#itertools.chain.from_iterable" rel="nofollow"><code>chain.from_iterable()</code></a>:</p>
<pre><code>from itertools import chain
max(chain.from_iterable(list_of_lists))[0]
</code></pre>
<p>This treats all nested lists as one long list, an empty list somewhere in between simply doesn't contribute to that new sequence.</p>
| 5 | 2016-10-05T11:51:22Z | [
"python",
"list",
"max",
"nested-lists"
]
|
max() of big nested lists | 39,873,114 | <p>I encountered a quite odd problem while dealing with the max of a long list of lists of of pairs, such as</p>
<pre><code>[
[(0, 1), (1, 1), (2, 1), (3, 4), (4, 1), (5, 1), (6, 1),...,(141,3)],
...,
[(12, 1), (36, 1), (91, 1), (92, 1), (110, 1),..., (180, 1)]
]
</code></pre>
<p>I am trying to get the maximum of the first element of all the pairs.
Pythonically, I was doing:</p>
<pre><code>max([max(x) for x in list])[0]
</code></pre>
<p>which actually returns the correct number, IF the list is shorter than 281 lists.
In fact, as soon as the list is longer than 280, I get this message</p>
<pre><code>ValueError: max() arg is an empty sequence
</code></pre>
<p>So, for a long list</p>
<pre><code>max([max(x) for x in list[0:280]])[0]
</code></pre>
<p>it's fine, while</p>
<pre><code>max([max(x) for x in list[0:281]])[0]
</code></pre>
<p>breaks.</p>
<p>Am I doing something wrong here?</p>
| -1 | 2016-10-05T11:46:07Z | 39,873,318 | <p>Why not just this?</p>
<pre><code>max([max([t[0] for t in sl if t]) for sl in l if sl])
</code></pre>
<p>You can extract the first item from the beginning. Empty lists and tuples are ignored.</p>
<p>EDIT</p>
<pre><code>max([max([t for t in sl if t]) for sl in l if sl])[0]
</code></pre>
<p>is more efficient.</p>
| 0 | 2016-10-05T11:57:24Z | [
"python",
"list",
"max",
"nested-lists"
]
|
How to calculate SHA from a string with the Github api in python? | 39,873,507 | <p>I want to update a file with the Github API and commit it into a branch. I have troubles creating the commit. The SHA does not match the expected one.</p>
<pre><code>{
'documentation_url': 'https://developer.github.com/enterprise/2.7/v3/repos/contents/',
'message': 'pom.xml does not match de42fdd980f9b8067a2af982de46b8d5547e4597'
}
</code></pre>
<p>I do the following:</p>
<pre><code>import hashlib
myfile = "new content of my README"
resulting_file = base64.b64encode(bytes(myfile, "utf-8"))
file_as_str = str(resulting_file.decode('utf-8'))
sha = hashlib.sha1(file_as_str.encode('utf-8')).hexdigest()
url = 'https://someurl.com/someproject/contents/README.md?access_token=' + access_token
data = '{"message": "bla bla", "content": "'+file_as_str+'", "sha": "'+sha+'", "branch": "'+branch+'"}'
response = requests.put(url, data=data)
</code></pre>
<p>I would not like to use a lib to do this to better understand what is happening. probably the SHA is not generated properly, but I cannot identify why. Could someone help?</p>
| 0 | 2016-10-05T12:06:08Z | 39,874,235 | <p>GitHub calculates hashes as followes:</p>
<pre><code>sha1("blob " + filesize + "\0" + data)
</code></pre>
<p>so use this code:</p>
<pre><code>with open(filepath, 'rb') as file_for_hash:
data = file_for_hash.read()
filesize = len(data)
sha = hashlib.sha1("blob " + filesize + "\0" + data).hexdigest()
</code></pre>
| 0 | 2016-10-05T12:40:05Z | [
"python",
"git",
"github-api"
]
|
How to calculate SHA from a string with the Github api in python? | 39,873,507 | <p>I want to update a file with the Github API and commit it into a branch. I have troubles creating the commit. The SHA does not match the expected one.</p>
<pre><code>{
'documentation_url': 'https://developer.github.com/enterprise/2.7/v3/repos/contents/',
'message': 'pom.xml does not match de42fdd980f9b8067a2af982de46b8d5547e4597'
}
</code></pre>
<p>I do the following:</p>
<pre><code>import hashlib
myfile = "new content of my README"
resulting_file = base64.b64encode(bytes(myfile, "utf-8"))
file_as_str = str(resulting_file.decode('utf-8'))
sha = hashlib.sha1(file_as_str.encode('utf-8')).hexdigest()
url = 'https://someurl.com/someproject/contents/README.md?access_token=' + access_token
data = '{"message": "bla bla", "content": "'+file_as_str+'", "sha": "'+sha+'", "branch": "'+branch+'"}'
response = requests.put(url, data=data)
</code></pre>
<p>I would not like to use a lib to do this to better understand what is happening. probably the SHA is not generated properly, but I cannot identify why. Could someone help?</p>
| 0 | 2016-10-05T12:06:08Z | 39,874,911 | <p>You don't need to calculate the SHA for the new file. Instead you must supply the SHA of the file that is being <em>replaced</em>. You can obtain that by performing a <a href="https://developer.github.com/enterprise/2.7/v3/repos/contents/#get-contents" rel="nofollow">get contents</a> on the file using <code>requests.get()</code>:</p>
<pre><code>url = 'https://api.github.com/repos/someowner/someproject/contents/pom.xml'
r = requests.get(url)
sha = r.json()['sha']
</code></pre>
<p>Then use the value of <code>sha</code> in the <code>PUT</code> request to update the file:</p>
<pre><code>with open('myfile', 'rb') as f:
content = str(base64.b64encode(f.read()), encoding='utf8')
data = {'message': 'bla bla', 'content': content, 'sha': sha, 'branch': branch}
r = requests.put(url, json=data)
</code></pre>
| 2 | 2016-10-05T13:10:35Z | [
"python",
"git",
"github-api"
]
|
OOP: best way to code relations between objects of different classes | 39,873,713 | <p>Let's say we have two classes <code>Basket</code> and <code>Item</code>. Each basket contains a list of items. I can store in the basket the <code>id</code>s of the items, or directly the items objects. Which is the best solution, and why (in terms of memory usage, covenience, etc...)?</p>
<p><strong>CASE A</strong></p>
<pre><code>class Basket(object):
def __init__(self, basket_name):
self._name = basket_name
self._items = []
def add_item(self, item_id)
self._items.append(item_id)
class Item(object):
def __init__(self, item_id):
self._id= item_id
>>> b = Basket('My_Basket')
>>> i1 = Item(1)
>>> i2 = Item(2)
>>> b.add_item(1)
>>> b.add_item(2)
</code></pre>
<p><strong>CASE B</strong></p>
<pre><code>class Basket(object):
def __init__(self, basket_name):
self._name = basket_name
self._items = []
def add_item(self, item)
self._items.append(item)
class Item(object):
def __init__(self, item_id):
self._id= item_id
>>> b = Basket('My_Basket')
>>> i1 = Item(1)
>>> i2 = Item(2)
>>> b.add_item(i1)
>>> b.add_item(i2)
</code></pre>
| 0 | 2016-10-05T12:16:19Z | 39,873,813 | <p>You should store the items directly. As previously mentioned there is no resource issue with doing it and then it provides the basket with direct access to the items. Say you wanted to know how much the basket weighs? well if you add a .weight method to your items class then you can have your basket iterate through all of the items it contains and return the weight of them. </p>
| 3 | 2016-10-05T12:21:19Z | [
"python",
"oop"
]
|
OOP: best way to code relations between objects of different classes | 39,873,713 | <p>Let's say we have two classes <code>Basket</code> and <code>Item</code>. Each basket contains a list of items. I can store in the basket the <code>id</code>s of the items, or directly the items objects. Which is the best solution, and why (in terms of memory usage, covenience, etc...)?</p>
<p><strong>CASE A</strong></p>
<pre><code>class Basket(object):
def __init__(self, basket_name):
self._name = basket_name
self._items = []
def add_item(self, item_id)
self._items.append(item_id)
class Item(object):
def __init__(self, item_id):
self._id= item_id
>>> b = Basket('My_Basket')
>>> i1 = Item(1)
>>> i2 = Item(2)
>>> b.add_item(1)
>>> b.add_item(2)
</code></pre>
<p><strong>CASE B</strong></p>
<pre><code>class Basket(object):
def __init__(self, basket_name):
self._name = basket_name
self._items = []
def add_item(self, item)
self._items.append(item)
class Item(object):
def __init__(self, item_id):
self._id= item_id
>>> b = Basket('My_Basket')
>>> i1 = Item(1)
>>> i2 = Item(2)
>>> b.add_item(i1)
>>> b.add_item(i2)
</code></pre>
| 0 | 2016-10-05T12:16:19Z | 39,873,929 | <p>I would prefer storing objects, not IDs. Because each time you would have to do something with your Items you would have to first somehow get/load this object by ID. But this is a general case.</p>
<p>In case of you will have tons of Items and no operations with full list (e.g. basket will only perform actions on a single object, not on full collection) you might want to store only IDs.</p>
| 1 | 2016-10-05T12:26:09Z | [
"python",
"oop"
]
|
OOP: best way to code relations between objects of different classes | 39,873,713 | <p>Let's say we have two classes <code>Basket</code> and <code>Item</code>. Each basket contains a list of items. I can store in the basket the <code>id</code>s of the items, or directly the items objects. Which is the best solution, and why (in terms of memory usage, covenience, etc...)?</p>
<p><strong>CASE A</strong></p>
<pre><code>class Basket(object):
def __init__(self, basket_name):
self._name = basket_name
self._items = []
def add_item(self, item_id)
self._items.append(item_id)
class Item(object):
def __init__(self, item_id):
self._id= item_id
>>> b = Basket('My_Basket')
>>> i1 = Item(1)
>>> i2 = Item(2)
>>> b.add_item(1)
>>> b.add_item(2)
</code></pre>
<p><strong>CASE B</strong></p>
<pre><code>class Basket(object):
def __init__(self, basket_name):
self._name = basket_name
self._items = []
def add_item(self, item)
self._items.append(item)
class Item(object):
def __init__(self, item_id):
self._id= item_id
>>> b = Basket('My_Basket')
>>> i1 = Item(1)
>>> i2 = Item(2)
>>> b.add_item(i1)
>>> b.add_item(i2)
</code></pre>
| 0 | 2016-10-05T12:16:19Z | 39,873,988 | <p>Option B is usually the best option because this is how <strong>Object Oriented Programming</strong> works. Because you are using the objects directly you can also access them directly in you code. If you use the link option then in order to access a given <code>Item</code> later you would have to do some sort of query to find that object. When you use the object directly what python essentially does is creates that link for you. The object is not copied twice but instead it is referenced in the <code>_items</code> list inside your <code>Basket</code> object.</p>
<p>Also, the <code>self._id= item_id</code> in</p>
<pre><code>def __init__(self, item_id):
self._id= item_id
</code></pre>
<p>would not be required because you would have no need to find that id, and hence:</p>
<pre><code>>>>i1 = Item(1)
>>>i2 = Item(2)
</code></pre>
<p>Would simply become:</p>
<pre><code>>>> i1 = Item()
>>> i2 = Item()
</code></pre>
| 1 | 2016-10-05T12:29:02Z | [
"python",
"oop"
]
|
OOP: best way to code relations between objects of different classes | 39,873,713 | <p>Let's say we have two classes <code>Basket</code> and <code>Item</code>. Each basket contains a list of items. I can store in the basket the <code>id</code>s of the items, or directly the items objects. Which is the best solution, and why (in terms of memory usage, covenience, etc...)?</p>
<p><strong>CASE A</strong></p>
<pre><code>class Basket(object):
def __init__(self, basket_name):
self._name = basket_name
self._items = []
def add_item(self, item_id)
self._items.append(item_id)
class Item(object):
def __init__(self, item_id):
self._id= item_id
>>> b = Basket('My_Basket')
>>> i1 = Item(1)
>>> i2 = Item(2)
>>> b.add_item(1)
>>> b.add_item(2)
</code></pre>
<p><strong>CASE B</strong></p>
<pre><code>class Basket(object):
def __init__(self, basket_name):
self._name = basket_name
self._items = []
def add_item(self, item)
self._items.append(item)
class Item(object):
def __init__(self, item_id):
self._id= item_id
>>> b = Basket('My_Basket')
>>> i1 = Item(1)
>>> i2 = Item(2)
>>> b.add_item(i1)
>>> b.add_item(i2)
</code></pre>
| 0 | 2016-10-05T12:16:19Z | 39,874,782 | <p><strong>everything</strong> in python is an object, including integers used as IDs for other objects. So in both Case A and Case B you are appending references to objects to the <code>Basket._items</code> list.</p>
<p>So what is the difference between A and B? If you only store the IDs then how will you reference the original objects? It is harder to guarantee that they will exist in the namespace. Any code that looks up properties from <code>item</code> instances may fall into that trap.</p>
| 1 | 2016-10-05T13:04:56Z | [
"python",
"oop"
]
|
I want to appoint array in insert sentence | 39,873,794 | <p>I use pyorient.
The following things want to make it, but can register nothing.</p>
<pre><code>lst = ['10', '20', '30']
var = 2016
client.command("insert into class1 (datet, price) values(var, lst[0])")
</code></pre>
| -2 | 2016-10-05T12:20:26Z | 39,874,656 | <p>You could use</p>
<pre><code>lst = ['10', '20', '30']
var = 2016
client.command("insert into class1 set datet='%d', price='%s'" % (var,lst[0]));
</code></pre>
<p>or</p>
<pre><code>client.command("insert into class1 (datet,price) values ('%d','%s')" % (var,lst[0]))
</code></pre>
<p>Hope it helps.</p>
| 0 | 2016-10-05T12:59:22Z | [
"python",
"orientdb"
]
|
How to prevent a particular string from being printed in find_all()? | 39,873,820 | <p>How to exclude a substring from being printed in object <code>obj</code></p>
<pre><code>obj = soup.find_all('tag')
if "string" not in obj.text:
print obj.text
</code></pre>
<p>But due to the use of find_all() method for object obj nothing is being printed.
What should be done so that we print only the wanted string in obj.</p>
| -1 | 2016-10-05T12:21:35Z | 39,873,971 | <p>You need to loop through the list returned by <code>find_all()</code>:</p>
<pre><code>for i in soup.find_all('tag'):
txt = i.text
if 'string' not in txt:
print txt
</code></pre>
<p>Alternatively, you could create another list where the unwanted tags are filtered out:</p>
<pre><code>filtered_lst = [i for i in soup.find_all('tag') if 'string' not in i.text]
</code></pre>
<p>This will give you a list of <code>Tag</code> objects similar to that returned by <code>find_all()</code>, but with only the tags that do not include <code>'string'</code> in their <code>.text</code>. After that you can do what you want it it:</p>
<pre><code>for tag in filtered_lst:
print tag.text
</code></pre>
<h1>Update:</h1>
<p>On the other hand, if your goal is to simply filter <code>'string'</code> from the text of the tag, you can use the <code>replace()</code> method of strings:</p>
<pre><code>for tag in soup.find_all('tag'):
print tag.text.replace('string', '')
</code></pre>
<p>However, keep in mind that this will remove <code>'string'</code> wherever it is in the text, and may leave unwanted whitespace to be removed later. For example:</p>
<pre><code>>>> 'hellostring string'.replace('string', '')
'hello '
</code></pre>
| 0 | 2016-10-05T12:27:59Z | [
"python",
"web-scraping"
]
|
heroku: no default language could be detected for this app | 39,873,920 | <p>First time using Heroku. Trying to push. I have run the command:</p>
<p><code>heroku create --buildpack heroku/pyhon</code> and it displayed</p>
<p><code>$ heroku create --buildpack heroku/python
Creating app... done, glacial-reef-7599
Setting buildpack to heroku/python... done
https://glacial-reef-7599.herokuapp.com/ | https://git.heroku.com/glacial-reef-7599.git</code></p>
<p>Stack trace:</p>
<pre><code>$ git push heroku master
Counting objects: 129, done.
Delta compression using up to 8 threads.
Compressing objects: 100% (124/124), done.
Writing objects: 100% (129/129), 69.06 KiB | 0 bytes/s, done.
Total 129 (delta 22), reused 0 (delta 0)
remote: Compressing source files... done.
remote: Building source:
remote:
remote: ! No default language could be detected for this app.
remote: HINT: This occurs when Heroku cannot detect the buildpack to use for this application automatically.
remote: See https://devcenter.heroku.com/articles/buildpacks
remote:
remote: ! Push failed
remote: Verifying deploy...
remote:
remote: ! Push rejected to pure-badlands-9125.
remote:
To https://git.heroku.com/pure-badlands-9125.git
! [remote rejected] master -> master (pre-receive hook declined)
error: failed to push some refs to 'https://git.heroku.com/pure-badlands-9125.git'
</code></pre>
<p>I've gotta be missing something.</p>
<p>I have added a <code>requirements.txt</code> to my root directory. It looks like this:</p>
<pre><code>.git
.idea
projectapp
projectname
rango
db.sqlite3
manage.py
populate_rango.py
requirements.txt
</code></pre>
| 0 | 2016-10-05T12:25:50Z | 39,876,229 | <p>You need to create a runtime.txt file. On the command line, in the same folder as your requirements.txt file, enter <code>echo "python-3.5.1" > runtime.txt</code>. Of course, make sure to switch the 3.5.1 with whichever version of Python you are using.</p>
| 0 | 2016-10-05T14:08:25Z | [
"python",
"heroku"
]
|
How to iterate over pandas dataframe and create new column | 39,873,995 | <p>I have a pandas dataframe that has 2 columns. I want to loop through it's rows and based on a string from column 2 I would like to add a string in a newly created 3th column. I tried:</p>
<pre><code>for i in df.index:
if df.ix[i]['Column2']==variable1:
df['Column3'] = variable2
elif df.ix[i]['Column2']==variable3:
df['Column3'] = variable4
print(df)
</code></pre>
<p>But the resulting dataframe has in column 3 only Variable2.</p>
<p>Any ideas how else I could do this?</p>
| 2 | 2016-10-05T12:29:19Z | 39,874,053 | <p>I think you can use double <a href="http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.where.html" rel="nofollow"><code>numpy.where</code></a>, what is faster as loop:</p>
<pre><code>df['Column3'] = np.where(df['Column2']==variable1, variable2,
np.where(df['Column2']==variable3, variable4))
</code></pre>
<p>And if need add variable if both conditions are <code>False</code>:</p>
<pre><code>df['Column3'] = np.where(df['Column2']==variable1, variable2,
np.where(df['Column2']==variable3, variable4, variable5))
</code></pre>
<p>Sample:</p>
<pre><code>df = pd.DataFrame({'Column2':[1,2,4,3]})
print (df)
Column2
0 1
1 2
2 4
3 3
variable1 = 1
variable2 = 2
variable3 = 3
variable4 = 4
variable5 = 5
df['Column3'] = np.where(df['Column2']==variable1, variable2,
np.where(df['Column2']==variable3, variable4, variable5))
print (df)
Column2 Column3
0 1 2
1 2 5
2 4 5
3 3 4
</code></pre>
<p>Another solution, thanks <a href="http://stackoverflow.com/questions/39873995/how-to-iterrate-over-pandas-dataframe-and-create-new-column/39874053#comment67034759_39874053"><code>Jon Clements</code></a>:</p>
<pre><code>df['Column4'] = df.Column2.map({variable1: variable2, variable3:variable4}).fillna(variable5)
print (df)
Column2 Column3 Column4
0 1 2 2.0
1 2 5 5.0
2 4 5 5.0
3 3 4 4.0
</code></pre>
| 2 | 2016-10-05T12:31:38Z | [
"python",
"loops",
"pandas",
"condition",
"multiple-columns"
]
|
How to iterate over pandas dataframe and create new column | 39,873,995 | <p>I have a pandas dataframe that has 2 columns. I want to loop through it's rows and based on a string from column 2 I would like to add a string in a newly created 3th column. I tried:</p>
<pre><code>for i in df.index:
if df.ix[i]['Column2']==variable1:
df['Column3'] = variable2
elif df.ix[i]['Column2']==variable3:
df['Column3'] = variable4
print(df)
</code></pre>
<p>But the resulting dataframe has in column 3 only Variable2.</p>
<p>Any ideas how else I could do this?</p>
| 2 | 2016-10-05T12:29:19Z | 39,874,167 | <p>You can also try this (if you want to keep the <code>for</code> loop you use) :</p>
<pre><code>new_column = []
for i in df.index:
if df.ix[i]['Column2']==variable1:
new_column.append(variable2)
elif df.ix[i]['Column2']==variable3:
new_column.append(variable4)
else : #if both conditions not verified
new_column.append(other_variable)
df['Column3'] = new_column
</code></pre>
| 0 | 2016-10-05T12:36:38Z | [
"python",
"loops",
"pandas",
"condition",
"multiple-columns"
]
|
How to iterate over pandas dataframe and create new column | 39,873,995 | <p>I have a pandas dataframe that has 2 columns. I want to loop through it's rows and based on a string from column 2 I would like to add a string in a newly created 3th column. I tried:</p>
<pre><code>for i in df.index:
if df.ix[i]['Column2']==variable1:
df['Column3'] = variable2
elif df.ix[i]['Column2']==variable3:
df['Column3'] = variable4
print(df)
</code></pre>
<p>But the resulting dataframe has in column 3 only Variable2.</p>
<p>Any ideas how else I could do this?</p>
| 2 | 2016-10-05T12:29:19Z | 39,874,196 | <p>Firstly, there is no need to loop through each and every index, just use pandas built in <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#the-where-method-and-masking" rel="nofollow">boolean indexing</a>. First line here, we gather all of the values in <code>Column2</code> that are the same as <code>variable1</code> and set the same row in <code>Column3</code> to be <code>variable2</code></p>
<pre><code>df.ix[df.Column2==variable1, 'Column3'] = variable2
df.ix[df.Column2==variable3, 'Column3'] = variable4
</code></pre>
<p>A simple example would be</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'Animal':['dog', 'fish', 'fish', 'dog']})
print(df)
Animal
0 dog
1 fish
2 fish
3 dog
df.ix[df.Animal=='dog', 'Colour'] = 'brown'
df.ix[df.Animal=='fish', 'Colour'] = 'silver'
print(df)
Animal Colour
0 dog brown
1 fish silver
2 fish silver
3 dog brown
</code></pre>
<p>The above method can be build on very easily using multiple conditions like <code>&</code> and <code>|</code> to boolean index.</p>
<pre><code>df = pd.DataFrame({'Animal':['dog', 'fish', 'fish', 'dog'], 'Age': [1, 3, 2, 10]})
print(df)
Age Animal
0 1 dog
1 3 fish
2 2 fish
3 10 dog
df.ix[(df.Animal=='dog') & (df.Age > 8), 'Colour'] = 'grey' # old dogs go grey
df.ix[(df.Animal=='dog') & (df.Age <= 8), 'Colour'] = 'brown'
df.ix[df.Animal=='fish', 'Colour'] = 'silver'
print(df)
Age Animal Colour
0 1 dog brown
1 3 fish silver
2 2 fish silver
3 10 dog grey
</code></pre>
| 0 | 2016-10-05T12:37:55Z | [
"python",
"loops",
"pandas",
"condition",
"multiple-columns"
]
|
How can I install pip requirements? | 39,874,121 | <p>I am installing a requirements package list using</p>
<pre><code>pip install -r requirements.txt
</code></pre>
<p>but I am getting the error</p>
<pre><code> Using cached alabaster-0.7.8-py2.py3-none-any.whl
Collecting anaconda-client==1.4.0 (from -r requirements.txt (line 2))
Could not find a version that satisfies
the requirement anaconda-client==1.4.0 (from -r requirements.txt
(line 2)) (from versions: 1.1.1, 1.2.2)
No matching distribution found for anaconda-client==1.4.0
(from -r requirements.txt (line 2))
</code></pre>
<p>What does this error mean and how can I solve it?</p>
| -1 | 2016-10-05T12:34:43Z | 39,875,122 | <p>Pip is basically used to install the latest version of the files available on server
Pip install filename
Maybe the file you are installing is not on server till now</p>
| 1 | 2016-10-05T13:19:52Z | [
"python",
"pip",
"anaconda"
]
|
'Subclassing' a Function in Python? | 39,874,269 | <p>I'm working with the <code>docx</code> library in Python, and I was hoping to create a subclass <code>NewStyleDoc</code> of the <code>Document</code> class from <code>docx</code>. I attempted to do this as follows:</p>
<pre><code>from docx import Document
class NewStyleDocument(Document):
# stuff
</code></pre>
<p>And I received the error:</p>
<pre><code>TypeError: function() argument 1 must be code, not str
</code></pre>
<p>Which means <code>Document</code> is actually a function. (I verified this with <code>type(Document)</code>) My question is: can I define a class that inherits all of the properties of <code>Document</code>? My ultimate goals is simple: I just want to do:</p>
<pre><code>doc = NewStyleDocument()
</code></pre>
<p>and have some custom fonts. (Usually you have to modify styles each time you create a new document.) Maybe there is an easier way?</p>
| 0 | 2016-10-05T12:41:55Z | 39,874,466 | <p>This is from the documentation. Your issue seems to be you are using a constructor built into the module, not into the object.</p>
<pre><code>Document objects¶
class docx.document.Document[source]
WordprocessingML (WML) document. Not intended to be constructed directly. Use docx.Document() to open or create a document.
</code></pre>
<p>So you need to add another layer in there (Docx.document.Document)</p>
| 0 | 2016-10-05T12:51:06Z | [
"python",
"inheritance",
"docx"
]
|
'Subclassing' a Function in Python? | 39,874,269 | <p>I'm working with the <code>docx</code> library in Python, and I was hoping to create a subclass <code>NewStyleDoc</code> of the <code>Document</code> class from <code>docx</code>. I attempted to do this as follows:</p>
<pre><code>from docx import Document
class NewStyleDocument(Document):
# stuff
</code></pre>
<p>And I received the error:</p>
<pre><code>TypeError: function() argument 1 must be code, not str
</code></pre>
<p>Which means <code>Document</code> is actually a function. (I verified this with <code>type(Document)</code>) My question is: can I define a class that inherits all of the properties of <code>Document</code>? My ultimate goals is simple: I just want to do:</p>
<pre><code>doc = NewStyleDocument()
</code></pre>
<p>and have some custom fonts. (Usually you have to modify styles each time you create a new document.) Maybe there is an easier way?</p>
| 0 | 2016-10-05T12:41:55Z | 39,874,559 | <p>The simplest method (as <code>docx.Document</code>) appears to be a factory function is probably to just let it do what it needs to so you don't repeat, and wrap around it:</p>
<pre><code>from docx import Document
def NewStyleDocument(docx=None):
document = Document(docx)
document.add_heading('Document Title', 0)
return document
mydoc = NewStyleDocument()
</code></pre>
| 2 | 2016-10-05T12:54:45Z | [
"python",
"inheritance",
"docx"
]
|
Date with a time zone specified as a string is parsed as naive | 39,874,396 | <p>I'm curious why the timezone in this example, <code>GMT</code>, is not parsed as a valid one:</p>
<pre><code>>>> from datetime import datetime
>>> import pytz
>>> b = 'Mon, 3 Oct 2016 21:24:17 GMT'
>>> fmt = '%a, %d %b %Y %H:%M:%S %Z'
>>> datetime.strptime(b, fmt).astimezone(pytz.utc)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: astimezone() cannot be applied to a naive datetime
</code></pre>
<p>Doing the same with a <code>-0700</code> instead of <code>GMT</code> and <code>%z</code> instead of <code>%Z</code> in the format works just fine.</p>
<p>What's the proper way to parse dates ending in string time zones if not this?</p>
| -1 | 2016-10-05T12:47:47Z | 39,874,625 | <p>Use <code>.replace()</code> method with <code>datetime</code> object to update the time zone info.</p>
<pre><code>>>> datetime.strptime(b, fmt).replace(tzinfo=pytz.utc)
datetime.datetime(2016, 10, 3, 21, 24, 17, tzinfo=<UTC>)
</code></pre>
<p>Since you mentioned, <code>.astimezone()</code> is working with <code>%Z</code> instead of <code>%s</code> in the format string. Even though there is <code>z</code> in both the formatting (difference in just case), but they are totally different in terms of what they represent. </p>
<p>As per the <a href="http://strftime.org/" rel="nofollow"><code>strftime</code></a>'s directive document:</p>
<blockquote>
<p><strong>%z</strong> : UTC offset in the form +HHMM or -HHMM (empty string if the the object is naive).</p>
<p><strong>%Z</strong> : Time zone name (empty string if the object is naive).</p>
</blockquote>
| 0 | 2016-10-05T12:57:51Z | [
"python",
"datetime"
]
|
Get column names for max values over a certain row in a pandas DataFrame | 39,874,501 | <p>In the DataFrame</p>
<pre><code>import pandas as pd
df=pd.DataFrame({'col1':[1,2,3],'col2':[3,2,1],'col3':[1,1,1]},index= ['row1','row2','row3'])
print df
col1 col2 col3
row1 1 3 1
row2 2 2 1
row3 3 1 1
</code></pre>
<p>I want to get the column names of the cells with the max value(s) over a certain row. </p>
<p>The desired output would be (in pseudocode):</p>
<pre><code>get_column_name_for_max_values_of(row2)
>['col1','col2']
</code></pre>
<p>What would be the most concise way to express </p>
<pre><code>get_column_name_for_max_values_of(row2)
</code></pre>
<p>?</p>
| 1 | 2016-10-05T12:52:05Z | 39,874,583 | <p>If not duplicates, you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.idxmax.html" rel="nofollow"><code>idxmax</code></a>, but it return only first column of <code>max</code> value:</p>
<pre><code>print (df.idxmax(1))
row1 col2
row2 col1
row3 col1
dtype: object
def get_column_name_for_max_values_of(row):
return df.idxmax(1).ix[row]
print (get_column_name_for_max_values_of('row2'))
col1
</code></pre>
<p>But with duplicates use <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow"><code>boolean indexing</code></a>:</p>
<pre><code>print (df.ix['row2'] == df.ix['row2'].max())
col1 True
col2 True
col3 False
Name: row2, dtype: bool
print (df.ix[:,df.ix['row2'] == df.ix['row2'].max()])
col1 col2
row1 1 3
row2 2 2
row3 3 1
print (df.ix[:,df.ix['row2'] == df.ix['row2'].max()].columns)
Index(['col1', 'col2'], dtype='object')
</code></pre>
<p>And function is:</p>
<pre><code>def get_column_name_for_max_values_of(row):
return df.ix[:,df.ix[row] == df.ix[row].max()].columns.tolist()
print (get_column_name_for_max_values_of('row2'))
['col1', 'col2']
</code></pre>
| 1 | 2016-10-05T12:55:50Z | [
"python",
"pandas"
]
|
Get column names for max values over a certain row in a pandas DataFrame | 39,874,501 | <p>In the DataFrame</p>
<pre><code>import pandas as pd
df=pd.DataFrame({'col1':[1,2,3],'col2':[3,2,1],'col3':[1,1,1]},index= ['row1','row2','row3'])
print df
col1 col2 col3
row1 1 3 1
row2 2 2 1
row3 3 1 1
</code></pre>
<p>I want to get the column names of the cells with the max value(s) over a certain row. </p>
<p>The desired output would be (in pseudocode):</p>
<pre><code>get_column_name_for_max_values_of(row2)
>['col1','col2']
</code></pre>
<p>What would be the most concise way to express </p>
<pre><code>get_column_name_for_max_values_of(row2)
</code></pre>
<p>?</p>
| 1 | 2016-10-05T12:52:05Z | 39,874,650 | <p>you could also use apply and create a method such has:</p>
<pre><code>def returncolname(row, colnames):
return colnames[np.argmax(row.values)]
df['colmax'] = df.apply(lambda x: returncolname(x, df.columns), axis=1)
Out[62]:
row1 col2
row2 col1
row3 col1
dtype: object
</code></pre>
<p>an you can use df.max(axis=1) to extract maxes</p>
<pre><code>df.max(axis=1)
Out[69]:
row1 3
row2 2
row3 3
</code></pre>
| 2 | 2016-10-05T12:59:12Z | [
"python",
"pandas"
]
|
How to parse Python set-inside-list structure into text? | 39,874,541 | <p>I have the following strange format I am trying to parse. </p>
<p>The data structure I am trying to parse is a "set" of key-value pairs in a list:</p>
<pre><code>[{'key1:value1', 'key2:value2', 'key3:value3',...}]
</code></pre>
<p>That's the only data I have, and it needs to be processed. I don't think this can be described as a Python data structure, but I need to parse this to become a string like </p>
<pre><code>'key1:value1, key2:value2, key3:value3'.
</code></pre>
<p>Is this doable?</p>
<p>EDIT: Yes, it is <code>key:value</code>, not <code>key</code>:<code>value</code></p>
<p>Also, this is Python3.x</p>
| -3 | 2016-10-05T12:54:04Z | 39,874,598 | <pre><code>', '.join('{0}:{1}'.format(key, value) for key, value in my_dict.iteritems() for my_dict in my_list)
</code></pre>
<p>where my_list is name of your list variable</p>
| 1 | 2016-10-05T12:56:42Z | [
"python",
"regex",
"string",
"python-3.x"
]
|
How to parse Python set-inside-list structure into text? | 39,874,541 | <p>I have the following strange format I am trying to parse. </p>
<p>The data structure I am trying to parse is a "set" of key-value pairs in a list:</p>
<pre><code>[{'key1:value1', 'key2:value2', 'key3:value3',...}]
</code></pre>
<p>That's the only data I have, and it needs to be processed. I don't think this can be described as a Python data structure, but I need to parse this to become a string like </p>
<pre><code>'key1:value1, key2:value2, key3:value3'.
</code></pre>
<p>Is this doable?</p>
<p>EDIT: Yes, it is <code>key:value</code>, not <code>key</code>:<code>value</code></p>
<p>Also, this is Python3.x</p>
| -3 | 2016-10-05T12:54:04Z | 39,874,620 | <p>I would use itertools </p>
<pre><code>d = {'key1':'value1', 'key2':'value2', 'key3':'value3'}
for k, v in d.iteritems():
print k + v + ',',
</code></pre>
| 0 | 2016-10-05T12:57:40Z | [
"python",
"regex",
"string",
"python-3.x"
]
|
How to parse Python set-inside-list structure into text? | 39,874,541 | <p>I have the following strange format I am trying to parse. </p>
<p>The data structure I am trying to parse is a "set" of key-value pairs in a list:</p>
<pre><code>[{'key1:value1', 'key2:value2', 'key3:value3',...}]
</code></pre>
<p>That's the only data I have, and it needs to be processed. I don't think this can be described as a Python data structure, but I need to parse this to become a string like </p>
<pre><code>'key1:value1, key2:value2, key3:value3'.
</code></pre>
<p>Is this doable?</p>
<p>EDIT: Yes, it is <code>key:value</code>, not <code>key</code>:<code>value</code></p>
<p>Also, this is Python3.x</p>
| -3 | 2016-10-05T12:54:04Z | 39,874,733 | <p>Try this,</p>
<pre><code>print ', '.join(i for x in list_of_set for i in x)
</code></pre>
<p>If it's <code>set</code> there is no issue with the parsing. The code is equals to </p>
<pre><code>output = ''
for x in list of_set:
for i in x:
output += i
print output
</code></pre>
| 0 | 2016-10-05T13:02:21Z | [
"python",
"regex",
"string",
"python-3.x"
]
|
How to parse Python set-inside-list structure into text? | 39,874,541 | <p>I have the following strange format I am trying to parse. </p>
<p>The data structure I am trying to parse is a "set" of key-value pairs in a list:</p>
<pre><code>[{'key1:value1', 'key2:value2', 'key3:value3',...}]
</code></pre>
<p>That's the only data I have, and it needs to be processed. I don't think this can be described as a Python data structure, but I need to parse this to become a string like </p>
<pre><code>'key1:value1, key2:value2, key3:value3'.
</code></pre>
<p>Is this doable?</p>
<p>EDIT: Yes, it is <code>key:value</code>, not <code>key</code>:<code>value</code></p>
<p>Also, this is Python3.x</p>
| -3 | 2016-10-05T12:54:04Z | 39,874,761 | <p>So, you have a list whose only element is a dictionary, and you want to get all the keys-value pairs from that dictionary and put them into a string?</p>
<p>If so, try something like this:</p>
<pre><code>d = yourList[0]
s = ""
for key in d.keys():
s += key + ":" + d[key] + ", "
s = s[:-2] #To trim off the last comma that gets added
</code></pre>
| 0 | 2016-10-05T13:03:43Z | [
"python",
"regex",
"string",
"python-3.x"
]
|
How to parse Python set-inside-list structure into text? | 39,874,541 | <p>I have the following strange format I am trying to parse. </p>
<p>The data structure I am trying to parse is a "set" of key-value pairs in a list:</p>
<pre><code>[{'key1:value1', 'key2:value2', 'key3:value3',...}]
</code></pre>
<p>That's the only data I have, and it needs to be processed. I don't think this can be described as a Python data structure, but I need to parse this to become a string like </p>
<pre><code>'key1:value1, key2:value2, key3:value3'.
</code></pre>
<p>Is this doable?</p>
<p>EDIT: Yes, it is <code>key:value</code>, not <code>key</code>:<code>value</code></p>
<p>Also, this is Python3.x</p>
| -3 | 2016-10-05T12:54:04Z | 39,874,967 | <p>Iterating over <code>.items()</code> and formatting differently then previous answers.</p>
<p>If your data is the following: <code>list</code> of <code>dict</code> objects then</p>
<pre><code>>>> data = [{'key1':'value1', 'key2':'value2', 'key3':'value3'}]
>>> ', '.join('{0}:{1}'.format(*item) for item in my_dict.items() for my_dict in data)
'key2:value2, key3:value3, key1:value1'
</code></pre>
<p>If you data is the <code>list</code> of <code>set</code> objects then approach is simpler</p>
<pre><code>>>> from itertools import chain
>>> data = [{'key1:value1', 'key2:value2', 'key3:value3'}]
>>> ', '.join(chain.from_iterable(data))
'key1:value1, key2:value2, key3:value3'
</code></pre>
<p><strong>UPD</strong> </p>
<p>NOTE: order can be changed, because <code>set</code> and <code>dict</code> objects are not ordered.</p>
| 1 | 2016-10-05T13:13:20Z | [
"python",
"regex",
"string",
"python-3.x"
]
|
How to parse Python set-inside-list structure into text? | 39,874,541 | <p>I have the following strange format I am trying to parse. </p>
<p>The data structure I am trying to parse is a "set" of key-value pairs in a list:</p>
<pre><code>[{'key1:value1', 'key2:value2', 'key3:value3',...}]
</code></pre>
<p>That's the only data I have, and it needs to be processed. I don't think this can be described as a Python data structure, but I need to parse this to become a string like </p>
<pre><code>'key1:value1, key2:value2, key3:value3'.
</code></pre>
<p>Is this doable?</p>
<p>EDIT: Yes, it is <code>key:value</code>, not <code>key</code>:<code>value</code></p>
<p>Also, this is Python3.x</p>
| -3 | 2016-10-05T12:54:04Z | 39,875,064 | <p>Since your structure (let's call it <code>myStruct</code>) is a <code>set</code> rather than a <code>dict</code>, the following code should do what you want:</p>
<pre><code>result = ", ".join([x for x in myStruct[0]])
</code></pre>
<p>Beware, a <code>set</code> is not ordered, so you might end up with something like <code>'key2:value2, key1:value1, key3:value3'</code>.</p>
| 1 | 2016-10-05T13:17:32Z | [
"python",
"regex",
"string",
"python-3.x"
]
|
Python - replace a line by its column in file | 39,874,600 | <p>Sorry for posting such an easy question, but i couldn't find an answer on google.
I wish my code to do something like this
code:</p>
<pre><code>lines = open("Bal.txt").write
lines[1] = new_value
lines.close()
</code></pre>
<p>p.s i wish to replace the line in a file with a value</p>
| -1 | 2016-10-05T12:56:51Z | 39,876,489 | <p>xxx.dat before:</p>
<pre><code>ddddddddddddddddd
EEEEEEEEEEEEEEEEE
fffffffffffffffff
with open('xxx.txt','r') as f:
x=f.readlines()
x[1] = "QQQQQQQQQQQQQQQQQQQ\n"
with open('xxx.txt','w') as f:
f.writelines(x)
</code></pre>
<p>xxx.dat after:</p>
<pre><code>ddddddddddddddddd
QQQQQQQQQQQQQQQQQQQ
fffffffffffffffff
</code></pre>
<p>Note:f.read() returns a string, whereas f.readlines() returns a list, enabling you to replace an occurrence within that list.<br>
Inclusion of the <code>\n</code> (Linux) newline character is important to separate line[1] from line[2] when you next read the file, or you would end up with:</p>
<pre><code>ddddddddddddddddd
QQQQQQQQQQQQQQQQQQQfffffffffffffffff
</code></pre>
| 0 | 2016-10-05T14:19:02Z | [
"python",
"file"
]
|
python list is out of range at iteration 14? | 39,874,762 | <p>i have a list of indexes that point a term in database</p>
<p>Here is my code:</p>
<pre><code>for doc in TSS:
tokens = word_tokenize(doc[1])
tokens = [token.lower() for token in tokens if len(token) > 2]
tokens = [token for token in tokens if token not in words]
tokens = [stemmer.stem(token) for token in tokens]
final_tokens.extend(tokens)
sql = """SELECT id_term FROM tss_terms WHERE tss_terms.term IN %s"""
pram = [final_tokens]
cursor.execute(sql, pram)
ids = list(cursor.fetchall())
count = 0
data[doc[1]] = {'tf': {}, 'ntf': {}}
for token in final_tokens:
data[doc[1]]['tf'][token] = freq(token,final_tokens)
data[doc[1]]['ntf'][token] = tf(token,final_tokens)
query = """INSERT INTO tss_term_freq(id_term,id_doc,tf,normalized_tf)VALUES(%s,%s,%s,%s)"""
param = [ids[count],doc[0],data[doc[1]]['tf'][token],data[doc[1]]['ntf'][token]]
#cursor.execute(query, param)
count = count + 1
del final_tokens[:]
print count
</code></pre>
<p>the <code>ids</code> list always get <code>error : list index out of range</code> at the 14th iteration.</p>
<p>the values of TSS[13] are like this:</p>
<pre><code>(5927L, 'PERHITUNGAN POHON KELAPA SAWIT PADA CITRA FOTO UDARA\r\nYANG BERBASIS BENTUK MAHKOTA POHON')
</code></pre>
<p>then the values of TSS[14] are like this:</p>
<pre><code>(6698L, 'SINKRONISASI WAKTU METER LISTRIK BERDASARKAN GLOBAL POSITIONING SYSTEM (GPS) PADA SUPERVISORY CONTROL AND DATA ACQUISITION (SCADA) BERBASIS WEB')
</code></pre>
<p>TSS contains document ids and titles of thesis in my university</p>
<p>can anyone show my mistake and fix it?</p>
<p>Please help :(</p>
| -2 | 2016-10-05T13:03:44Z | 39,874,975 | <p>The way the list "id" is declared is wrong.
I didnt get what you are doing there.
But if want to store all the values returned by fetchall() function then use for loop for doing it.
Declare an empty list id.
id = [ ]
Use a for loop for taking all the values.
And to save the value in list use
id.append(value)</p>
| 0 | 2016-10-05T13:13:40Z | [
"python"
]
|
How to convert Odoo/Python code from old to new APIs? | 39,874,787 | <p>I am convert my whole Odoo Python code from the old API to the new API. So when I create new API this error is generated. How to solve it?</p>
<pre><code>File "/usr/lib/python2.7/dist-packages/simplejson/__init__.py", line 380, in dumps
return _default_encoder.encode(obj)
File "/usr/lib/python2.7/dist-packages/simplejson/encoder.py", line 275, in encode
chunks = self.iterencode(o, _one_shot=True)
File "/usr/lib/python2.7/dist-packages/simplejson/encoder.py", line 357, in iterencode
return _iterencode(o, 0)
File "/usr/lib/python2.7/dist-packages/simplejson/encoder.py", line 252, in default
raise TypeError(repr(o) + " is not JSON serializable")
TypeError: flight.itinerary(18,) is not JSON serializable
</code></pre>
| -3 | 2016-10-05T13:05:07Z | 39,875,356 | <p>Somewhere in your code you are passing an object ( flight.itinerary(18,) ) you probably are assigning a value like this.</p>
<pre><code>flight_itinerary = self.env['flight.itinerary'].browse([18])
something_else = flight_itinerary
</code></pre>
<p>Try </p>
<pre><code>something_else = flight_itinerary.id
</code></pre>
<p>My guess is you are passing a flight.itinerary object when you mean to pass the id </p>
| 1 | 2016-10-05T13:30:16Z | [
"python",
"openerp",
"odoo-8"
]
|
How do I get the computer to guess by enumeration? | 39,874,868 | <p>I've only just started using Python so please excuse how bad my code is!</p>
<p>So the computer is playing a game with itself where it has guessed a number between 0 and 100 (target) and it's trying to guess what that number was but it can only guess by enumeration ie. 1,2,3 etc. (i know this isn't the best way for to guess but it's the method I've been asked to show)</p>
<p>This is my code...</p>
<pre><code>print "Let's play a game."
print "I'm going to guess a number between 0 and 100. What is it?" #guess by enumeration
from random import randint
target = randint(0, 100)
print "This is the target number,", target
count=0
while True:
guess=0
guess+=1
count+=1
print guess
if guess == target:
print ("Well done, you got it! It took you", count, "attempts.")
break
else:
print "You didn't get it that time, try again."
</code></pre>
<p>I'm getting an error when I put this put in. I think there's an issue with the loop and getting the target and guess to equal each other.</p>
<p>This is also the first question I've asked so I'm sorry if this isn't how the questions should be submitted. I'd appreciate any help :-)</p>
| -1 | 2016-10-05T13:08:26Z | 39,874,991 | <p>Put the <code>guess = 0</code> before your <code>for</code> loop: you are reseting <code>guess</code> at each iteration.
Also, <code>count</code> and <code>guess</code> do exactly the same thing, you can just replace one of them by the other.
Finally, the <code>break</code> is not correctly indented, it should be at the same level as everything else in this <code>if</code> statement.</p>
| 1 | 2016-10-05T13:14:30Z | [
"python",
"python-2.7"
]
|
How do I get the computer to guess by enumeration? | 39,874,868 | <p>I've only just started using Python so please excuse how bad my code is!</p>
<p>So the computer is playing a game with itself where it has guessed a number between 0 and 100 (target) and it's trying to guess what that number was but it can only guess by enumeration ie. 1,2,3 etc. (i know this isn't the best way for to guess but it's the method I've been asked to show)</p>
<p>This is my code...</p>
<pre><code>print "Let's play a game."
print "I'm going to guess a number between 0 and 100. What is it?" #guess by enumeration
from random import randint
target = randint(0, 100)
print "This is the target number,", target
count=0
while True:
guess=0
guess+=1
count+=1
print guess
if guess == target:
print ("Well done, you got it! It took you", count, "attempts.")
break
else:
print "You didn't get it that time, try again."
</code></pre>
<p>I'm getting an error when I put this put in. I think there's an issue with the loop and getting the target and guess to equal each other.</p>
<p>This is also the first question I've asked so I'm sorry if this isn't how the questions should be submitted. I'd appreciate any help :-)</p>
| -1 | 2016-10-05T13:08:26Z | 39,875,129 | <p><code>gess</code> is always equal to <code>1</code> in the while loop, to solve it just move <code>guess=0</code> outside: </p>
<pre><code>...
guess = 0
while True:
guess +=1
....
</code></pre>
| 1 | 2016-10-05T13:20:12Z | [
"python",
"python-2.7"
]
|
JSONEncoder not handling lists | 39,875,038 | <p>I have a deeply nested data structure with extensive lists. I want to count the lists instead of displaying all the contents.</p>
<pre><code>class SummaryJSONEncoder(json.JSONEncoder):
"""
Simple extension to JSON encoder to handle date or datetime objects
"""
def default(self, obj):
func = inspect.currentframe().f_code
logger.info("%s in %s:%i" % (
func.co_name,
func.co_filename,
func.co_firstlineno
))
logger.info('default %s', type(obj))
if isinstance(obj, (datetime.datetime, datetime.date,)):
return obj.isoformat()
if isinstance(obj, (list, tuple, set,)):
return "count(%s)" % len(obj)
else:
logger.info('Falling back for %s', type(obj))
return super(SummaryJSONEncoder, self).default(obj)
def encode(self, obj):
func = inspect.currentframe().f_code
logger.info("%s in %s:%i" % (
func.co_name,
func.co_filename,
func.co_firstlineno
))
return super(SummaryJSONEncoder, self).encode(obj)
</code></pre>
<p>The sets seem to encode properly, but lists and tuples will not bend to my will.</p>
<pre><code> >>> json.dumps({'hello': set([]), 'world': [1,2,3], 'snot': (1,2,3,), 'time': datetime.datetime.now()}, indent=4, cls=SummaryJSONEncoder)
2016-10-05 14:07:42,786 (9296) __main__ INFO - encode in <pyshell#56>:20
2016-10-05 14:07:42,789 (9296) __main__ INFO - default in <pyshell#56>:5
2016-10-05 14:07:42,792 (9296) __main__ INFO - default <type 'set'>
2016-10-05 14:07:42,793 (9296) __main__ INFO - default in <pyshell#56>:5
2016-10-05 14:07:42,796 (9296) __main__ INFO - default <type 'datetime.datetime'>
'{\n "world": [\n 1, \n 2, \n 3\n ], \n "hello": "count(0)", \n "snot": [\n 1, \n 2, \n 3\n ], \n "time": "2016-10-05T14:07:42.786000"\n}'
>>>
</code></pre>
<p>I cannot tell, but it looks like lists and tuples are handled elsewhere and not passed to the default method. Has anyone needed to do this before?</p>
| 1 | 2016-10-05T13:16:37Z | 39,875,880 | <p>This seems to work</p>
<pre><code>class SummaryJSONEncoder(json.JSONEncoder):
"""
Simple extension to JSON encoder to handle date or datetime objects
"""
def default(self, obj):
if isinstance(obj, (datetime.datetime, datetime.date,)):
return obj.isoformat()
if isinstance(obj, (list, tuple, set,)):
return "count(%s)" % len(obj)
else:
return super(SummaryJSONEncoder, self).default(obj)
def _iterencode_list(self, obj, x):
if isinstance(obj, (list, tuple, set,)):
return self.default(obj)
return super(SummaryJSONEncoder, self)._iterencode_list(obj, x)
</code></pre>
<p>The code trace is.</p>
<pre><code>json.dumps({'hello': set([]), 'world': [1,2,3], 'snot': (1,2,3,), 'time': datetime.datetime.now()}, indent=4, cls=SummaryJSONEncoder)
2016-10-05 14:50:10,785 (9296) __main__ INFO - default in <pyshell#73>:5
2016-10-05 14:50:10,788 (9296) __main__ INFO - default <type 'list'>
2016-10-05 14:50:10,792 (9296) __main__ INFO - default in <pyshell#73>:5
2016-10-05 14:50:10,796 (9296) __main__ INFO - default <type 'set'>
2016-10-05 14:50:10,799 (9296) __main__ INFO - default in <pyshell#73>:5
2016-10-05 14:50:10,802 (9296) __main__ INFO - default <type 'tuple'>
2016-10-05 14:50:10,806 (9296) __main__ INFO - default in <pyshell#73>:5
2016-10-05 14:50:10,811 (9296) __main__ INFO - default <type 'datetime.datetime'>
'{\n "world": count(3), \n "hello": "count(0)", \n "snot": count(3), \n "time": "2016-10-05T14:50:10.785000"\n}'
</code></pre>
<p>I hope this helps someone :-)</p>
| 0 | 2016-10-05T13:52:18Z | [
"python",
"json",
"list",
"set",
"encode"
]
|
Member of a CBV in Django | 39,875,057 | <p>I'm, trying to implement a LoginRequiredMixin. For example, if user goes to /post/6 and he isn't logged in, he is redirected to /auth/login/?next=/post/6. I'm trying to make a function that will redirect user either to /post/* (according to next in the url) or to the / if there is no next in the url. I tried to get a url param in GET request, save it to CBV member and then use it in post. But for some reasons it isn't actually saved. Here is a piece of my code:</p>
<pre><code>class LoginView(View):
redirect_to = ''
def post(self, request, *args, **kwargs):
user = authenticate(username=request.POST['login'], password=request.POST['password'])
print(self.redirect_to) # It's equal to '' here
if user is not None:
login(request, user)
else:
print("Account doesn't exists!")
return HttpResponseRedirect(reverse('blog:index'))
def get(self, request, *args, **kwargs):
self.redirect_to = 'edited'
form = RegistrationForm()
return render(request, 'authorization/login.html', {
'form': form
})
</code></pre>
<p>Maybe there is any other solutions? Thanks in advance!</p>
| 0 | 2016-10-05T13:17:13Z | 39,917,875 | <p>I think your safest bet is to use <a href="https://django-braces.readthedocs.io/" rel="nofollow"><code>braces</code></a>:</p>
<h2>Installation</h2>
<pre><code>$ pip install braces
</code></pre>
<h2>Usage</h2>
<p>The <a href="https://django-braces.readthedocs.io/en/latest/access.html#loginrequiredmixin" rel="nofollow"><code>LoginRequiredMixin</code></a> pretty much aims to replicate the <code>login_required</code> decorator functionality for CBVs:</p>
<pre><code>from django.views.generic import TemplateView
from braces.views import LoginRequiredMixin
class SomeSecretView(LoginRequiredMixin, TemplateView):
template_name = "path/to/template.html"
login_url = "/login/"
def get(self, request):
return self.render_to_response({})
</code></pre>
| 0 | 2016-10-07T12:57:07Z | [
"python",
"django",
"django-views"
]
|
Merging two dic in python3 using Unpacking Generalisations in Python3.5 | 39,875,061 | <p>There are two dictionaries as follow which I want to merge them, my point is to select those keys that I am interested in, for example I am interested in all the keys except county. Solution I 've used is using <code>del</code> function after creating your new dictionary, however I am sure there are more ways that are more efficient to my solution. How can I solve this problem without del function using <strong>UNPACKING ARGUMENT</strong>.</p>
<pre><code> >>> d1 = {'avgUserperDay': '12', 'avgPurchaseperDay': '1', 'country': 'Japan'}
>>> d2 = {'tUser': 1, 'tPurchase': 0, 'country': 'Japan'}
>>> d ={**d1,**d2}
>>>{'tUser': 1, 'tPurchase': 0, 'avgPurchaseperDay': '1', 'avgUserperDay': '12', 'country': 'Japan'}
>>> del d['country']
>>> d
{'tUser': 1, 'tPurchase': 0, 'avgPurchaseperDay': '1', 'avgUserperDay': '12'}
</code></pre>
<p>AFTER DISCUSSION, </p>
<p>This command works with 3.5.1,</p>
<pre><code>>>> {**{k:v for k, v in chain(d1.items(), d2.items()) if k != 'country'}}
{'tUser': 1, 'tPurchase': 0, 'avgPurchaseperDay': '1', 'avgUserperDay': '12'}
</code></pre>
| -1 | 2016-10-05T13:17:22Z | 39,875,335 | <p>why would you want to do it using argument unpacking?
just do:</p>
<pre><code>from itertools import chain
d = {key:value for key, value in chain(d1.iteritems(), d2.iteritems())
if key not in keys_to_ignore}
</code></pre>
<p>where keys_to_ignore is list/set/tuple of keys you want to ignore</p>
| 1 | 2016-10-05T13:29:31Z | [
"python",
"python-3.5",
"argument-unpacking"
]
|
Merging two dic in python3 using Unpacking Generalisations in Python3.5 | 39,875,061 | <p>There are two dictionaries as follow which I want to merge them, my point is to select those keys that I am interested in, for example I am interested in all the keys except county. Solution I 've used is using <code>del</code> function after creating your new dictionary, however I am sure there are more ways that are more efficient to my solution. How can I solve this problem without del function using <strong>UNPACKING ARGUMENT</strong>.</p>
<pre><code> >>> d1 = {'avgUserperDay': '12', 'avgPurchaseperDay': '1', 'country': 'Japan'}
>>> d2 = {'tUser': 1, 'tPurchase': 0, 'country': 'Japan'}
>>> d ={**d1,**d2}
>>>{'tUser': 1, 'tPurchase': 0, 'avgPurchaseperDay': '1', 'avgUserperDay': '12', 'country': 'Japan'}
>>> del d['country']
>>> d
{'tUser': 1, 'tPurchase': 0, 'avgPurchaseperDay': '1', 'avgUserperDay': '12'}
</code></pre>
<p>AFTER DISCUSSION, </p>
<p>This command works with 3.5.1,</p>
<pre><code>>>> {**{k:v for k, v in chain(d1.items(), d2.items()) if k != 'country'}}
{'tUser': 1, 'tPurchase': 0, 'avgPurchaseperDay': '1', 'avgUserperDay': '12'}
</code></pre>
| -1 | 2016-10-05T13:17:22Z | 39,875,385 | <blockquote>
<p>How can I solve this problem without del function using UNPACKING ARGUMENT?</p>
</blockquote>
<p>Yes, you can. But you should not. Ideal way should be:</p>
<pre><code>d1.update(d2) # values will be updated in d1 dict
del d1['country']
</code></pre>
<p>There no direct way to meet your conditions:</p>
<ul>
<li>create new <code>dict</code> using <em>argument unpacking</em></li>
<li>not using <code>del</code> to remove country.</li>
</ul>
<p>But there are work around if this is what you want. For example using <code>itertools.chain()</code> with <em>dict comprehension</em> as:</p>
<pre><code>{**{k:v for k, v in chain(d1.items(), d2.items()) if k != 'country'}}
</code></pre>
<p><em>Note:</em> For those curios about how <code>{**dict1, **dict2}</code> even works. It is new syntax supported since from python 3.5+, proposed in <a href="https://www.python.org/dev/peps/pep-0448/" rel="nofollow">PEP 448</a>. Check: <a href="https://docs.python.org/dev/whatsnew/3.5.html#pep-448-additional-unpacking-generalizations" rel="nofollow">What's New in Python 3.5</a> document.</p>
<p>Since, <strong><code>{**dict1, **dict2}</code> is only supported in Python 3.5+</strong>, for earlier version of Python, you can do (as mentioned by S. <a href="http://stackoverflow.com/a/39875454/2063361">De Melo</a>):</p>
<pre><code>d = dict(d1, **d2)
d.pop("country")
</code></pre>
<p>OR without using <code>**</code> as:</p>
<pre><code>{k, v for k, v in chain(d1.iteritems(), d2.iteritems()) if k != 'country'}
</code></pre>
| 1 | 2016-10-05T13:31:01Z | [
"python",
"python-3.5",
"argument-unpacking"
]
|
Merging two dic in python3 using Unpacking Generalisations in Python3.5 | 39,875,061 | <p>There are two dictionaries as follow which I want to merge them, my point is to select those keys that I am interested in, for example I am interested in all the keys except county. Solution I 've used is using <code>del</code> function after creating your new dictionary, however I am sure there are more ways that are more efficient to my solution. How can I solve this problem without del function using <strong>UNPACKING ARGUMENT</strong>.</p>
<pre><code> >>> d1 = {'avgUserperDay': '12', 'avgPurchaseperDay': '1', 'country': 'Japan'}
>>> d2 = {'tUser': 1, 'tPurchase': 0, 'country': 'Japan'}
>>> d ={**d1,**d2}
>>>{'tUser': 1, 'tPurchase': 0, 'avgPurchaseperDay': '1', 'avgUserperDay': '12', 'country': 'Japan'}
>>> del d['country']
>>> d
{'tUser': 1, 'tPurchase': 0, 'avgPurchaseperDay': '1', 'avgUserperDay': '12'}
</code></pre>
<p>AFTER DISCUSSION, </p>
<p>This command works with 3.5.1,</p>
<pre><code>>>> {**{k:v for k, v in chain(d1.items(), d2.items()) if k != 'country'}}
{'tUser': 1, 'tPurchase': 0, 'avgPurchaseperDay': '1', 'avgUserperDay': '12'}
</code></pre>
| -1 | 2016-10-05T13:17:22Z | 39,875,454 | <p>If you don't want to use <code>del</code>, you can replace it by <code>.pop(key)</code>.
For example, using unpacking argument too:</p>
<pre><code>d = dict(d1, **d2)
d.pop("country")
</code></pre>
<p>Notice that <code>.pop</code> returns the value too (here "Japan").</p>
| 1 | 2016-10-05T13:34:08Z | [
"python",
"python-3.5",
"argument-unpacking"
]
|
Python - TypeError: unbound method error | 39,875,067 | <p>Please help, I am new to python and now getting below error </p>
<p>"<em>TypeError: unbound method assertEqual() must be called with ExampleScript14 instance as first argument (got str instance instead)</em>"</p>
<p><strong>for the below code:</strong></p>
<p>from selenium import webdriver
from selenium.webdriver.common.by import By
import unittest
import time
import variables
from time import sleep</p>
<pre><code>class ExampleScript14(unittest.TestCase):
@classmethod
def setUpClass(cls):
super(ExampleScript14, cls).setUpClass()
cls.driver = webdriver.Chrome()
cls.driver.get(cls.url)
cls.test_click_the_username()
@classmethod
def test_click_the_username(self):
# Click the USer name
self.driver.find_element_by_link_text(variables.USER_NAME).click()
# click the Edit button
self.driver.find_element_by_id("btnSave").click()
print "Verify Edit button changed to Save button"
element = self.driver.find_element_by_id("btnSave")
element_attribute = element.get_attribute("value").encode('utf8')
print "attr:", type(element_attribute)
print "The button value is:", element_attribute
self.assertEqual("Save", element_attribute)
if __name__ == "__main__":
unittest.main()
</code></pre>
| -1 | 2016-10-05T13:17:38Z | 39,875,141 | <p>You <code>test_click_the_username</code> should not be a <code>classmethod</code>. Just delete <code>@classmethod</code> decorator and it should work.</p>
| 1 | 2016-10-05T13:20:54Z | [
"python",
"selenium"
]
|
Run the urls in python | 39,875,212 | <p>I would like to download some datasets from a webpage X. Links to my datasets are included on the webpage. This is my code (I changed the name of the webpage)</p>
<pre><code>import urllib2
from BeautifulSoup import *
import webbrowser
link = urllib2.urlopen('http://www.x.com/html/tlc/html/about/abcd.shtml').read()
soup = BeautifulSoup(link)
tags = soup('a')
for tag in tags:
if 'https://s3.amazonaws.com/abcd/qwer/' in tag.get('href'):
webbrowser.open(tag.get('href'))
</code></pre>
<p>This works fine. However, there are around 40 links of datasets I need to download on the webpage. If I run this code, my Chrome will open 40 new tabs almost at the same time, and since my computer is quite slow, only 6 datasets are downloaded.</p>
<p>Really appreciate if someone could help me fix this</p>
| -1 | 2016-10-05T13:24:12Z | 39,875,363 | <p>Since this seems to be a problem of your computer/browser, you could try to not download them all at once.</p>
<p>Have a look at this:
<a href="http://stackoverflow.com/questions/24533951/wait-for-download-completion-in-python">Wait for download completion in Python</a></p>
<p>This uses the urllib without opening the browser.</p>
| -1 | 2016-10-05T13:30:24Z | [
"python",
"beautifulsoup"
]
|
Python script stops after a few minutes | 39,875,272 | <p>I'm building a python script to check the price of an amazon item every 5-10 seconds. Problem is, the script stops 'working' after a few minutes. There is no output to the console but it shows up as 'running' in my processes.</p>
<p>I'm using requests sessions for making http requests and time to display the time of request. </p>
<p>My code is as follows;</p>
<pre><code>target_price = raw_input('Enter target price: ')
url = raw_input('Enter the product url: ')
while True:
delay=randint(5,10)
print datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d %H:%M:%S')+': '+'Sleeping for ' + str(delay) + ' seconds'
time.sleep(delay)
try:
with requests.Session() as s:
page = s.get(url,headers=headers,proxies=proxyDict,verify=False,timeout=5)
tree = html.fromstring(page.content)
price = tree.xpath('//div[@class="a-row a-spacing-mini olpOffer"]/div[@class="a-column a-span2 olpPriceColumn"]/span[@class="a-size-large a-color-price olpOfferPrice a-text-bold"]/text()')[0]
new_price = re.findall("[-+]?\d+[\.]?\d+[eE]?[-+]?\d*", price)[0]
old_price = new_price
print new_price
if float(new_price)<float(target_price):
print 'Lower price found!'
mydriver = webdriver.Chrome()
send_simple_message()
login(mydriver)
print 'Old Price: ' + old_price
print 'New Price: ' + new_price
else:
print 'Trying again'
except Exception as e:
print e
print 'Error!'
</code></pre>
<p>EDIT: I've removed the wait() function and used time.sleep instead.</p>
<p>EDIT2: When I use Keyboard interrupt to stop the script, here's the output</p>
<pre><code> Traceback (most recent call last):
File "checker.py", line 85, in <module>
page = s.get(url,headers=headers,proxies=proxyDict,verify=False,timeout=5)
File "C:\Python27\lib\site-packages\requests\sessions.py", line 488, in get
return self.request('GET', url, **kwargs)
File "C:\Python27\lib\site-packages\requests\sessions.py", line 475, in request
resp = self.send(prep, **send_kwargs)
File "C:\Python27\lib\site-packages\requests\sessions.py", line 596, in send
r = adapter.send(request, **kwargs)
File "C:\Python27\lib\site-packages\requests\adapters.py", line 423, in send
timeout=timeout
File "C:\Python27\lib\site-packages\requests\packages\urllib3\connectionpool.py", line 589, in urlopen
self._prepare_proxy(conn)
File "C:\Python27\lib\site-packages\requests\packages\urllib3\connectionpool.py", line 797, in _prepare_proxy
conn.connect()
File "C:\Python27\lib\site-packages\requests\packages\urllib3\connection.py",
line 267, in connect
self._tunnel()
File "C:\Python27\lib\httplib.py", line 729, in _tunnel
line = response.fp.readline()
KeyboardInterrupt
</code></pre>
<p>Is it requests that is running into an infinite loop?</p>
| 3 | 2016-10-05T13:26:43Z | 39,876,241 | <p>The timeout argument to the <code>s.get()</code> function is tricky. <a href="http://docs.python-requests.org/en/latest/user/quickstart/#timeouts" rel="nofollow">Here</a> I found a good explanation for its unusual behavior. The <code>timeout</code> will stop the process if the requested url does not respond but it wouldn't stop it if it respond infinitely.</p>
<p>In your case, the connection is established nut the requested page is just sending responses in an infinite loop.</p>
<p>You can set a timeout for the whole function call: <a href="http://stackoverflow.com/questions/2281850/timeout-function-if-it-takes-too-long-to-finish">Timeout function if it takes too long to finish</a></p>
| 0 | 2016-10-05T14:08:59Z | [
"python"
]
|
Insertion sort doesn't sort | 39,875,273 | <p>I have attempted to create an insertion sort in python, however the list returned is not sorted. What is the problem with my code?</p>
<p>Argument given: [3, 2, 1, 4, 5, 8, 7, 9, 6]</p>
<p>Result: 2
1
3
6
4
7
5
8
9</p>
<p>Python code:</p>
<pre><code>def insertion_sort(mylist):
sorted_list = []
for i in mylist:
posfound = 0 #defaults to 0
for j in range(len(sorted_list)):
if sorted_list[j] > i:
sorted_list.insert(j-1, i) #put the number in before element 'j'
posfound = 1 #if you found the correct position in the list set to 1
break
if posfound == 0: #if you can't find a place in the list
sorted_list.insert(len(sorted_list), i) #put number at the end of the list
return sorted_list
</code></pre>
| 2 | 2016-10-05T13:26:48Z | 39,875,453 | <p>You need to change <code>sorted_list.insert(j-1, i)</code> to be <code>sorted_list.insert(j, i)</code> to insert before position <code>j</code>. </p>
<p><code>insert(j-1, ..)</code> will insert before the <em>previous</em> element, and in the case where <code>j=0</code> it'll wrap around and insert before the last element. </p>
<p>The <a href="https://docs.python.org/3/tutorial/datastructures.html#data-structures" rel="nofollow">Python data structures tutorial</a> may be useful. </p>
| 4 | 2016-10-05T13:34:08Z | [
"python",
"algorithm",
"insertion-sort"
]
|
Insertion sort doesn't sort | 39,875,273 | <p>I have attempted to create an insertion sort in python, however the list returned is not sorted. What is the problem with my code?</p>
<p>Argument given: [3, 2, 1, 4, 5, 8, 7, 9, 6]</p>
<p>Result: 2
1
3
6
4
7
5
8
9</p>
<p>Python code:</p>
<pre><code>def insertion_sort(mylist):
sorted_list = []
for i in mylist:
posfound = 0 #defaults to 0
for j in range(len(sorted_list)):
if sorted_list[j] > i:
sorted_list.insert(j-1, i) #put the number in before element 'j'
posfound = 1 #if you found the correct position in the list set to 1
break
if posfound == 0: #if you can't find a place in the list
sorted_list.insert(len(sorted_list), i) #put number at the end of the list
return sorted_list
</code></pre>
| 2 | 2016-10-05T13:26:48Z | 39,875,475 | <p>As often, it was a off-by-one error, the code below is fixed. I also made some parts a bit prettier.</p>
<pre><code>def insertion_sort(mylist):
sorted_list = []
for i in mylist:
for index, j in enumerate(sorted_list):
if j > i:
sorted_list.insert(index, i) #put the number in before element 'j'
break
else:
sorted_list.append(i) #put number at the end of the list
return sorted_list
</code></pre>
| 1 | 2016-10-05T13:35:01Z | [
"python",
"algorithm",
"insertion-sort"
]
|
Insertion sort doesn't sort | 39,875,273 | <p>I have attempted to create an insertion sort in python, however the list returned is not sorted. What is the problem with my code?</p>
<p>Argument given: [3, 2, 1, 4, 5, 8, 7, 9, 6]</p>
<p>Result: 2
1
3
6
4
7
5
8
9</p>
<p>Python code:</p>
<pre><code>def insertion_sort(mylist):
sorted_list = []
for i in mylist:
posfound = 0 #defaults to 0
for j in range(len(sorted_list)):
if sorted_list[j] > i:
sorted_list.insert(j-1, i) #put the number in before element 'j'
posfound = 1 #if you found the correct position in the list set to 1
break
if posfound == 0: #if you can't find a place in the list
sorted_list.insert(len(sorted_list), i) #put number at the end of the list
return sorted_list
</code></pre>
| 2 | 2016-10-05T13:26:48Z | 39,875,722 | <p>As Efferalgan & tzaman have mentioned your core problem is due to an off-by-one error. To catch these sorts of errors it's useful to print <code>i</code>, <code>j</code> and <code>sorted_list</code> on each loop iteration to make sure they contain what you think they contain.</p>
<p>Here are a few versions of your algorithm. First, a repaired version of your code that fixes the off-by-one error; it also implements Efferalgan's suggestion of using <code>.append</code> if an insertion position isn't found.</p>
<pre><code>def insertion_sort(mylist):
sorted_list = []
for i in mylist:
posfound = 0 #defaults to 0
for j in range(len(sorted_list)):
if sorted_list[j] > i:
sorted_list.insert(j, i) #put the number in before element 'j'
posfound = 1 #if you found the correct position in the list set to 1
break
if posfound == 0: #if you can't find a place in the list
sorted_list.append(i) #put number at the end of the list
return sorted_list
</code></pre>
<p>Here's a slightly improved version that uses an <code>else</code> clause on the loop instead of the <code>posfound</code> flag; it also uses slice assignment to do the insertion.</p>
<pre><code>def insertion_sort(mylist):
sorted_list = []
for i in mylist:
for j in range(len(sorted_list)):
if sorted_list[j] > i:
sorted_list[j:j] = [i]
break
else: #if you can't find a place in the list
sorted_list.append(i) #put number at the end of the list
return sorted_list
</code></pre>
<p>Finally, a version that uses <code>enumerate</code> to get the indices and items in <code>sorted_list</code> rather than a simple <code>range</code> loop.</p>
<pre><code>def insertion_sort(mylist):
sorted_list = []
for u in mylist:
for j, v in enumerate(sorted_list):
if v > u:
sorted_list[j:j] = [u]
break
else: #if you can't find a place in the list
sorted_list.append(u) #put number at the end of the list
return sorted_list
</code></pre>
| 2 | 2016-10-05T13:46:21Z | [
"python",
"algorithm",
"insertion-sort"
]
|
how to send application/x-www-form-urlencoded JSON string in python botlle server | 39,875,519 | <p>I want to post a JSON string in the format of </p>
<pre><code>application/x-www-form-urlencoded
</code></pre>
<p>using python's bottle</p>
<p>Here's the web service I had written</p>
<pre><code>import json
from bottle import route, run, request
@route('/ocr_response2', method='POST')
def ocr_response2():
word = request.json
print word
if __name__ == "__main__":
run(host='0.0.0.0', port=8080, debug=True)
</code></pre>
<p>I know this would work if <code>contentType: "application/json",</code>
But can't figure out if content type is <code>application/x-www-form-urlencoded
</code></p>
<p>Here's how i am sending the data </p>
<pre><code>import requests
d = {'spam': 20, 'eggs': 3}
requests.post("http://XX.XX.XX.XXX:8080", data=d)
</code></pre>
| -1 | 2016-10-05T13:36:51Z | 39,876,141 | <p>use <code>request.forms.get('spam')</code></p>
<p>also in <code>requests.post</code> url should be <code>http://XX.XX.XX.XXX:8080/ocr_response2</code></p>
| 1 | 2016-10-05T14:04:27Z | [
"python",
"bottle"
]
|
When i run this command " cascPath = sys.argv[1] " i get error IndexError: list index out of range | 39,875,587 | <p>I am using a Raspberry Pi 3 Model B, with Raspbian, opencv 2.x and Python 3 installed.</p>
<p>I want to access my USB Webcam and take a picture with it.
I've found tons of code but none are of any use. I found one which is better but when I run the command</p>
<pre><code>cascPath = sys.argv[1]
</code></pre>
<p>I get the error </p>
<blockquote>
<p>Traceback (most recent call last):</p>
<p>File "/home/pi/test.py", line 4, in </p>
<pre><code>cascPath = sys.argv[1]
</code></pre>
<p>IndexError: list index out of range</p>
</blockquote>
<p>I simply need to access my webcam to take a picture.</p>
<hr>
<pre><code>import cv2
import sys
cascPath = sys.argv[1]
faceCascade = cv2.CascadeClassifier(cascPath)
video_capture = cv2.VideoCapture(0)
while True:
# Capture frame-by-frame
ret, frame = video_capture.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = faceCascade.detectMultiScale(
gray,
scaleFactor=1.1,
minNeighbors=5,
minSize=(30, 30),
flags=cv2.cv.CV_HAAR_SCALE_IMAGE
)
# Draw a rectangle around the faces
for (x, y, w, h) in faces:
cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)
# Display the resulting frame
cv2.imshow('Video', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
#When everything is done, release the capture
video_capture.release()
cv2.destroyAllWindows()
</code></pre>
<p>This is the code</p>
| -3 | 2016-10-05T13:40:07Z | 39,875,673 | <p><code>sys.argv[1]</code> is the first CLI parameter and if you don't provide any CLI parameter, <code>len(sys.argv)=1</code> so you can only access sys.argv[0] which is the script name.</p>
<p>What you need to do is provide a CLI parameter which is for <code>cascPath</code>.</p>
<p>The Cascade is a xml file contains OpenCV data to detect objects which might comes with the tutorial you read / the code snippet you downloaded.</p>
| 0 | 2016-10-05T13:44:14Z | [
"python",
"opencv",
"webcam",
"raspberry-pi3",
"getpicture"
]
|
Python regex words boundary with unexpected results | 39,875,620 | <pre><code>import re
sstring = "ON Any ON Any"
regex1 = re.compile(r''' \bON\bANY\b''', re.VERBOSE)
regex2 = re.compile(r'''\b(ON)?\b(Any)?''', re.VERBOSE)
regex3 = re.compile(r'''\b(?:ON)?\b(?:Any)?''', re.VERBOSE)
for a in regex1.findall(sstring): print(a)
print("----------")
for a in regex2.findall(sstring): print(a)
print("----------")
for a in regex3.findall(sstring): print(a)
print("----------")
</code></pre>
<blockquote>
<hr>
<p>('ON', '')
('', '')
('', 'Any')
('', '')
('ON', '')
('', '')
('', 'Any')</p>
<h2>('', '')</h2>
<p>ON</p>
<p>Any</p>
<p>ON</p>
<p>Any</p>
<hr>
</blockquote>
<p>Having read many articles on the internet and S.O. I think I still don't understand the regex word boundary: <code>\b</code></p>
<p>The first regex doesn't give me the expected result I think it's must give me "ON Any On Any" but it still not give me that.</p>
<p>The second regex gives me tuples and I don't know why or understand the meaning of: ('', '')</p>
<p>The third regex gives prints the results on separated lines and empty lines in betweens</p>
<p>Could you please help me to understand that.</p>
| 1 | 2016-10-05T13:41:22Z | 39,876,126 | <p>Note that to match <code>ON ANY</code> you need to add an escaped (since you are using <code>re.VERBOSE</code> flag) space between <code>ON</code> and <code>ANY</code> as <code>\b</code> word boundary <em>being a <strong>zero-width assertion</em></strong> does not consume any text, just asserts a position between specific characters. That is the reason for your first <code>re.compile(r''' \bON\bANY\b''', re.VERBOSE)</code> approach failure.</p>
<p>Use</p>
<pre><code>rx = re.compile(r''' \bON\ ANY\b ''', re.VERBOSE|re.IGNORECASE)
</code></pre>
<p>See the <a href="https://ideone.com/cBsGLd" rel="nofollow">Python demo</a></p>
<p>The <code>re.compile(r'''\b(ON)?\b(Any)?''', re.VERBOSE)</code> returns tuples since you defined <code>(...)</code> <em>capturing groups</em> in the pattern.</p>
<p>The <code>re.compile(r'''\b(?:ON)?\b(?:Any)?''', re.VERBOSE)</code> matches optional sequences, either <code>ON</code> or <code>Any</code>, so you get those words as values. You get empty values as well because this regex can match just a word boundary (all other subpatterns are optional).</p>
<p>More details about word boundaries:</p>
<ul>
<li><a href="http://www.regular-expressions.info/wordboundaries.html" rel="nofollow">Regular-Expressions.info</a></li>
<li><a class='doc-link' href="http://stackoverflow.com/documentation/regex/1539/word-boundary#t=201610051404594046741">SO Word Boundary Documentation</a></li>
<li><a href="http://stackoverflow.com/questions/21389837/java-regex-word-boundaries">Java Regex Word Boundaries</a> (this is still a word boundary in a regex, also applicable here)</li>
</ul>
| 0 | 2016-10-05T14:04:01Z | [
"python",
"regex",
"word-boundary"
]
|
Sending audio data from JS to Python | 39,875,668 | <p>I'm trying to send a .wav audio file (blob) från JS to Python using Flask. I simply want to save the file on the Python end and be able to play it on my computer. Here is my try:</p>
<p><strong>JS:</strong> </p>
<pre><code>fetch(serverUrl, {
method: "post",
body: blob
});
</code></pre>
<p>Where blob is of the type <code>Blob {size: 5040, type: "audio/wav;"}</code></p>
<p><strong>Python:</strong> </p>
<pre><code>@app.route('/messages', methods = ['POST'])
def api_message():
# Open file and write binary (blob) data
f = open('./file.wav', 'wb')
f.write(request.data)
f.close()
return "Binary message written!"
</code></pre>
<p>The file gets saved but only contains shitloads of <code>[object BlobEvent]</code>. What am I doing wrong and how can I fix it?</p>
<p><strong>Edit:</strong>
The audio samples are collected using <code>MediaRecorder()</code></p>
<pre><code>const mediaRecorder = new MediaRecorder(stream);
// Start
const chunks = [];
mediaRecorder.ondataavailable = e => {
chunks.push(e);
}
// On stop
blob = new Blob(chunks, {'type': 'audio/wav;'});
</code></pre>
<p>I tried playing the audio again on the client side and it works just fine:</p>
<pre><code>const audio = document.createElement('audio');
const audioURL = window.URL.createObjectURL(blob);
audio.src = audioURL;
</code></pre>
| 0 | 2016-10-05T13:43:56Z | 39,879,185 | <p>Have you tried using FormData?</p>
<pre><code>var form = new FormData();
form.append('file', BLOBDATA, FILENAME);
$.ajax({
type: 'POST',
url: 'ServerURL',
data: form, // Our pretty new form
cache: false,
processData: false, // tell jQuery not to process the data
contentType: false // tell jQuery not to set contentType
}).done(function(data) {
console.log(data);
});
</code></pre>
<p>On the python end, you could check if the data's there by doing something like:</p>
<pre><code>@app.route('/messages', methods=['POST'])
def api_message():
app.logger.debug(request.files['file'].filename)
</code></pre>
| 0 | 2016-10-05T16:22:28Z | [
"javascript",
"python",
"audio",
"flask",
"blob"
]
|
Sending audio data from JS to Python | 39,875,668 | <p>I'm trying to send a .wav audio file (blob) från JS to Python using Flask. I simply want to save the file on the Python end and be able to play it on my computer. Here is my try:</p>
<p><strong>JS:</strong> </p>
<pre><code>fetch(serverUrl, {
method: "post",
body: blob
});
</code></pre>
<p>Where blob is of the type <code>Blob {size: 5040, type: "audio/wav;"}</code></p>
<p><strong>Python:</strong> </p>
<pre><code>@app.route('/messages', methods = ['POST'])
def api_message():
# Open file and write binary (blob) data
f = open('./file.wav', 'wb')
f.write(request.data)
f.close()
return "Binary message written!"
</code></pre>
<p>The file gets saved but only contains shitloads of <code>[object BlobEvent]</code>. What am I doing wrong and how can I fix it?</p>
<p><strong>Edit:</strong>
The audio samples are collected using <code>MediaRecorder()</code></p>
<pre><code>const mediaRecorder = new MediaRecorder(stream);
// Start
const chunks = [];
mediaRecorder.ondataavailable = e => {
chunks.push(e);
}
// On stop
blob = new Blob(chunks, {'type': 'audio/wav;'});
</code></pre>
<p>I tried playing the audio again on the client side and it works just fine:</p>
<pre><code>const audio = document.createElement('audio');
const audioURL = window.URL.createObjectURL(blob);
audio.src = audioURL;
</code></pre>
| 0 | 2016-10-05T13:43:56Z | 39,897,411 | <p>You are passing an array of event objects to the Blob constructor not the audio data.<br>
The data is <code>e.data</code>, so your code should be</p>
<pre><code>mediaRecorder.ondataavailable = e => {
chunks.push(e.data);
}
</code></pre>
| 2 | 2016-10-06T13:30:22Z | [
"javascript",
"python",
"audio",
"flask",
"blob"
]
|
Is there a built-in function in Tensorflow for shuffling or permutating tensors? | 39,875,674 | <p>What's the best way to permutate a tensor along both axis (first rows and then columns or vice versa)? Should I define a <code>py_func</code> and do it using numpy or use one of tensor transformation functions like <code>tf.slice</code> - I don't know if that's possible.</p>
<p>To achieve this using numpy, I usually do the following:</p>
<pre><code>>>> arr = np.arange(9).reshape([3,3])
>>> arr
array([[0, 1, 2],
[3, 4, 5],
[6, 7, 8]])
>>> col_perm = np.random.permutation(arr.shape[1])
>>> col_perm
array([2, 1, 0])
>>> row_perm = np.random.permutation(arr.shape[0])
>>> row_perm
array([2, 0, 1])
>>> shuffled_arr = arr[row_perm,:][:,col_perm]
>>> shuffled_arr
array([[8, 7, 6],
[2, 1, 0],
[5, 4, 3]])
</code></pre>
| 1 | 2016-10-05T13:44:17Z | 39,875,757 | <p>What about <a href="https://www.tensorflow.org/versions/r0.11/api_docs/python/constant_op.html#random_shuffle" rel="nofollow"><code>tf.random_shuffle()</code></a> combined with <a href="https://www.tensorflow.org/versions/r0.11/api_docs/python/array_ops.html#transpose" rel="nofollow">tensor transposition</a> (<code>tf.transpose()</code>)?</p>
| 0 | 2016-10-05T13:47:15Z | [
"python",
"numpy",
"tensorflow"
]
|
convert decimal to string python | 39,875,794 | <p>I imported tab delimited file to create a dataframe (<code>df</code>) which has the following <code>label</code>:</p>
<pre><code>label
1
2
3
1
</code></pre>
<p>This is stored as pandas.core.series.Series and I want to convert it to string format so that I can get rid of the decimals when I write this out to a text file.</p>
<pre><code>df.class_label=df.label.fillna('')
df.to_string(columns=['label'],index=False)
</code></pre>
<p>The variable type is still <code>Series</code>, and output (text file) also has the decimals:</p>
<pre><code>1.0 2.0 3.0 1.0
</code></pre>
<p>How to get rid of these decimals?</p>
| 1 | 2016-10-05T13:48:55Z | 39,875,899 | <p>You can use the <code>float_format</code> keyword argument of the <code>to_string()</code> method:</p>
<pre><code>df.to_string(columns=['label'], index=False, float_format=lambda x: '{:d}'.format(x))
</code></pre>
| 1 | 2016-10-05T13:53:11Z | [
"python",
"pandas",
"decimal",
"tostring"
]
|
convert decimal to string python | 39,875,794 | <p>I imported tab delimited file to create a dataframe (<code>df</code>) which has the following <code>label</code>:</p>
<pre><code>label
1
2
3
1
</code></pre>
<p>This is stored as pandas.core.series.Series and I want to convert it to string format so that I can get rid of the decimals when I write this out to a text file.</p>
<pre><code>df.class_label=df.label.fillna('')
df.to_string(columns=['label'],index=False)
</code></pre>
<p>The variable type is still <code>Series</code>, and output (text file) also has the decimals:</p>
<pre><code>1.0 2.0 3.0 1.0
</code></pre>
<p>How to get rid of these decimals?</p>
| 1 | 2016-10-05T13:48:55Z | 39,876,067 | <p>Using <code>astype(int)</code> will change a <code>float</code> to an <code>int</code> and will drop your <code>.0</code> as desired.</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'label': [1.0, 2.0, 4.0, 1.0]})
print(df)
label
0 1.0
1 2.0
2 4.0
3 1.0
df.label = df.label.astype(int)
print(df)
label
0 1
1 2
2 4
3 1
</code></pre>
<p>Here we do not need to convert this to a string. This will be done when exporting to <code>.csv</code> or <code>.txt</code> and will preserve the <code>int</code>.</p>
| 1 | 2016-10-05T14:00:35Z | [
"python",
"pandas",
"decimal",
"tostring"
]
|
convert decimal to string python | 39,875,794 | <p>I imported tab delimited file to create a dataframe (<code>df</code>) which has the following <code>label</code>:</p>
<pre><code>label
1
2
3
1
</code></pre>
<p>This is stored as pandas.core.series.Series and I want to convert it to string format so that I can get rid of the decimals when I write this out to a text file.</p>
<pre><code>df.class_label=df.label.fillna('')
df.to_string(columns=['label'],index=False)
</code></pre>
<p>The variable type is still <code>Series</code>, and output (text file) also has the decimals:</p>
<pre><code>1.0 2.0 3.0 1.0
</code></pre>
<p>How to get rid of these decimals?</p>
| 1 | 2016-10-05T13:48:55Z | 39,876,132 | <p>I think you have some <code>NaN</code> values, so <code>int</code> are converted to <code>float</code> because <a href="http://pandas.pydata.org/pandas-docs/stable/gotchas.html#na-type-promotions" rel="nofollow">na type promotions</a>.</p>
<p>So you can read data in column <code>label</code> as <code>str</code> and then it works nice:</p>
<pre><code>import pandas as pd
import numpy as np
import io
temp=u"""lab1;label
5;1
5;2
7;
7;3
"""
#after testing replace io.StringIO(temp) to filename
df = pd.read_csv(io.StringIO(temp), sep=';', dtype={'label':str})
print (df)
lab1 label
0 5 1
1 5 2
2 7 NaN
3 7 3
df['class_label'] = df.label.fillna('')
print (df)
lab1 label class_label
0 5 1 1
1 5 2 2
2 7 NaN
3 7 3 3
print (df.to_string(columns=['class_label'],index=False))
class_label
1
2
3
</code></pre>
| 1 | 2016-10-05T14:04:11Z | [
"python",
"pandas",
"decimal",
"tostring"
]
|
Django 1.10 Using a dropdown menu to filter queries | 39,875,830 | <p>I have a database with a bunch of pictures and the countries they were taken in. This is for a photo album on this site I'm making. Currently, I have all the pictures on one page. I like this. I want to now be able to search for all the pictures from a certain country, or city. My design calls for two buttons on top (filter by country, filter by city), and all the pictures from the database displayed below when no filter is used. I want these buttons to be a dropdown list of all the countries and cities respectively. When a user clicks on the countries button a dropdown is called - using bootstrap. They can then click on the country of choice and see all the pictures that are there, ordered by city. If they click on the dropdown for cities, then all the pictures from that city are called. If they select countries, then the cities dropdown only displays the cities in that country. Right now, I have no clue how to do this. I can populate the dropdowns - but I get all the photo's countries - meaning repeats. How can I do this?</p>
<p>Here is my views.py:</p>
<pre><code>def photo_album(request):
queryset_list = Pictures.objects.all()
query = request.GET.get("q")
if query:
queryset_list = queryset_list.filter(
Q(pictures__icontains=query) |
Q(picture_name__icontains=query) |
Q(country__icontains=query) |
Q(city__icontains=query)
).distinct()
paginator = Paginator(queryset_list, 20)
page_request_var = "page"
page = request.GET.get(page_request_var)
try:
queryset = paginator.page(page)
except PageNotAnInteger:
# If page is not an integer, deliver first page.
queryset = paginator.page(1)
except EmptyPage:
# If page is out of range (e.g. 9999), deliver last page of results.
queryset = paginator.page(paginator.num_pages)
context = {
"object_list": queryset,
"title": "List",
"page_request_var": page_request_var,
}
return render(request, "in_country_pics/photo_album.html", context)
</code></pre>
<p>my html:</p>
<pre><code><div class="container">
<div class="photo-title">
<h1>Welcome to Our Photo Album</h1>
</div>
<div class="col-sm-12 photoalbum-buttons">
<form method="GET" action="" class="row">
<div class="col-sm-6">
<div class="input-group">
<input class="form-control" type="text" name="q" placeholder="Search Posts" value="{{ request.GET.q }}"/>
<span class="input-group-btn">
<button class="btn btn-default" type="submit">Search <i class="fa fa-search"></i></button>
</span>
</div>
</div>
</form>
<div class="dropdown form-actions">
<button class="btn btn-primary gradient dropdown-toggle" type="button" data-toggle="dropdown">
<i class="fa fa-search"></i>
By Country
</button>
<ul class="dropdown-menu">
{% for obj in object_list %}
<li ><a href="#">{{ obj.country }}</a></li>
{% endfor %}
</ul>
</div>
<div class="dropdown form-actions">
<button class="btn btn-primary gradient dropdown-toggle" type="button" data-toggle="dropdown">
<i class="fa fa-search"></i>
By City
</button>
<ul class="dropdown-menu">
{% for obj in object_list %}
<li><a href="#">{{ obj.city }}</a></li>
{% endfor %}
</ul>
</div>
</div>
<p id="photo-separator">______________________________________________</p>
<div class="row photo-post">
{% for obj in object_list %}
<div class="col-sm-3">
<div class="thumbnail">
<img src="{{ obj.pictures.url }}" class="img-responsive"/>
<div class="caption photo-description">
<p class="photo-location">{{obj.city}}, {{obj.country}}</p>
<p class="photo-time">Taken: Aug 04, 2016</p>
<p><a href="" class="btn btn-primary" type="button">View</a></p>
</div>
</div>
</div>
{% if forloop.counter|divisibleby:4 %}
<div class='col-sm-12'><hr/></div></div><div></div><div class='row'>
{% endif %}
{% endfor %}
</div>
</div>
{% endblock %}
</code></pre>
<p>In the html, I have the first search bar working, but as a text. I have the below simple bootstrap dropdowns. If using ajax or jquery is best, I'm open to that.</p>
| 0 | 2016-10-05T13:50:39Z | 39,876,366 | <p>You'll need Ajax to do that.</p>
<p>Follow <a href="https://realpython.com/blog/python/django-and-ajax-form-submissions/" rel="nofollow">this</a> tutorial to help you.</p>
<p>you need to download a <a href="https://raw.githubusercontent.com/realpython/django-form-fun/master/part1/main.js" rel="nofollow">script</a> (it is in the tutorial) to help you with the <em>csrf_token</em>, otherwise, when you submit the form you'll get a django error related with this token.</p>
<p>when calling to the Ajax url like this </p>
<pre><code>$.ajax({
url: "some path/", // endpoint
</code></pre>
<p>you'll hvae to create that url in your <em>urls.py</em> file:</p>
<pre><code>urlpatterns = [
url(r'^path/$', views.your_view_name),
]
</code></pre>
<p>this way you can call the view (or just a function in this case) send the info you need to your template.</p>
<p>Later, with jquery you can change the html of the element with its id something like this</p>
<pre><code>$('#your_element_id').html("<p>your updated code goes here</p>");
</code></pre>
<p>you can also append elementets, just change the <em>.html</em> with <em>.append</em>.
The difference is that .html replace what you have with the code you give, and .apend only adds that code with what you have there.</p>
| 1 | 2016-10-05T14:14:07Z | [
"jquery",
"python",
"django",
"django-models",
"django-templates"
]
|
Sorting object attributes in different orders | 39,875,855 | <p>I'm writing a soccer league program and I want to sort the table before printing it out. Each team is a member of a class with certain attributes and so far I've been able to sort the integer attributes correctly.</p>
<pre><code>for team in sorted(teams, key=attrgetter("points", "goalDiff", "scored", "name"), reverse = True):
</code></pre>
<p>I want all the attributes except <code>name</code> to be reversed, is there a possible way to "un-reverse" the <code>name</code> attribute in this line of code or do I have to take on a different approach?</p>
| 0 | 2016-10-05T13:51:27Z | 39,875,911 | <p>If all attributes (except the name) are numeric, negate those numbers to get a reverse sort for those:</p>
<pre><code>sorted(teams, key=lambda t: (-t.points, -t.goalDiff, -t.scored, t.name))
</code></pre>
<p>Negating numbers gives you a way to reverse their sort order without actually having to reverse the sort.</p>
<p>If that's not the case, then you'd have to sort twice, first just by the <code>name</code> attribute (in forward order), then in reverse order by the other attributes. For any object where <code>points</code>, <code>goalDiff</code> and <code>scored</code> are equal, the original sorting order (by name) is retained, because the sort algorithm Python uses is stable:</p>
<pre><code>sorted(
sorted(teams, key=attrgetter('name')),
key=attrgetter("points", "goalDiff", "scored"),
reverse=True)
</code></pre>
| 6 | 2016-10-05T13:53:58Z | [
"python",
"python-3.x",
"sorting"
]
|
Python: PySerial disconnecting from device randomly | 39,875,897 | <p>I have a process that runs data acquisition using PySerial. It's working fine now, but there's a weird thing I had to do to make it work continuously, and I'm not sure this is normal, so I'm asking this question.</p>
<p><strong>What happens:</strong> It looks like that the connection drops now and then! Around once every 30-60 minutes, with big error bars (could go for hours and be OK, but sometimes happens often).</p>
<p><strong>My question</strong>: Is this standard?</p>
<p><strong>My temporary solution</strong>: I wrote a simple "reopen" function that looks like this:</p>
<pre><code>def ReopenDevice(devObject):
try:
devObject.close()
devObject.open()
except Exception as e:
print("Error while trying to connect to device " + devObject.port + ". The error says: " + str(e))
time.sleep(2)
</code></pre>
<p>And what I do is that if data pulling fails for 2 minutes, I reopen the device with this function, and it continues working well with no problems.</p>
<p><strong>My program model</strong>: It's a GUI program, where the user clicks something like "Start", and that button does some preparations and runs a function through <code>multiprocessing.Process()</code> that starts with:</p>
<pre><code>devObj = serial.Serial()
#... other params
devObj.open()
</code></pre>
<p>and that function then runs a while loop that keeps polling data with something like:</p>
<pre><code>bytesToRead = devObj.inWaiting()
if bytesToRead != 0:
buffer = decodeString(devObj.read(bytesToRead))
#process buffer and push it to a list...
</code></pre>
<p>The way I know that the problem happened, is that <code>devObj.inWaiting()</code> Keeps returning zero... no matter how much data there's on the device!</p>
<p>Is this behavior expected and should always be considered whether it happens or doesn't happen?</p>
| 0 | 2016-10-05T13:53:01Z | 40,110,426 | <p>The problem reduced a lot after not calling <code>inWaiting()</code> very frequently. Anyway, I kept the reconnect part to ensure that my program never fails. Thanks for "Kobi K" for suggesting the possible cause of the problem.</p>
| 0 | 2016-10-18T14:05:01Z | [
"python",
"pyserial",
"stability"
]
|
Phone menu - Python 3 | 39,876,060 | <p>I'm trying to make some project of phone Menu, with viewing, adding and removing contacts. Which way would be better, to add contact to dictionary or by making new file and write/read from it?</p>
<p>I tried first method - I had added new contact to empty dictionary and then I tried to view it by using viewing option but still dictionary is empty.</p>
<p>That's a first sample of my "project":</p>
<pre><code>condition = True
while condition == True:
print("Menu")
print("contacts")
print("Add contacts")
print("Remove contacts")
phone_contacts = {}
def contacts(x):
for item in dict(x):
print(item, x[item])
def add_contacts(x):
new_key = input("Enter a name\n")
new_value = input("Enter a number\n")
x[new_key] = new_value
print(phone_contacts)
def remove_contacts(x):
for item in dict(x):
print(item)
removing_contact = input("Enter a contact to remove\n")
if removing_contact in x:
del x[removing_contact]
print("Contact has been deleted!")
else:
print("There is no '%s\' contact!") % (removing_contact)
choose = input("Select option")
if choose == "1":
print(contacts(phone_contacts))
choose_2 = input("End/Back to MENU").lower()
if choose_2 == "end":
break
elif choose_2 == "menu":
pass
elif choose == "2":
print(add_contacts(phone_contacts))
choose_2 = input("End/Back to MENU").lower()
if choose_2 == "end":
break
elif choose_2 == "menu":
pass
elif choose == "3":
print(remove_contacts(phone_contacts))
choose_2 = input("End/Back to MENU").lower()
if choose_2 == "end":
break
elif choose_2 == "menu":
pass
else:
print("You didn't type anything!")
choose_2 = input("End/Back to MENU").lower()
if choose_2 == "end":
break
elif choose_2 == "menu":
pass
</code></pre>
<p>So this way doesn't work, I tried also write into a text.txt file </p>
<pre><code>condition = True
while condition == True:
print("Menu")
print("contacts")
print("Add contacts")
print("Remove contacts")
phone_contacts = {}
def contacts(x):
for item in dict(x):
print(item, x[item])
def add_contacts(x):
new_key = input("Enter a name\n")
new_value = input("Enter a number\n")
text = "%s - %d" % (new_key, int(new_value))
savefile = open("text.txt", "w")
savefile.write(text)
savefile.read(text)
savefile.close()
def remove_contacts(x):
for item in dict(x):
print(item)
removing_contact = input("Enter a contact to remove\n")
if removing_contact in x:
del x[removing_contact]
print("Contact has been deleted!")
else:
print("There is no '%s\' contact!") % (removing_contact)
choose = input("Select option")
if choose == "1":
print(contacts(phone_contacts))
choose_2 = input("End/Back to MENU").lower()
if choose_2 == "end":
break
elif choose_2 == "menu":
pass
elif choose == "2":
print(add_contacts(phone_contacts))
choose_2 = input("End/Back to MENU").lower()
if choose_2 == "end":
break
elif choose_2 == "menu":
pass
elif choose == "3":
print(remove_contacts(phone_contacts))
choose_2 = input("End/Back to MENU").lower()
if choose_2 == "end":
break
elif choose_2 == "menu":
pass
else:
print("You didn't type anything!")
choose_2 = input("End/Back to MENU").lower()
if choose_2 == "end":
break
elif choose_2 == "menu":
pass
</code></pre>
<p>It doesn't work neither. </p>
<p>What am I doing wrong in both cases? Which way should I choose, first or the second one? </p>
<p>BTW I would be grateful for any tips how I could correct my code, even if those tips doesn't pertains to the problem. </p>
| 1 | 2016-10-05T14:00:13Z | 39,876,413 | <p>In both options you are overwriting the dictionary on every iteration. You should initilize it only once outside the loop. For the first option it will look like:</p>
<pre><code>phone_contacts = {} # this line moved from inside the loop
while condition == True:
print("Menu")
print("contacts")
print("Add contacts")
print("Remove contacts")
# the line deleted from here
# ...
</code></pre>
| 0 | 2016-10-05T14:16:10Z | [
"python",
"python-3.x",
"dictionary"
]
|
Phone menu - Python 3 | 39,876,060 | <p>I'm trying to make some project of phone Menu, with viewing, adding and removing contacts. Which way would be better, to add contact to dictionary or by making new file and write/read from it?</p>
<p>I tried first method - I had added new contact to empty dictionary and then I tried to view it by using viewing option but still dictionary is empty.</p>
<p>That's a first sample of my "project":</p>
<pre><code>condition = True
while condition == True:
print("Menu")
print("contacts")
print("Add contacts")
print("Remove contacts")
phone_contacts = {}
def contacts(x):
for item in dict(x):
print(item, x[item])
def add_contacts(x):
new_key = input("Enter a name\n")
new_value = input("Enter a number\n")
x[new_key] = new_value
print(phone_contacts)
def remove_contacts(x):
for item in dict(x):
print(item)
removing_contact = input("Enter a contact to remove\n")
if removing_contact in x:
del x[removing_contact]
print("Contact has been deleted!")
else:
print("There is no '%s\' contact!") % (removing_contact)
choose = input("Select option")
if choose == "1":
print(contacts(phone_contacts))
choose_2 = input("End/Back to MENU").lower()
if choose_2 == "end":
break
elif choose_2 == "menu":
pass
elif choose == "2":
print(add_contacts(phone_contacts))
choose_2 = input("End/Back to MENU").lower()
if choose_2 == "end":
break
elif choose_2 == "menu":
pass
elif choose == "3":
print(remove_contacts(phone_contacts))
choose_2 = input("End/Back to MENU").lower()
if choose_2 == "end":
break
elif choose_2 == "menu":
pass
else:
print("You didn't type anything!")
choose_2 = input("End/Back to MENU").lower()
if choose_2 == "end":
break
elif choose_2 == "menu":
pass
</code></pre>
<p>So this way doesn't work, I tried also write into a text.txt file </p>
<pre><code>condition = True
while condition == True:
print("Menu")
print("contacts")
print("Add contacts")
print("Remove contacts")
phone_contacts = {}
def contacts(x):
for item in dict(x):
print(item, x[item])
def add_contacts(x):
new_key = input("Enter a name\n")
new_value = input("Enter a number\n")
text = "%s - %d" % (new_key, int(new_value))
savefile = open("text.txt", "w")
savefile.write(text)
savefile.read(text)
savefile.close()
def remove_contacts(x):
for item in dict(x):
print(item)
removing_contact = input("Enter a contact to remove\n")
if removing_contact in x:
del x[removing_contact]
print("Contact has been deleted!")
else:
print("There is no '%s\' contact!") % (removing_contact)
choose = input("Select option")
if choose == "1":
print(contacts(phone_contacts))
choose_2 = input("End/Back to MENU").lower()
if choose_2 == "end":
break
elif choose_2 == "menu":
pass
elif choose == "2":
print(add_contacts(phone_contacts))
choose_2 = input("End/Back to MENU").lower()
if choose_2 == "end":
break
elif choose_2 == "menu":
pass
elif choose == "3":
print(remove_contacts(phone_contacts))
choose_2 = input("End/Back to MENU").lower()
if choose_2 == "end":
break
elif choose_2 == "menu":
pass
else:
print("You didn't type anything!")
choose_2 = input("End/Back to MENU").lower()
if choose_2 == "end":
break
elif choose_2 == "menu":
pass
</code></pre>
<p>It doesn't work neither. </p>
<p>What am I doing wrong in both cases? Which way should I choose, first or the second one? </p>
<p>BTW I would be grateful for any tips how I could correct my code, even if those tips doesn't pertains to the problem. </p>
| 1 | 2016-10-05T14:00:13Z | 39,876,663 | <p>You should define all functions before and outside the main while(True). You should turn the ifs block into a function that receives the input.
You should make it explicit which key is which option.</p>
<pre><code>list1=['a','b','c']
def operateList(number):
if number == '3':
try: list1.remove(input('Type what you want to remove:'))
except: print('not in List')
elif number == '2':
list1.append(input('Type in what you want to add:'))
list1.sort()
elif number == '1':
print(list1)
while(True):
print('1: List')
print('2: Add')
print('3: Remove')
operateList(input('Input option number:'))
</code></pre>
| 0 | 2016-10-05T14:26:07Z | [
"python",
"python-3.x",
"dictionary"
]
|
Phone menu - Python 3 | 39,876,060 | <p>I'm trying to make some project of phone Menu, with viewing, adding and removing contacts. Which way would be better, to add contact to dictionary or by making new file and write/read from it?</p>
<p>I tried first method - I had added new contact to empty dictionary and then I tried to view it by using viewing option but still dictionary is empty.</p>
<p>That's a first sample of my "project":</p>
<pre><code>condition = True
while condition == True:
print("Menu")
print("contacts")
print("Add contacts")
print("Remove contacts")
phone_contacts = {}
def contacts(x):
for item in dict(x):
print(item, x[item])
def add_contacts(x):
new_key = input("Enter a name\n")
new_value = input("Enter a number\n")
x[new_key] = new_value
print(phone_contacts)
def remove_contacts(x):
for item in dict(x):
print(item)
removing_contact = input("Enter a contact to remove\n")
if removing_contact in x:
del x[removing_contact]
print("Contact has been deleted!")
else:
print("There is no '%s\' contact!") % (removing_contact)
choose = input("Select option")
if choose == "1":
print(contacts(phone_contacts))
choose_2 = input("End/Back to MENU").lower()
if choose_2 == "end":
break
elif choose_2 == "menu":
pass
elif choose == "2":
print(add_contacts(phone_contacts))
choose_2 = input("End/Back to MENU").lower()
if choose_2 == "end":
break
elif choose_2 == "menu":
pass
elif choose == "3":
print(remove_contacts(phone_contacts))
choose_2 = input("End/Back to MENU").lower()
if choose_2 == "end":
break
elif choose_2 == "menu":
pass
else:
print("You didn't type anything!")
choose_2 = input("End/Back to MENU").lower()
if choose_2 == "end":
break
elif choose_2 == "menu":
pass
</code></pre>
<p>So this way doesn't work, I tried also write into a text.txt file </p>
<pre><code>condition = True
while condition == True:
print("Menu")
print("contacts")
print("Add contacts")
print("Remove contacts")
phone_contacts = {}
def contacts(x):
for item in dict(x):
print(item, x[item])
def add_contacts(x):
new_key = input("Enter a name\n")
new_value = input("Enter a number\n")
text = "%s - %d" % (new_key, int(new_value))
savefile = open("text.txt", "w")
savefile.write(text)
savefile.read(text)
savefile.close()
def remove_contacts(x):
for item in dict(x):
print(item)
removing_contact = input("Enter a contact to remove\n")
if removing_contact in x:
del x[removing_contact]
print("Contact has been deleted!")
else:
print("There is no '%s\' contact!") % (removing_contact)
choose = input("Select option")
if choose == "1":
print(contacts(phone_contacts))
choose_2 = input("End/Back to MENU").lower()
if choose_2 == "end":
break
elif choose_2 == "menu":
pass
elif choose == "2":
print(add_contacts(phone_contacts))
choose_2 = input("End/Back to MENU").lower()
if choose_2 == "end":
break
elif choose_2 == "menu":
pass
elif choose == "3":
print(remove_contacts(phone_contacts))
choose_2 = input("End/Back to MENU").lower()
if choose_2 == "end":
break
elif choose_2 == "menu":
pass
else:
print("You didn't type anything!")
choose_2 = input("End/Back to MENU").lower()
if choose_2 == "end":
break
elif choose_2 == "menu":
pass
</code></pre>
<p>It doesn't work neither. </p>
<p>What am I doing wrong in both cases? Which way should I choose, first or the second one? </p>
<p>BTW I would be grateful for any tips how I could correct my code, even if those tips doesn't pertains to the problem. </p>
| 1 | 2016-10-05T14:00:13Z | 39,880,951 | <p>First thing, you have to declare phone_contacts and the functions outside of the loop.</p>
<p>Second there are redundancies in the conditions.</p>
<p>The idea of creating a file to store contacts is great. I would save it as a <code>.json</code> file as it is very simple to handle.</p>
<p>Here is the code, which I have refactored as well as I could.</p>
<pre><code>import json
phone_contacts = {}
def print_contacts():
if not phone_contacts:
print("Empty list.")
return
for name, number in sorted(phone_contacts.items()):
print(name, number) # explicit is better than implicit
def add_contact():
name = input("Enter a name\n")
number = input("Enter a number\n")
if name and number:
phone_contacts[name] = number
print("Contact added: {0}, {1}".format(name, number))
def remove_contacts():
print_contacts()
removing_contact = input("Enter a contact to remove\n")
if removing_contact in phone_contacts:
del phone_contacts[removing_contact]
print("Contact has been deleted!")
else:
print("There is no '%s' contact!") % (removing_contact)
def load_contacts():
global phone_contacts
try:
with open('contacts.json', 'r') as file:
phone_contacts = json.load(file)
except (ValueError, OSError): # OSError catches FileNotFoundError
phone_contacts = {}
def save_contacts():
with open('contacts.json', 'w+') as file:
json.dump(phone_contacts, file)
load_contacts()
while True:
print("0. Exit")
print("1. Menu")
print("2. Add contact")
print("3. Remove contacts")
choose = input("Select option: ")
if choose == "0":
print("Exiting program...")
break
elif choose == "1":
print_contacts()
elif choose == "2":
add_contact()
elif choose == "3":
remove_contacts()
else:
print("You didn't type a valid option!")
# moved this block out as it's common to all options
choose_2 = input("End/Back to MENU\n").lower()
if choose_2 == "end":
break
# even if user typed anything different of menu
# he/she would continue in the loop so that else was needless
save_contacts()
</code></pre>
<p>Also note that you don't need to pass phone_contacts as an argument since it's global.</p>
<p>I've added load and save contacts functions that is pretty understandable, even if you have no experience with JSON.</p>
<p>There's a lot of things to ask there so if you have some doubt and want to ask me, feel comfortable! ;)</p>
| 0 | 2016-10-05T18:09:51Z | [
"python",
"python-3.x",
"dictionary"
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.