title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
Python - Intensity map without interpolation
39,894,926
<p>I need to make an intensity plot.</p> <p>I have three lists of x,y,z values, imported from real data: <code>x_list, y_list, z_list</code>. Each of these lists contain 200 values. Therefore there is a corresponding value of z for each x,y couple.</p> <p>I have tried the following, after some search on the web and another question on StackOverflow:</p> <pre><code>import numpy as np import pylab as plt data = np.loadtxt('data.d') x_list = data[:,0] y_list = data[:,1] z_list = data[:,2] from scipy.interpolate import interp2d f = interp2d(x_list,y_list,z_list,kind="linear") x_coords = np.arange(min(x_list),max(x_list)+1) y_coords = np.arange(min(y_list),max(y_list)+1) Z = f(x_coords,y_coords) fig = plt.imshow(Z, extent=[min(x_list),max(x_list),min(y_list),max(y_list)], origin="lower") fig.axes.set_autoscale_on(False) plt.scatter(x_list,y_list,400,facecolors='none') plt.show() </code></pre> <p>This uses interpolation, and I am not sure that it is exactly what I need. Is there a way to plot ONLY the 200 values of z, corresponding to the 200 x,y couples, for which I have a given value, withuot interpolation? Obviously I still need some kind of "intensity relation", I cannot just have a scatter plot without a way of interpreting the "intensity" of the 200 z values.</p>
0
2016-10-06T11:34:47Z
39,895,429
<p>From what I understand, you want to display xyz points in a 2D graph where z-value would be represented by a color. If that is correct the solution is as simple as stating <code>facecolors=z_list</code> in your scatter plot:</p> <pre><code>data = np.random.rand(200,3) x_list = data[:,0] y_list = data[:,1] z_list = data[:,2] plt.scatter(x_list,y_list,200,facecolors=z_list) plt.colorbar() plt.show() </code></pre> <p>Example output : <a href="http://i.stack.imgur.com/nQahF.png" rel="nofollow"><img src="http://i.stack.imgur.com/nQahF.png" alt="enter image description here"></a></p>
2
2016-10-06T12:00:50Z
[ "python", "matplotlib" ]
Generate html document with images and text within python script (without servers if possible)
39,894,970
<p>How can I generate HTML containing images and text, using a template and css, in python?</p> <p>There are few similar questions on stackoverflow (e.g.: <a href="http://stackoverflow.com/questions/6748559/generating-html-documents-in-python">Q1</a>, <a href="http://stackoverflow.com/questions/98135/how-do-i-use-django-templates-without-the-rest-of-django">Q2</a>, <a href="http://stackoverflow.com/questions/16523939/how-to-write-and-save-html-file-in-python">Q3</a>) but they offer solutions that (to me) seem overkill, like requiring servers (e.g. genshi).</p> <p>Simple code using <code>django</code> would be as follows:</p> <pre><code>from django.template import Template, Context from django.conf import settings settings.configure() # We have to do this to use django templates standalone - see # http://stackoverflow.com/questions/98135/how-do-i-use-django-templates-without-the-rest-of-django # Our template. Could just as easily be stored in a separate file template = """ &lt;html&gt; &lt;head&gt; &lt;title&gt;Template {{ title }}&lt;/title&gt; &lt;/head&gt; &lt;body&gt; Body with {{ mystring }}. &lt;/body&gt; &lt;/html&gt; """ t = Template(template) c = Context({"title": "title from code", "mystring":"string from code"}) print t.render(c) </code></pre> <p>(From here: <a href="http://stackoverflow.com/questions/6748559/generating-html-documents-in-python">Generating HTML documents in python</a>)</p> <p>This code produces an error, supposedly because I need to set up a backend:</p> <pre><code>Traceback (most recent call last): File "&lt;input&gt;", line 17, in &lt;module&gt; File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/template/base.py", line 184, in __init__ engine = Engine.get_default() File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/template/engine.py", line 81, in get_default "No DjangoTemplates backend is configured.") django.core.exceptions.ImproperlyConfigured: No DjangoTemplates backend is configured. </code></pre> <p>Is there a simple way to have a template.html and style.css and a bunch of images, and use data in a python script to replace placeholders in the template.html without having to set up a server?</p>
0
2016-10-06T11:37:05Z
39,895,138
<p>I use code like this:</p> <pre><code>self.content = ''' &lt;html&gt; &lt;head&gt; ''' + base_pyhtml.getAdmin ('documentation') + ''' &lt;style&gt; ''' + base_pycss.getAll () + ''' ''' + documentation_pycss.getAll () + ''' &lt;/style&gt; &lt;/head&gt; &lt;body&gt; ''' + base_pyhtml.getFixed () + ''' &lt;div class="moving"&gt; &lt;div class="documentation"&gt; </code></pre> <p>and</p> <pre><code>def getAll (): return ''' * { margin: 0; padding: 0; } body { font-family: arial; } html { visibility: hidden; } h1 { margin-bottom: 30; padding: 10 1 10 1; text-align: center; color: ''' + logoGreen + '''; background-color: ''' + panoramaPink + '''; font-size: 110%; </code></pre> <p>For me it works fine in practice. This <a href="http://www.transcrypt.org" rel="nofollow">site</a> was completely made with this trivial technique. What I like is that I can use the full power of Python in this way, rather than being restricted by or even learning special template syntax.</p> <p>By using .pyhtml and .pycss extensions and configuring my editor, I get HTML and CSS syntax highlighting on this type of code as shown below:</p> <p><a href="http://i.stack.imgur.com/jdzDn.png" rel="nofollow"><img src="http://i.stack.imgur.com/jdzDn.png" alt="enter image description here"></a></p>
0
2016-10-06T11:45:32Z
[ "python", "html", "css", "django" ]
Generate html document with images and text within python script (without servers if possible)
39,894,970
<p>How can I generate HTML containing images and text, using a template and css, in python?</p> <p>There are few similar questions on stackoverflow (e.g.: <a href="http://stackoverflow.com/questions/6748559/generating-html-documents-in-python">Q1</a>, <a href="http://stackoverflow.com/questions/98135/how-do-i-use-django-templates-without-the-rest-of-django">Q2</a>, <a href="http://stackoverflow.com/questions/16523939/how-to-write-and-save-html-file-in-python">Q3</a>) but they offer solutions that (to me) seem overkill, like requiring servers (e.g. genshi).</p> <p>Simple code using <code>django</code> would be as follows:</p> <pre><code>from django.template import Template, Context from django.conf import settings settings.configure() # We have to do this to use django templates standalone - see # http://stackoverflow.com/questions/98135/how-do-i-use-django-templates-without-the-rest-of-django # Our template. Could just as easily be stored in a separate file template = """ &lt;html&gt; &lt;head&gt; &lt;title&gt;Template {{ title }}&lt;/title&gt; &lt;/head&gt; &lt;body&gt; Body with {{ mystring }}. &lt;/body&gt; &lt;/html&gt; """ t = Template(template) c = Context({"title": "title from code", "mystring":"string from code"}) print t.render(c) </code></pre> <p>(From here: <a href="http://stackoverflow.com/questions/6748559/generating-html-documents-in-python">Generating HTML documents in python</a>)</p> <p>This code produces an error, supposedly because I need to set up a backend:</p> <pre><code>Traceback (most recent call last): File "&lt;input&gt;", line 17, in &lt;module&gt; File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/template/base.py", line 184, in __init__ engine = Engine.get_default() File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/template/engine.py", line 81, in get_default "No DjangoTemplates backend is configured.") django.core.exceptions.ImproperlyConfigured: No DjangoTemplates backend is configured. </code></pre> <p>Is there a simple way to have a template.html and style.css and a bunch of images, and use data in a python script to replace placeholders in the template.html without having to set up a server?</p>
0
2016-10-06T11:37:05Z
39,895,310
<p>There are quite a few python template engines - for a start you may want to have a look here : <a href="https://wiki.python.org/moin/Templating" rel="nofollow">https://wiki.python.org/moin/Templating</a></p> <p>As far as I'm concerned I'd use jinja2 but YMMV.</p>
1
2016-10-06T11:54:00Z
[ "python", "html", "css", "django" ]
Generate html document with images and text within python script (without servers if possible)
39,894,970
<p>How can I generate HTML containing images and text, using a template and css, in python?</p> <p>There are few similar questions on stackoverflow (e.g.: <a href="http://stackoverflow.com/questions/6748559/generating-html-documents-in-python">Q1</a>, <a href="http://stackoverflow.com/questions/98135/how-do-i-use-django-templates-without-the-rest-of-django">Q2</a>, <a href="http://stackoverflow.com/questions/16523939/how-to-write-and-save-html-file-in-python">Q3</a>) but they offer solutions that (to me) seem overkill, like requiring servers (e.g. genshi).</p> <p>Simple code using <code>django</code> would be as follows:</p> <pre><code>from django.template import Template, Context from django.conf import settings settings.configure() # We have to do this to use django templates standalone - see # http://stackoverflow.com/questions/98135/how-do-i-use-django-templates-without-the-rest-of-django # Our template. Could just as easily be stored in a separate file template = """ &lt;html&gt; &lt;head&gt; &lt;title&gt;Template {{ title }}&lt;/title&gt; &lt;/head&gt; &lt;body&gt; Body with {{ mystring }}. &lt;/body&gt; &lt;/html&gt; """ t = Template(template) c = Context({"title": "title from code", "mystring":"string from code"}) print t.render(c) </code></pre> <p>(From here: <a href="http://stackoverflow.com/questions/6748559/generating-html-documents-in-python">Generating HTML documents in python</a>)</p> <p>This code produces an error, supposedly because I need to set up a backend:</p> <pre><code>Traceback (most recent call last): File "&lt;input&gt;", line 17, in &lt;module&gt; File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/template/base.py", line 184, in __init__ engine = Engine.get_default() File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/template/engine.py", line 81, in get_default "No DjangoTemplates backend is configured.") django.core.exceptions.ImproperlyConfigured: No DjangoTemplates backend is configured. </code></pre> <p>Is there a simple way to have a template.html and style.css and a bunch of images, and use data in a python script to replace placeholders in the template.html without having to set up a server?</p>
0
2016-10-06T11:37:05Z
39,932,850
<p>Thanks for your answers, they helped me coming up with something that works for me.</p> <p>I am using <code>jinja2</code> to render and html file ('index.html') that I have made separately. </p> <pre><code>from jinja2 import Template, Environment, FileSystemLoader # Render html file env = Environment(loader=FileSystemLoader('templates')) template = env.get_template('index.html') output_from_parsed_template = template.render(no_users=len(users), do_stages=do_stages, users=users, message_counts=message_counts) # to save the results with open("OutputAnalysis.html", "w") as fh: fh.write(output_from_parsed_template) </code></pre> <p>The html template is:</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;!-- &lt;link rel="stylesheet" type="text/css" href="styles.css"&gt; --&gt; &lt;style type="text/css"&gt; #share-buttons img { width: 32px; padding: 5px; border: 0; box-shadow: 0; display: inline; } body { padding-left: 5px; padding-right: 5px; color: black; max-width: 450px; text-align: center; } &lt;/style&gt; &lt;title&gt;Your file 2016&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;h1&gt;This has {{ no_users }} users:&lt;/h1&gt; &lt;ul id="users"&gt; {% for user in users %} &lt;li&gt;{{user}}&lt;/li&gt; {% endfor %} &lt;/ul&gt; {# STAGE 1 #} {% if 1 in do_stages%} &lt;h1&gt;Something worth showing&lt;/h1&gt; &lt;p&gt; &lt;img src="image.png" alt="caption" style="width:200px;height:200px;"&gt; &lt;/p&gt; {% endif %} {# STAGE 2 #} {% if 2 in do_stages%} &lt;h1&gt;Other header&lt;/h1&gt; &lt;p&gt; {% for u in range(0,no_users) %} &lt;p&gt;{{users[u]}} sent {{message_counts[u]}} messages.&lt;/p&gt; {% endfor %} &lt;/p&gt; &lt;p&gt; {% endif %} &lt;div id="share-buttons"&gt; &lt;!-- Twitter --&gt; &lt;a href="https://twitter.com/share?url=https://stefanocosentino.com" target="_blank"&gt; &lt;img src="twitter_icon.png" alt="Twitter" /&gt; &lt;/a&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Note that the html file has the style defined in the heather and loads from the local folder "template".</p>
-1
2016-10-08T13:19:29Z
[ "python", "html", "css", "django" ]
How to choose object from list and print its name
39,895,170
<p>I have class Something with few objects:</p> <pre><code>class Something(): def __init__(self, name, attr1, attr2): self.name= name self.attr1= attr1 self.attr2= attr2 def getName(self): return self.name Obj1=Something('Name1', 'bla bla1', 'bla bla2') Obj2=Something('Name2', 'bla bla3', 'bla bla4') </code></pre> <p>Those objects are stored in list:</p> <pre><code>objects = [Obj1, Obj2] </code></pre> <p>I want to select object from the printed list and then (if object is on the list) print its name. So far I wrote code below, but it doesn't work. with error (AttributeError: 'str' object has no attribute 'getNazwa')</p> <pre><code>print('Select object from list: ', objects) y=raw_input('enter the name of the object') for i in objects: if y == i: print "Name: " + i.getName() </code></pre> <p>When print list it's someting like that:</p> <pre><code>('Select object fromfrom list: ', [&lt;__main__.Something instance at 0x024FB440&gt;, &lt;__main__.Something instance at 0x024FB490&gt;]) </code></pre> <p>How to convert it into print objects name?</p> <p>I guess that solution isn't rocket science for You Guys, so someone will help me ;)</p>
0
2016-10-06T11:46:43Z
39,895,279
<p>Thing is that you compare string to an object here:</p> <pre><code>if y == i: </code></pre> <p>so you should either look at <code>__eq__</code> method of your class, or compare input string with obj name like:</p> <pre><code>if y == i.getName() </code></pre>
0
2016-10-06T11:52:25Z
[ "python", "class", "object" ]
How to choose object from list and print its name
39,895,170
<p>I have class Something with few objects:</p> <pre><code>class Something(): def __init__(self, name, attr1, attr2): self.name= name self.attr1= attr1 self.attr2= attr2 def getName(self): return self.name Obj1=Something('Name1', 'bla bla1', 'bla bla2') Obj2=Something('Name2', 'bla bla3', 'bla bla4') </code></pre> <p>Those objects are stored in list:</p> <pre><code>objects = [Obj1, Obj2] </code></pre> <p>I want to select object from the printed list and then (if object is on the list) print its name. So far I wrote code below, but it doesn't work. with error (AttributeError: 'str' object has no attribute 'getNazwa')</p> <pre><code>print('Select object from list: ', objects) y=raw_input('enter the name of the object') for i in objects: if y == i: print "Name: " + i.getName() </code></pre> <p>When print list it's someting like that:</p> <pre><code>('Select object fromfrom list: ', [&lt;__main__.Something instance at 0x024FB440&gt;, &lt;__main__.Something instance at 0x024FB490&gt;]) </code></pre> <p>How to convert it into print objects name?</p> <p>I guess that solution isn't rocket science for You Guys, so someone will help me ;)</p>
0
2016-10-06T11:46:43Z
39,895,296
<p>in your lines:</p> <pre><code>for i in objects: if y == i: </code></pre> <p>i is an object, and y in a string, so you can't compare them</p> <p>however, you can do </p> <pre><code>for i in objects: if y == i.getName(): </code></pre> <p>so you compare two strings together</p>
0
2016-10-06T11:53:24Z
[ "python", "class", "object" ]
getting list of indices of each value of list in a pythonic way
39,895,221
<p>I have a list <code>data</code> of values, and I want to return a dictionary mapping each value of <code>data</code> to a list of the indices where this value appears.</p> <p>This can be done using this code:</p> <pre><code>data = np.array(data) {val: list(np.where(data==val)[0]) for val in data} </code></pre> <p>but this runs in O(n^2), and this is too slow for long lists. Can an O(n) solution be coded using a "pythonic" syntax? (it can be done with creating an empty list and updating it in a loop, but I understand this is not recommended in python.)</p>
0
2016-10-06T11:49:43Z
39,895,339
<p>You can use a <a href="https://docs.python.org/3/library/collections.html#collections.defaultdict" rel="nofollow"><code>defaultdict</code></a> of <code>lists</code> to achieve this in O(n):</p> <pre><code>from collections import defaultdict d = defaultdict(list) for idx, item in enumerate(data): d[item].append(idx) </code></pre> <p>For example, if <code>data</code> contains the string <code>'abcabccbazzzqa'</code>:</p> <pre><code>d = defaultdict(list) for idx, item in enumerate('abcabccbazzzqa'): d[item].append(idx) &gt;&gt;&gt; d defaultdict(&lt;type 'list'&gt;, {'a': [0, 3, 8, 13], 'q': [12], 'c': [2, 5, 6], 'b': [1, 4, 7], 'z': [9, 10, 11]}) &gt;&gt;&gt; d['a'] [0, 3, 8, 13] </code></pre>
4
2016-10-06T11:55:35Z
[ "python", "numpy" ]
getting list of indices of each value of list in a pythonic way
39,895,221
<p>I have a list <code>data</code> of values, and I want to return a dictionary mapping each value of <code>data</code> to a list of the indices where this value appears.</p> <p>This can be done using this code:</p> <pre><code>data = np.array(data) {val: list(np.where(data==val)[0]) for val in data} </code></pre> <p>but this runs in O(n^2), and this is too slow for long lists. Can an O(n) solution be coded using a "pythonic" syntax? (it can be done with creating an empty list and updating it in a loop, but I understand this is not recommended in python.)</p>
0
2016-10-06T11:49:43Z
39,895,368
<p>Try this out :</p> <pre><code>data = np.array(data) dic = {} for i, val in enumerate(data): if val in dic.keys(): dic[val].append(i) else: dic[val]=[] dic[val].append(i) </code></pre>
1
2016-10-06T11:56:52Z
[ "python", "numpy" ]
Pandas dataframe creation from a list
39,895,315
<p>Im getting the following error <code>Shape of passed values is (1, 5), indices imply (5, 5)</code>. From what I can tell this suggests that the data set doesnt match the column count, and of course it obviously is correct. Initially I thought it could be due to using a list, but I get the same issue if passing in a numpy array.</p> <p>Can anyone point out my stupidity, as im clearly doing something incorrectly.</p> <pre><code>data = ['data1', 'data2', 'data3', 'data4', 'data5'] report_name = 'test.csv' try: df = pd.DataFrame(data, columns=['column1', 'column2', 'column3', 'column4', 'column5'], index=None) df.sort_values('column1', ascending=True, inplace=True) df.to_csv(report_name, index=False) except Exception, e: print e </code></pre>
1
2016-10-06T11:54:10Z
39,895,386
<p>you have to pass a 2d dimensional array to <code>pd.DataFrame</code> for the data if you force the shape by passing <code>columns</code></p> <pre><code>data = [['data1', 'data2', 'data3', 'data4', 'data5']] df = pd.DataFrame(data, columns=['column1', 'column2', 'column3', 'column4', 'column5']) </code></pre>
1
2016-10-06T11:57:50Z
[ "python", "pandas" ]
Pandas dataframe creation from a list
39,895,315
<p>Im getting the following error <code>Shape of passed values is (1, 5), indices imply (5, 5)</code>. From what I can tell this suggests that the data set doesnt match the column count, and of course it obviously is correct. Initially I thought it could be due to using a list, but I get the same issue if passing in a numpy array.</p> <p>Can anyone point out my stupidity, as im clearly doing something incorrectly.</p> <pre><code>data = ['data1', 'data2', 'data3', 'data4', 'data5'] report_name = 'test.csv' try: df = pd.DataFrame(data, columns=['column1', 'column2', 'column3', 'column4', 'column5'], index=None) df.sort_values('column1', ascending=True, inplace=True) df.to_csv(report_name, index=False) except Exception, e: print e </code></pre>
1
2016-10-06T11:54:10Z
39,895,572
<p>You've missed the list brackets around <code>data</code></p> <pre><code>df = pd.DataFrame(data = [data], columns=['column1', 'column2', 'column3', 'column4', 'column5'], index=None) </code></pre> <p>Things to note: <code>pd.DataFrame()</code> expects a list of <em>tuples</em>, this means: </p> <pre><code>data = ['data1', 'data2', 'data3', 'data4', 'data5'] df = pd.DataFrame(data) # This implies every element in the list `data` is a tuple print(df) Out[]: 0 0 data1 1 data2 2 data3 3 data4 4 data5 </code></pre> <p>As opposed to :</p> <pre><code>data = ['data1', 'data2', 'data3', 'data4', 'data5'] df = pd.DataFrame([data]) # This implies that the list `data` is the first tuple print(df) Out[]: 0 1 2 3 4 0 data1 data2 data3 data4 data5 </code></pre>
0
2016-10-06T12:07:05Z
[ "python", "pandas" ]
2D Orthogonal projection of vector onto line with numpy yields wrong result
39,895,330
<p>I have 350 document scores that, when I plot them, have this shape:</p> <pre><code>docScores = [(0, 68.62998962), (1, 60.21374512), (2, 54.72480392), (3, 50.71389389), (4, 49.39723969), ..., (345, 28.3756237), (346, 28.37126923), (347, 28.36397934), (348, 28.35762787), (349, 28.34219933)] </code></pre> <p>I posted the complete array <a href="http://pastebin.com/JeW3kJf4" rel="nofollow">here</a> on <code>pastebin</code> (it corresponds to the <code>dataPoints</code> list on the code below).</p> <p><a href="http://i.stack.imgur.com/BAeDE.png" rel="nofollow"><img src="http://i.stack.imgur.com/BAeDE.png" alt="Score distribution"></a></p> <p>Now, I originally needed to find the <code>elbow point</code> of this <code>L-shape</code> curve, which I found thanks to <a href="http://stackoverflow.com/questions/2018178/finding-the-best-trade-off-point-on-a-curve">this post</a>.</p> <p>Now, on the following plot, the red vector <code>p</code> represents the elbow point. I would like to find the point <code>x=(?,?)</code> (the yellow star) on the vector <code>b</code> which corresponds to the orthogonal projection of <code>p</code> onto <code>b</code>. </p> <p><a href="http://i.stack.imgur.com/f1Kju.png" rel="nofollow"><img src="http://i.stack.imgur.com/f1Kju.png" alt="enter image description here"></a></p> <p>The red point on the plot is the one I obtain (which is obviously wrong). I obtain it doing the following:</p> <pre><code>b_hat = b / np.linalg.norm(b) #unit vector of b proj_p_onto_b = p.dot(b_hat)*b_hat red_point = proj_p_onto_b + s </code></pre> <p>Now, if the projection of <code>p</code> onto <code>b</code> is defined by the its starting and ending point, namely <code>s</code> and <code>x</code> (the yellow star), it follows that <code>proj_p_onto_b = x - s</code>, therefore <code>x = proj_p_onto_b + s</code> ?</p> <p>Did I make a mistake here ?</p> <p><strong>EDIT :</strong> In answer to @cxw, here is the code for computing the elbow point :</p> <pre><code>def findElbowPoint(self, rawDocScores): dataPoints = zip(range(0, len(rawDocScores)), rawDocScores) s = np.array(dataPoints[0]) l = np.array(dataPoints[len(dataPoints)-1]) b_vect = l-s b_hat = b_vect/np.linalg.norm(b_vect) distances = [] for scoreVec in dataPoints[1:]: p = np.array(scoreVec) - s proj = p.dot(b_hat)*b_hat d = abs(np.linalg.norm(p - proj)) # orthgonal distance between b and the L-curve distances.append((scoreVec[0], scoreVec[1], proj, d)) elbow_x = max(distances, key=itemgetter(3))[0] elbow_y = max(distances, key=itemgetter(3))[1] proj = max(distances, key=itemgetter(3))[2] max_distance = max(distances, key=itemgetter(3))[3] red_point = proj + s </code></pre> <p><strong>EDIT</strong> : Here is the code for the plot :</p> <pre><code>&gt;&gt;&gt; l_curve_x_values = [x[0] for x in docScores] &gt;&gt;&gt; l_curve_y_values = [x[1] for x in docScores] &gt;&gt;&gt; b_line_x_values = [x[0] for x in docScores] &gt;&gt;&gt; b_line_y_values = np.linspace(s[1], l[1], len(docScores)) &gt;&gt;&gt; p_line_x_values = l_curve_x_values[:elbow_x] &gt;&gt;&gt; p_line_y_values = np.linspace(s[1], elbow_y, elbow_x) &gt;&gt;&gt; plt.plot(l_curve_x_values, l_curve_y_values, b_line_x_values, b_line_y_values, p_line_x_values, p_line_y_values) &gt;&gt;&gt; red_point = proj + s &gt;&gt;&gt; plt.plot(red_point[0], red_point[1], 'ro') &gt;&gt;&gt; plt.show() </code></pre>
3
2016-10-06T11:55:10Z
39,895,669
<p>First of all, is the point at ~(50, 37) <code>p</code> or <code>s+p</code>? If <code>p</code>, that might be your problem right there! If the Y component of your <code>p</code> variable is positive, you won't get the results you expect when you do the dot product.</p> <p>Assuming that point is <code>s+p</code>, if a bit of Post-It scribbling is correct,</p> <pre><code>p_len = np.linalg.norm(p) p_hat = p / p_len red_len = p_hat.dot(b_hat) * p_len # red_len = |x-s| # because p_hat . b_hat = 1 * 1 * cos(angle) = |x-s| / |p| red_point = s + red_len * b_hat </code></pre> <p>Not tested! YMMV. Hope this helps.</p>
1
2016-10-06T12:12:43Z
[ "python", "numpy", "plot", "linear-algebra", "orthogonal" ]
2D Orthogonal projection of vector onto line with numpy yields wrong result
39,895,330
<p>I have 350 document scores that, when I plot them, have this shape:</p> <pre><code>docScores = [(0, 68.62998962), (1, 60.21374512), (2, 54.72480392), (3, 50.71389389), (4, 49.39723969), ..., (345, 28.3756237), (346, 28.37126923), (347, 28.36397934), (348, 28.35762787), (349, 28.34219933)] </code></pre> <p>I posted the complete array <a href="http://pastebin.com/JeW3kJf4" rel="nofollow">here</a> on <code>pastebin</code> (it corresponds to the <code>dataPoints</code> list on the code below).</p> <p><a href="http://i.stack.imgur.com/BAeDE.png" rel="nofollow"><img src="http://i.stack.imgur.com/BAeDE.png" alt="Score distribution"></a></p> <p>Now, I originally needed to find the <code>elbow point</code> of this <code>L-shape</code> curve, which I found thanks to <a href="http://stackoverflow.com/questions/2018178/finding-the-best-trade-off-point-on-a-curve">this post</a>.</p> <p>Now, on the following plot, the red vector <code>p</code> represents the elbow point. I would like to find the point <code>x=(?,?)</code> (the yellow star) on the vector <code>b</code> which corresponds to the orthogonal projection of <code>p</code> onto <code>b</code>. </p> <p><a href="http://i.stack.imgur.com/f1Kju.png" rel="nofollow"><img src="http://i.stack.imgur.com/f1Kju.png" alt="enter image description here"></a></p> <p>The red point on the plot is the one I obtain (which is obviously wrong). I obtain it doing the following:</p> <pre><code>b_hat = b / np.linalg.norm(b) #unit vector of b proj_p_onto_b = p.dot(b_hat)*b_hat red_point = proj_p_onto_b + s </code></pre> <p>Now, if the projection of <code>p</code> onto <code>b</code> is defined by the its starting and ending point, namely <code>s</code> and <code>x</code> (the yellow star), it follows that <code>proj_p_onto_b = x - s</code>, therefore <code>x = proj_p_onto_b + s</code> ?</p> <p>Did I make a mistake here ?</p> <p><strong>EDIT :</strong> In answer to @cxw, here is the code for computing the elbow point :</p> <pre><code>def findElbowPoint(self, rawDocScores): dataPoints = zip(range(0, len(rawDocScores)), rawDocScores) s = np.array(dataPoints[0]) l = np.array(dataPoints[len(dataPoints)-1]) b_vect = l-s b_hat = b_vect/np.linalg.norm(b_vect) distances = [] for scoreVec in dataPoints[1:]: p = np.array(scoreVec) - s proj = p.dot(b_hat)*b_hat d = abs(np.linalg.norm(p - proj)) # orthgonal distance between b and the L-curve distances.append((scoreVec[0], scoreVec[1], proj, d)) elbow_x = max(distances, key=itemgetter(3))[0] elbow_y = max(distances, key=itemgetter(3))[1] proj = max(distances, key=itemgetter(3))[2] max_distance = max(distances, key=itemgetter(3))[3] red_point = proj + s </code></pre> <p><strong>EDIT</strong> : Here is the code for the plot :</p> <pre><code>&gt;&gt;&gt; l_curve_x_values = [x[0] for x in docScores] &gt;&gt;&gt; l_curve_y_values = [x[1] for x in docScores] &gt;&gt;&gt; b_line_x_values = [x[0] for x in docScores] &gt;&gt;&gt; b_line_y_values = np.linspace(s[1], l[1], len(docScores)) &gt;&gt;&gt; p_line_x_values = l_curve_x_values[:elbow_x] &gt;&gt;&gt; p_line_y_values = np.linspace(s[1], elbow_y, elbow_x) &gt;&gt;&gt; plt.plot(l_curve_x_values, l_curve_y_values, b_line_x_values, b_line_y_values, p_line_x_values, p_line_y_values) &gt;&gt;&gt; red_point = proj + s &gt;&gt;&gt; plt.plot(red_point[0], red_point[1], 'ro') &gt;&gt;&gt; plt.show() </code></pre>
3
2016-10-06T11:55:10Z
39,898,113
<p>If you are using the plot to visually determine if the solution looks correct, you must plot the data using the same scale on each axis, i.e. use <code>plt.axis('equal')</code>. If the axes do not have equal scales, the angles between lines are distorted in the plot.</p>
2
2016-10-06T14:02:54Z
[ "python", "numpy", "plot", "linear-algebra", "orthogonal" ]
How to run non-linear regression in python
39,895,369
<p>i am having the following information(dataframe) in python</p> <pre><code>product baskets scaling_factor 12345 475 95.5 12345 108 57.7 12345 2 1.4 12345 38 21.9 12345 320 88.8 </code></pre> <p>and I want to run the following <strong>non-linear regression</strong> and <strong>estimate the parameters.</strong> </p> <p><strong>a ,b and c</strong></p> <p>Equation that i want to fit:</p> <pre><code>scaling_factor = a - (b*np.exp(c*baskets)) </code></pre> <p>In sas we usually run the following model:(uses gauss newton method )</p> <pre><code>proc nlin data=scaling_factors; parms a=100 b=100 c=-0.09; model scaling_factor = a - (b * (exp(c*baskets))); output out=scaling_equation_parms parms=a b c; </code></pre> <p>is there a similar way to estimate the parameters in Python using non linear regression, how can i see the plot in python.</p>
2
2016-10-06T11:56:56Z
39,895,677
<p>For problems like these I always use <a href="http://docs.scipy.org/doc/scipy-0.15.1/reference/generated/scipy.optimize.minimize.html" rel="nofollow"><code>scipy.optimize.minimize</code></a> with my own least squares function. The optimization algorithms don't handle large differences between the various inputs well, so it is a good idea to scale the parameters in your function so that the parameters exposed to scipy are all on the order of 1 as I've done below.</p> <pre><code>import numpy as np baskets = np.array([475, 108, 2, 38, 320]) scaling_factor = np.array([95.5, 57.7, 1.4, 21.9, 88.8]) def lsq(arg): a = arg[0]*100 b = arg[1]*100 c = arg[2]*0.1 now = a - (b*np.exp(c * baskets)) - scaling_factor return np.sum(now**2) guesses = [1, 1, -0.9] res = scipy.optimize.minimize(lsq, guesses) print(res.message) # 'Optimization terminated successfully.' print(res.x) # [ 0.97336709 0.98685365 -0.07998282] print([lsq(guesses), lsq(res.x)]) # [7761.0093358076601, 13.055053196410928] </code></pre> <p>Of course, as with all minimization problems it is important to use good initial guesses since all of the algorithms can get trapped in a local minimum. The optimization method can be changed by using the <code>method</code> keyword; some of the possibilities are</p> <ul> <li>‘Nelder-Mead’</li> <li>‘Powell’</li> <li>‘CG’</li> <li>‘BFGS’</li> <li>‘Newton-CG’</li> </ul> <p>The default is BFGS according to <a href="http://docs.scipy.org/doc/scipy-0.15.1/reference/generated/scipy.optimize.minimize.html" rel="nofollow">the documentation</a>.</p>
3
2016-10-06T12:13:08Z
[ "python", "python-3.x", "pandas", "numpy", "sklearn-pandas" ]
How to run non-linear regression in python
39,895,369
<p>i am having the following information(dataframe) in python</p> <pre><code>product baskets scaling_factor 12345 475 95.5 12345 108 57.7 12345 2 1.4 12345 38 21.9 12345 320 88.8 </code></pre> <p>and I want to run the following <strong>non-linear regression</strong> and <strong>estimate the parameters.</strong> </p> <p><strong>a ,b and c</strong></p> <p>Equation that i want to fit:</p> <pre><code>scaling_factor = a - (b*np.exp(c*baskets)) </code></pre> <p>In sas we usually run the following model:(uses gauss newton method )</p> <pre><code>proc nlin data=scaling_factors; parms a=100 b=100 c=-0.09; model scaling_factor = a - (b * (exp(c*baskets))); output out=scaling_equation_parms parms=a b c; </code></pre> <p>is there a similar way to estimate the parameters in Python using non linear regression, how can i see the plot in python.</p>
2
2016-10-06T11:56:56Z
39,896,700
<p>Agreeing with Chris Mueller, I'd also use <code>scipy</code> but <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.curve_fit.html" rel="nofollow"><code>scipy.optimize.curve_fit</code></a>. The code looks like:</p> <pre><code>###the top two lines are required on my linux machine import matplotlib matplotlib.use('Qt4Agg') import matplotlib.pyplot as plt from matplotlib.pyplot import cm import numpy as np from scipy.optimize import curve_fit #we could import more, but this is what we need ###defining your fitfunction def func(x, a, b, c): return a - b* np.exp(c * x) ###OP's data baskets = np.array([475, 108, 2, 38, 320]) scaling_factor = np.array([95.5, 57.7, 1.4, 21.9, 88.8]) ###let us guess some start values initialGuess=[100, 100,-.01] guessedFactors=[func(x,*initialGuess ) for x in baskets] ###making the actual fit popt,pcov = curve_fit(func, baskets, scaling_factor,initialGuess) #one may want to print popt print pcov ###preparing data for showing the fit basketCont=np.linspace(min(baskets),max(baskets),50) fittedData=[func(x, *popt) for x in basketCont] ###preparing the figure fig1 = plt.figure(1) ax=fig1.add_subplot(1,1,1) ###the three sets of data to plot ax.plot(baskets,scaling_factor,linestyle='',marker='o', color='r',label="data") ax.plot(baskets,guessedFactors,linestyle='',marker='^', color='b',label="initial guess") ax.plot(basketCont,fittedData,linestyle='-', color='#900000',label="fit with ({0:0.2g},{1:0.2g},{2:0.2g})".format(*popt)) ###beautification ax.legend(loc=0, title="graphs", fontsize=12) ax.set_ylabel("factor") ax.set_xlabel("baskets") ax.grid() ax.set_title("$\mathrm{curve}_\mathrm{fit}$") ###putting the covariance matrix nicely tab= [['{:.2g}'.format(j) for j in i] for i in pcov] the_table = plt.table(cellText=tab, colWidths = [0.2]*3, loc='upper right', bbox=[0.483, 0.35, 0.5, 0.25] ) plt.text(250,65,'covariance:',size=12) ###putting the plot plt.show() ###done </code></pre> <p>Eventually, giving you: <a href="http://i.stack.imgur.com/tRZ8q.png" rel="nofollow"><img src="http://i.stack.imgur.com/tRZ8q.png" alt="enter image description here"></a></p>
2
2016-10-06T12:59:31Z
[ "python", "python-3.x", "pandas", "numpy", "sklearn-pandas" ]
Creating lambda function with conditions on one df to use in df.apply of another df
39,895,553
<p>Consider <code>df</code></p> <pre><code>Index A B C 0 20161001 0 24.5 1 20161001 3 26.5 2 20161001 6 21.5 3 20161001 9 29.5 4 20161001 12 20.5 5 20161002 0 30.5 6 20161002 3 22.5 7 20161002 6 25.5 ... </code></pre> <p>Also consider <code>df2</code></p> <pre><code>Index Threshold 0 25 1 27 2 29 3 30 4 25 5 30 .. </code></pre> <p>I want to add a column <code>"Number of Rows"</code> to <code>df2</code> which contains the number of rows in <code>df</code> where <code>(C &gt; Threshold) &amp; (A &gt;= 20161001) &amp; (A &lt;= 20161002)</code> holds true. This is basically to imply that there are conditions on more than one column in <code>df</code></p> <pre><code>Index Threshold Number of Rows 0 25 4 1 27 2 2 29 2 3 30 1 4 25 4 5 30 1 .. </code></pre> <p>For <code>Threshold=25</code> in <code>df2</code>, there are 4 rows in <code>df</code> where <code>"C"</code> value crosses 25.</p> <p>I tried something like:</p> <pre><code>def foo(threshold,start,end): return len(df[(df['C'] &gt; threshold) &amp; (df['A'] &gt; start) &amp; (df['A'] &lt; end)]) df2['Number of rows'] = df.apply(lambda df2: foo(df2['Threshold'],start = 20161001, end = 20161002),axis=1) </code></pre> <p>But this is populating the <code>Number of Rows</code> column with 0. Why is this?</p>
2
2016-10-06T12:06:26Z
39,895,896
<p>You could make use of Boolean Indexing and the <code>sum()</code> aggregate function</p> <pre><code># Create the first dataframe (df) df = pd.DataFrame([[20161001,0 ,24.5], [20161001,3 ,26.5], [20161001,6 ,21.5], [20161001,9 ,29.5], [20161001,12,20.5], [20161002,0 ,30.5], [20161002,3 ,22.5], [20161002,6 ,25.5]],columns=['A','B','C']) # Create the second dataframe (df2) df2 = pd.DataFrame(data=[25,27,29,30,25,30],columns=['Threshold']) start = 20161001 end = 20161002 df2['Number of Rows'] = df2['Threshold'].apply(lambda x : ((df.C &gt; x) &amp; (df.A &gt;= start) &amp; (df.A &lt;= end)).sum()) print(df2['Number of Rows']) Out[]: 0 4 1 2 2 2 3 1 4 4 5 1 Name: Number of Rows, dtype: int64 </code></pre>
2
2016-10-06T12:22:42Z
[ "python", "pandas", "lambda" ]
Jenkins Python API: get QueueItem by ID
39,895,586
<p>Invoking a job in Jenkins via <a href="https://pypi.python.org/pypi/jenkinsapi/0.2.31" rel="nofollow">jenkinsapi</a> returns a <code>jenkinsapi.queue.QueueItem</code> object that represents queued build.</p> <p>How can I get <code>QueueItem</code> object of an already queued build, given <code>queue_id</code>? I have tried:</p> <pre><code>j = Jenkins(...) queue = j.get_queue() queue_item = queue[queue_id] </code></pre> <p>But that is valid only for about 6-10 seconds, after that <code>UnknownQueueItem</code> error is raised.</p>
0
2016-10-06T12:08:06Z
39,895,920
<p>It seems you have to create <code>QueueItem</code> manually:</p> <pre><code>j = Jenkins(...) url = j.base_server_url() + "/queue/item/" + str(queue_id) + "/" queue_item = jenkinsapi.queue.QueueItem(url, j); </code></pre>
0
2016-10-06T12:23:50Z
[ "python", "jenkins", "jenkins-api" ]
How to access a object's attrbute by using string corresponding to name if object is attribute of some other object
39,895,789
<p>I have 3 classes as below:- </p> <pre><code>class C(object): def __init__(self, v): self.var = v class B(object): def __init__(self, c): self.c = c class A(object): def __init__(self, b): self.b = b I have created instances as c = C("required result") b = B(c) a = A(b) &gt;&gt;&gt; a.b.c.var 'required result' </code></pre> <p>Now I need to pass b.c.var as a string to some function and get the value of var similar to sample function as below - </p> <pre><code>`sample(a, 'b.c.var')` should return 'required result'` </code></pre> <p>What should be pythonic way to achieve this This is my attempt :- </p> <pre><code>for attr in ('b', 'c', 'var'): a = getattr(a, attr) &gt;&gt;&gt; print a required result </code></pre>
0
2016-10-06T12:18:33Z
39,896,267
<p>Here is the more accurate way, I suppose. (using <code>try-except</code> construction):</p> <pre><code>... c = C("required result") b = B(c) a = A(b) def sample(obj, path): path_attrs = path.split('.') # splitting inner attributes path inner_attr = None for p in path_attrs: try: inner_attr = getattr(inner_attr if inner_attr else obj, p) except AttributeError: print('No %s field' % p) print(inner_attr) sample(a, 'b.c.var') # will output 'required result' </code></pre>
1
2016-10-06T12:39:17Z
[ "python" ]
How to access a object's attrbute by using string corresponding to name if object is attribute of some other object
39,895,789
<p>I have 3 classes as below:- </p> <pre><code>class C(object): def __init__(self, v): self.var = v class B(object): def __init__(self, c): self.c = c class A(object): def __init__(self, b): self.b = b I have created instances as c = C("required result") b = B(c) a = A(b) &gt;&gt;&gt; a.b.c.var 'required result' </code></pre> <p>Now I need to pass b.c.var as a string to some function and get the value of var similar to sample function as below - </p> <pre><code>`sample(a, 'b.c.var')` should return 'required result'` </code></pre> <p>What should be pythonic way to achieve this This is my attempt :- </p> <pre><code>for attr in ('b', 'c', 'var'): a = getattr(a, attr) &gt;&gt;&gt; print a required result </code></pre>
0
2016-10-06T12:18:33Z
39,896,333
<p>You can use <a href="https://docs.python.org/3/library/operator.html#operator.attrgetter" rel="nofollow">operator.attrgetter</a> which takes a dotted name notation, eg:</p> <pre><code>from operator import attrgetter attrgetter('b.c.var')(a) # 'required result' </code></pre> <p>Then if you don't like that syntax, use it to make your <code>sample</code> function, eg:</p> <pre><code>def sample(obj, attribute): getter = attrgetter(attribute) return getter(obj) </code></pre> <p>From the documentation linked above, the <code>operator.attrgetter</code> uses the equivalent of the following code:</p> <pre><code>def attrgetter(*items): if any(not isinstance(item, str) for item in items): raise TypeError('attribute name must be a string') if len(items) == 1: attr = items[0] def g(obj): return resolve_attr(obj, attr) else: def g(obj): return tuple(resolve_attr(obj, attr) for attr in items) return g def resolve_attr(obj, attr): for name in attr.split("."): obj = getattr(obj, name) return obj </code></pre> <p>So in fact - your original code was just trying to do the equivalent of <code>resolve_attr</code>...</p>
5
2016-10-06T12:42:47Z
[ "python" ]
How to open my favorite editor from PsychoPy Builder
39,895,908
<p>I'm using PsychoPy Builder. I'd like to write codes with vim. How should I open it from PsychoPy Builder? Sorry about my poor English.</p>
-2
2016-10-06T12:23:15Z
39,902,743
<p>The "builder" is a gui interface to the psychopy library. If you want to write code then you probably want to use psychopy as a library. To do that you will have to figure out where the library is stored on your system, and that might be easier if you don't use the stand-alone version, but get one of the library version and install that (you could use the tools pip or easy-install) if you have used those python tools before. Then you will find Psychopy whereever your other libraries get stored which will be something like .../python27/site-packages/Psychpy-/psychopy/.... With the first set of ... depending on Mac/Linux/FreeBSD/Windows</p> <p>Navigate down that path through demos; coder; stimuli; unti you see a .py file. Then you can open that up in Vim and modify it as practice.</p> <p>If none of this makes any sense, then you probably want to use the builder and standalone until you get some more hands on experience. Cheers,</p>
0
2016-10-06T17:59:28Z
[ "python", "psychopy" ]
How to check if videos overlap
39,896,059
<p>I am new to video analysis and python and is working on a project on video composition. I have three videos that overlap. for example below are the start and end time of the videos</p> <pre><code> video1 video2 video3 start 19-13-30 19-13-25 19-13-45 end 19-13-55 19-13-35 19-13-59 </code></pre> <p>In the above scenario video1 &amp; video2 overlap for 5 sec(19-13-30 to 19-13-35) and video1 and video3 overlap for 10 sec(19-13-45 to 19-13-55).</p> <p>So,is there a way to identify the overlaps in the videos given the timestamps and returning the timestamps for which they overlap or by just analyzing the video</p>
-2
2016-10-06T12:29:47Z
39,901,194
<p>Suppose you have a list of starttime and endtime of the videos [[video1_starttime,video1_endtime],[video2_starttime,video2_endtime],[video3_starttime,video3_endtime]], you can first sort the list based on startimes and then iterate over it to check if it is overlapping.</p> <p>You can use the below code to check for it:</p> <pre><code>overlapping = [ [x,y] for x in intervals for y in intervals if x is not y and x[1]&gt;y[0] and x[0]&lt;y[0] ] for x in overlapping: print '{0} overlaps with {1}'.format(x[0],x[1]) </code></pre> <p>where intervals is the list of <code>[starttime,endtime]</code></p> <p>To compare the timestamps, convert them to datetime objects using:</p> <pre><code>from datetime import datetime dateTimeObject = datetime.strptime(timestampString) </code></pre>
0
2016-10-06T16:27:00Z
[ "python", "timestamp", "video-processing" ]
Is it possible to get values from my local machine to my form inputs tag?
39,896,551
<p>I have this code:</p> <pre><code>&lt;div class="col-md-12"&gt; &lt;div class="form-panel"&gt; &lt;h4&gt;&lt;i class="fa fa-angle-right"&gt;&lt;/i&gt; Testing &lt;/h4&gt; &lt;hr /&gt; &lt;form method="post" name="ibisaserver"&gt; &lt;div class="form-group"&gt; &lt;label class="col-sm-3 col-sm-3 control-label"&gt;Address:&lt;/label&gt; &lt;div class="col-sm-9"&gt; &lt;input type="text" class="form-control" name="interfaces" value="" required&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="form-group "&gt; &lt;label class="col-sm-3 col-sm-3 control-label"&gt;Network: &lt;/label&gt; &lt;div class="col-sm-9"&gt; &lt;input type="text" class="form-control" name="direccionIp" value="" required&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;label class="col-sm-3 col-sm-3 control-label"&gt;Netmask : &lt;/label&gt; &lt;div class="col-sm-9"&gt; &lt;input type="text" class="form-control" name="mascaraSub" value="" required&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;label class="col-sm-3 col-sm-3 control-label"&gt;Broadcast : &lt;/label&gt; &lt;div class="col-sm-9"&gt; &lt;input type="text" class="form-control" name="direccionGat" value="" required&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>As you can see I have 4 inputs tag..</p> <p>And I have this code as well:</p> <pre><code>with open("/etc/network/interfaces", "r") as file: content = file.read() print content </code></pre> <p>Where I'm getting the information I need from the following path : "/etc/network/interfaces".</p> <p>Something like this:</p> <p><a href="http://i.stack.imgur.com/P9O0X.png" rel="nofollow"><img src="http://i.stack.imgur.com/P9O0X.png" alt="enter image description here"></a></p> <p>Now, My question is: Is there a way to show the data I'm getting from my python or my local machine ("etc/network/interfaces") to my input tags? </p>
0
2016-10-06T12:52:55Z
39,900,979
<p>There are two ways which you can use:</p> <ol> <li><p>Make the python file generate the output html file, which you can use. <a href="https://www.decalage.info/python/html" rel="nofollow">HTML.py</a> is a good option to start with it.</p></li> <li><p>You can use XmlHttpRequest to read local files using javascript and populate the data automatically using JQuery.</p></li> </ol>
0
2016-10-06T16:15:42Z
[ "javascript", "python", "html", "linux", "debian" ]
execution failure of an self insertion_sort definition in python3
39,896,566
<p>I want to put the numbers from the smallest to the largest.</p> <p>NO.1 succeed</p> <pre><code>def insertion_sort(list): for index in range(1,len(list)): value = list[index] i = index-1 while i &gt;=0: if value &lt; list[i]: list[i+1]=list[i] list[i] = value i = i-1 else : break a=[2,1,4,3,6,7,9,5] insertion_sort(a) print(a) </code></pre> <p>NO.2 failed</p> <pre><code>def insertion_sort(list): for index in range(1,len(list)): value = list[index] i = index - 1 while i&gt;=0: if value &gt; list[i]: i=i-1 else : list[i+1]=list[i] list[i]=value break a=[1,3,2,7,4,6,5] insertion_sort(a) print(a) </code></pre> <p>when I ran the second, it returned <code>[1, 2, 3, 4, 6, 5, 7]</code></p> <p>I don't know why and if I remove <code>break</code>, in the second one, it won't return a result, why? I thought the for loop will close itself.</p>
1
2016-10-06T12:53:36Z
39,896,829
<p>Implementation of insertion sort (without sentinel) should look like;</p> <pre><code>def insertion_sort(list_): for index in range(1,len(list_)): value = list_[index] i = index - 1 while i &gt;= 0 and list_[i] &gt; value : list_[i + 1] = list_[i] list_[i] = value i = i - 1 return list_ </code></pre> <p>Also remember to not named your list argument <code>list</code> because it's python builtin class.</p>
0
2016-10-06T13:05:27Z
[ "python" ]
Retruning multiple objects and using them as arguments
39,896,610
<p>I have a function which goes something like this:</p> <pre><code>def do_something(lis): do something return lis[0], lis[1] </code></pre> <p>and another function which needs to take those two return objects as arguments:</p> <pre><code>def other_function(arg1, arg2): pass </code></pre> <p>I have tried:</p> <pre><code>other_function(do_something(lis)) </code></pre> <p>but incurred this error:</p> <pre><code>TypeError: other_function() missing 1 required positional argument: 'arg2' </code></pre>
2
2016-10-06T12:55:33Z
39,896,654
<p>You need to unpack those arguments when calling <code>other_function</code>. </p> <pre><code>other_function(*do_something(lis)) </code></pre> <p>Based on the error message, it looks like your other function is defined (and should be defined as)</p> <pre><code>def other_function(arg1, arg2): pass </code></pre> <p>So, when you return from <code>do_something</code>, you are actually returning a tuple containing <code>(lis[0], lis[1])</code>. So when you originally called <code>other_function</code>, you passing a single tuple, when your <code>other_function</code> was still expecting a second argument. </p> <p>You can see this if you break it down a bit further. Below is a breakdown of how the returns look like when handled differently, a reproduction of your error and a demo of the solution: </p> <p>Returning in to a single variable will return a tuple of the result:</p> <pre><code>&gt;&gt;&gt; def foo(): ... lis = range(10) ... return lis[1], lis[2] ... &gt;&gt;&gt; result = foo() &gt;&gt;&gt; result (1, 2) </code></pre> <p>Returning in to two variables, unpacks in to each var:</p> <pre><code>&gt;&gt;&gt; res1, res2 = foo() &gt;&gt;&gt; res1 1 &gt;&gt;&gt; res2 2 </code></pre> <p>Trying to call other_function with <code>result</code> which now only holds a tuple of your result:</p> <pre><code>&gt;&gt;&gt; def other_function(arg1, arg2): ... print(arg1, arg2) ... &gt;&gt;&gt; other_function(result) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: other_function() missing 1 required positional argument: 'arg2' </code></pre> <p>Calling other_function with <code>res1</code>, <code>res2</code> that holds each value of the return from <code>foo</code>:</p> <pre><code>&gt;&gt;&gt; other_function(res1, res2) 1 2 </code></pre> <p>Using <code>result</code> (your tuple result) and unpacking in your function call to <code>other_function</code>:</p> <pre><code>&gt;&gt;&gt; other_function(*result) 1 2 </code></pre>
3
2016-10-06T12:57:49Z
[ "python", "function", "functional-programming", "return", "arguments" ]
Retruning multiple objects and using them as arguments
39,896,610
<p>I have a function which goes something like this:</p> <pre><code>def do_something(lis): do something return lis[0], lis[1] </code></pre> <p>and another function which needs to take those two return objects as arguments:</p> <pre><code>def other_function(arg1, arg2): pass </code></pre> <p>I have tried:</p> <pre><code>other_function(do_something(lis)) </code></pre> <p>but incurred this error:</p> <pre><code>TypeError: other_function() missing 1 required positional argument: 'arg2' </code></pre>
2
2016-10-06T12:55:33Z
39,896,692
<p>You can do it like this:</p> <pre><code>other_function(*do_something(list)) </code></pre> <p>The <code>*</code> char will expand the <code>tuple</code> returned by <code>do_something</code>.</p> <p>Your <code>do_something</code> function is actually returning a <code>tuple</code> which contains several values but <strong>is</strong> only one value itself.</p> <p>See <a href="https://docs.python.org/2/tutorial/controlflow.html#unpacking-argument-lists" rel="nofollow">the doc</a> for more details.</p>
1
2016-10-06T12:59:13Z
[ "python", "function", "functional-programming", "return", "arguments" ]
Can I perform multiple assertions in pytest?
39,896,716
<p>I'm using pytest for my selenium tests and wanted to know if it's possible to have multiple assertions in a single test?</p> <p>I call a function that compares multiple values and I want the test to report on all the values that don't match up. The problem I'm having is that using "assert" or "pytest.fail" stops the test as soon as it finds a value that doesn't match up.</p> <p>Is there a way to make the test carry on running and report on all values that don't match?</p>
0
2016-10-06T13:00:22Z
39,897,110
<p>As Jon Clements commented, you can fill a list of error messages and then assert the list is empty, displaying each message when the assertion is false.</p> <p>concretely, it could be something like that:</p> <pre><code>def test_something(self): errors = [] # replace assertions by conditions if not condition_1: errors.append("an error message") if not condition_2: errors.append("an other error message") # assert no error message has been registered, else print messages assert not errors, "errors occured:\n{}".format("\n".join(errors)) </code></pre> <p>The original assertions are replaced by <code>if</code> statements which append messages to an <code>errors</code> list in case condition are not met. Then you assert the <code>errors</code> list is empty (an empty list is False) and make the assertion message contains each message of the <code>errors</code> list.</p> <hr> <p>You could also make a test generator as described in the <a href="http://nose.readthedocs.io/en/latest/writing_tests.html#test-generators" rel="nofollow">nose documentation</a>. I did not find any pytest doc which describes it, but I know that pytest handled this exactly the same manner as nose.</p>
0
2016-10-06T13:17:50Z
[ "python", "selenium", "py.test" ]
Can I perform multiple assertions in pytest?
39,896,716
<p>I'm using pytest for my selenium tests and wanted to know if it's possible to have multiple assertions in a single test?</p> <p>I call a function that compares multiple values and I want the test to report on all the values that don't match up. The problem I'm having is that using "assert" or "pytest.fail" stops the test as soon as it finds a value that doesn't match up.</p> <p>Is there a way to make the test carry on running and report on all values that don't match?</p>
0
2016-10-06T13:00:22Z
39,899,876
<p>Here's an alternative approach called <a href="http://pythontesting.net/strategy/delayed-assert/" rel="nofollow">Delayed assert</a>, It pretty much similar to what @Tryph has provided, and gives better stack trace.</p>
0
2016-10-06T15:20:31Z
[ "python", "selenium", "py.test" ]
ra & dec conversion from hh:mm:ss to degrees
39,896,756
<p>I have a file that contains ra &amp; dec in hh:mm:ss format. Say the file name is "coord.txt" and it's content is :</p> <blockquote> <p>06 40 34.8 10 04 22 06 41 11.6 10 02 24 06 40 50.9 10 01 43</p> </blockquote> <p>06 40 34.8 is the ra and 10 04 22 is the dec How do I convert it to degrees with python or any other program.</p>
0
2016-10-06T13:02:11Z
39,897,712
<pre><code>s = "06 40 34.8 10 04 22 06 41 11.6 10 02 24 06 40 50.9 10 01 43" # or s = f.readline() d = [float(i) for i in s.split()] # d = [6.0, 40.0, 34.8, 10.0, 4.0, 22.0, 6.0, 41.0, 11.6, 10.0, 2.0, 24.0, 6.0, 40.0, 50.9, 10.0, 1.0, 43.0] d2 = [d[i:i+3] for i in range(0, len(d), 3)] # d2 = [[6.0, 40.0, 34.8], [10.0, 4.0, 22.0], [6.0, 41.0, 11.6], [10.0, 2.0, 24.0], [6.0, 40.0, 50.9], [10.0, 1.0, 43.0]] d3 = [(s/3600 + m/60 + h) * 15 for h,m,s in d2] d4 = [d3[i:i+2] for i in range(0, len(d3), 2)] print d4 # [[100.145, 151.09166666666667], [100.29833333333333, 150.6], [100.21208333333334, 150.42916666666667]] </code></pre>
0
2016-10-06T13:44:50Z
[ "python", "awk" ]
ra & dec conversion from hh:mm:ss to degrees
39,896,756
<p>I have a file that contains ra &amp; dec in hh:mm:ss format. Say the file name is "coord.txt" and it's content is :</p> <blockquote> <p>06 40 34.8 10 04 22 06 41 11.6 10 02 24 06 40 50.9 10 01 43</p> </blockquote> <p>06 40 34.8 is the ra and 10 04 22 is the dec How do I convert it to degrees with python or any other program.</p>
0
2016-10-06T13:02:11Z
39,899,050
<p>implementing @M.Danilchenko's logic in <code>awk</code></p> <pre><code>$ awk '{for(i=1;i&lt;NF;i+=3) a[++c]=($i*15+($(i+1)+$(i+2)/60)/4); for(i=1;i&lt;c;i+=2) printf "(%.3f,%.3f) ", a[i],a[i+1]; print ""}' file (100.145,151.092) (100.298,150.600) (100.212,150.429) </code></pre> <p>where</p> <pre><code>$ cat file 06 40 34.8 10 04 22 06 41 11.6 10 02 24 06 40 50.9 10 01 43 </code></pre>
0
2016-10-06T14:44:37Z
[ "python", "awk" ]
Multiprocessing process does not join when putting complex dictionary in return queue
39,896,807
<p>Given a pretty standard read/write multithreaded process with a read Queue and a write Queue:</p> <p>8 times <code>worker done</code> is printed, but the join() statement is never passed. But if I replace <code>queue_out.put(r)</code> by `queue_out.put(1) it works. </p> <p>This is melting my brain, probably something really stupid. Should I make a copy of my dictionary and put that in the return Queue? Did I make a stupid mistake somewhere? </p> <p><strong>Process function</strong></p> <pre><code>def reader(queue_in, queue_out, funktion): # Read from the queue while True: r = queue_in.get() if r == 'DONE': return funktion(r) # funktion adds additional keys to the dictionary queue_out.put(r) # &lt;---- replacing r by 1 does let me join() print "worker done" # &lt;----- this happens </code></pre> <p><strong>Populate the input queue</strong></p> <pre><code>def writer(generator, queue): # Write to the queue for r in enumerate(generator): # r is a complex dictionary queue.put(r) print "writer done" for _ in range(0, WORKERS): queue.put((-1, "DONE")) </code></pre> <p><strong>The rest</strong></p> <pre><code>WORKERS = 8 # init Queues queue_in = Queue() queue_out = Queue() # Start processes, with input and output quests readers = [] for _ in range(0, WORKERS): p = Process(target=reader, args=(queue_in, queue_out, funktion)) p.daemon = True p.start() readers.append(p) writer(generator, queue_in) for p in readers: p.join() print "joined" # &lt;---- this never happens queue_in.close() while not queue_out.empty(): print queue_out.get() queue_out.close() </code></pre>
2
2016-10-06T13:04:34Z
39,899,602
<p>I <em>think</em> I have pieced this together from two sources as I always have the same problem. I think the important thing is that this is in Windows. </p> <p>Note from <a href="https://docs.python.org/2/library/multiprocessing.html" rel="nofollow">the documentation</a></p> <blockquote> <p>Since Windows lacks os.fork() it has a few extra restrictions:</p> </blockquote> <p>Then read the answers <a href="http://stackoverflow.com/questions/25391025/what-exactly-is-python-multiprocessing-modules-join-method-doing">here</a> that <code>join()</code> is for forked processed. </p> <p>I have always managed to run <code>multiprocessing</code> in a similar fashion to you without using <code>join()</code> and not seen any errors - I'm more than happy for a counterexample to explain why it's needed. Indeed, removing it has corrected your issue.</p> <p>And <a href="http://rhodesmill.org/brandon/2010/python-multiprocessing-linux-windows/" rel="nofollow">this article</a> goes into more depth about the differences with child processes in multiprocessing between operating systems. I do think that the issue with <code>join()</code>, specifically, should be more explicit in the documentation.</p>
1
2016-10-06T15:08:26Z
[ "python", "multithreading", "dictionary", "queue", "multiprocessing" ]
alternative reading binary in python instead of C++
39,896,826
<p>I have a binary file and C++ code which can read that binary file like follow.</p> <pre><code>int NumberOfWord; FILE *f = fopen("../data/vec.bin", "rb"); fscanf(f, "%d", &amp;NumberOfWord); cout &lt;&lt; NumberOfWord&lt; &lt;endl; </code></pre> <p>This output is:</p> <pre><code>114042 </code></pre> <p>I want to reimplement like above code in python.</p> <pre><code>with open("../data/vec.bin","rb") as f: b = f.read(8) print struct.unpack("d",b)[0] </code></pre> <p>but this code is not working. my output is:</p> <pre><code>8.45476330511e-53 </code></pre> <p>My question are:</p> <p>1) why integer has 8 byte in C++.</p> <p>I never knows %d means double. but, actually the variable has a type of integer, but normally we output using "%d" in C++. It is weird.</p> <p>2) How do I extract a real number in python</p> <p>I want to extract a real number like above C++ code in python code. How do I that??</p> <p>maybe, I misunderstand about struct module in python.</p>
1
2016-10-06T13:05:20Z
39,896,994
<p>In C format strings, <code>%d</code> is short for decimal.</p> <p>In Python, <code>d</code> is short for double.</p> <p>If it's an integer, you should use <code>i</code> in <code>struct.unpack</code> call.</p> <pre><code>with open("../data/vec.bin","rb") as f: b = f.read() print struct.unpack("i",b)[0] </code></pre>
0
2016-10-06T13:12:35Z
[ "python", "c++" ]
alternative reading binary in python instead of C++
39,896,826
<p>I have a binary file and C++ code which can read that binary file like follow.</p> <pre><code>int NumberOfWord; FILE *f = fopen("../data/vec.bin", "rb"); fscanf(f, "%d", &amp;NumberOfWord); cout &lt;&lt; NumberOfWord&lt; &lt;endl; </code></pre> <p>This output is:</p> <pre><code>114042 </code></pre> <p>I want to reimplement like above code in python.</p> <pre><code>with open("../data/vec.bin","rb") as f: b = f.read(8) print struct.unpack("d",b)[0] </code></pre> <p>but this code is not working. my output is:</p> <pre><code>8.45476330511e-53 </code></pre> <p>My question are:</p> <p>1) why integer has 8 byte in C++.</p> <p>I never knows %d means double. but, actually the variable has a type of integer, but normally we output using "%d" in C++. It is weird.</p> <p>2) How do I extract a real number in python</p> <p>I want to extract a real number like above C++ code in python code. How do I that??</p> <p>maybe, I misunderstand about struct module in python.</p>
1
2016-10-06T13:05:20Z
39,898,513
<p>As you have been able to read the file correctly with this C++ (or rather C) line, <code>fscanf(f, "%d", &amp;NumberOfWord);</code>, I assume that your file contains a text representation of 114042. So it contains the bytes</p> <p><code>0x31 0x31 0x34 0x30 0x34 0x32 ...</code> or <code>'1', '1', '4', '0', '4', '2', ...</code></p> <p>When you open it in a text editor, you can see one single line <code>114042</code>.</p> <p>Now when you try to read if as binary with <code>i</code> format, you use the 4 first bytes of the file and actually get <code>int('31313034', 16)</code>: 825308208. I could not reproduce what you get with <code>d</code> format for decoding it as double because I could not guess what comes in your file after the last digit...</p> <p>If the number is alone on first line, it is easy: just read one line and convert it to an int:</p> <pre><code>with open("../data/vec.bin","rb") as f: print int(f.readline()) </code></pre> <p>If there are other characters after the last digit, you will have to first use a regex (do not forget to import <code>re</code>) to get the numeric value and then convert it to an int:</p> <pre><code>with open("../data/vec.bin","rb") as f: line = f.readline() m = re.match(t'\s*\d*', line) print(int(m.group(0))) </code></pre> <p>TL/DR: Do not try to read a text file as if it contained a binary representation</p>
1
2016-10-06T14:20:19Z
[ "python", "c++" ]
Calling python from matlab
39,896,899
<p>I am using matlab 2016b and was excited to see that there is some python support in Matlab (<a href="https://uk.mathworks.com/help/matlab/matlab_external/call-python-from-matlab.html" rel="nofollow">https://uk.mathworks.com/help/matlab/matlab_external/call-python-from-matlab.html</a>)</p> <p>I was wondering if there is a way to expose user-designed python classes to Matlab. So, say I have a python class:</p> <pre><code>class MyPythonClass(object): def __init__(self): self.value = 5 def set_value(self, v): self.value = v </code></pre> <p>Could this simple python class be somehow exposed to Matlab in the newer versions of Matlab? I see python support but no mention of any matlab to python bridge. </p>
2
2016-10-06T13:08:15Z
39,898,393
<p>Yes sure! I agree that the documentation could be slightly better in that part, but anyways. Note that Python support has been available since MATLAB R2014b. So, first you should check that Python is available and you have the correct version installed:</p> <pre><code>pyversion </code></pre> <p>Next, create a Python file/module which contains your test class:</p> <pre><code># MyTestModule.py class MyPythonClass(object): def __init__(self): self.value = 5 def set_value(self, v): self.value = v </code></pre> <p>A very important step: we have to add the current MATLAB path to the Python path, so Python can find your module. This is documented <a href="https://mathworks.com/help/matlab/matlab_external/call-user-defined-custom-module.html" rel="nofollow">here</a>:</p> <pre><code>if count(py.sys.path,'') == 0 insert(py.sys.path,int32(0),''); end </code></pre> <p>Now we're ready to our own Python class! All Python commands start with <code>py.</code>, so we create an instance of our class with</p> <pre><code>c = py.MyTestModule.MyPythonClass </code></pre> <p>which shows</p> <pre><code>c = Python MyPythonClass with properties: value: 5 &lt;MyTestModule.MyPythonClass object at 0x12b23cbd0&gt; </code></pre> <p>and our Python class can be used like a "normal" MATLAB class:</p> <pre><code>&gt;&gt; c.set_value(10) &gt;&gt; c.value ans = 10 &gt;&gt; set_value(c,5) &gt;&gt; c.value ans = 5 </code></pre>
1
2016-10-06T14:14:31Z
[ "python", "matlab" ]
Simple MLP time series training yields unexpeced mean line results
39,896,985
<p>I'm trying to play around with simple time series predictions. Given number of inputs (1Min ticks) Net should attempt to predict next one. I've trained 3 nets with different settings to illustrate my problem:</p> <p><a href="http://i.stack.imgur.com/F2JAw.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/F2JAw.jpg" alt="enter image description here"></a></p> <p>On the right you can see 3 trainer MLP's - randomly named and color coded, with some training stats. On the left - plot of predictions made by those nets and actual validation data in white. This plot was made by going through each tick of validation data (white), feeding 30|4|60 (Nancy|Kathy|Wayne) previous ticks to net and plotting what it will predict on place of current tick.</p> <p>Multilayer perceptron's settings (Nancy|Kathy|Wayne settings):</p> <p>Geometry: 2x30|4|60 input nodes -> 30|4|60 hidden layer nodes -> 2 outputs<br> Number of epochs: 10|5|10<br> Learning rate: 0.01<br> Momentum: 0.5|0.9|0.5<br> Nonlinearity: Rectify<br> Loss: Squared Error </p> <p>It seems that with more training applied - predictions are converging in to some kind of mean line, which is not what I was expecting at all. I was expecting predictions to stand somewhat close to validation data with some margin of error.<br> Am I picking wrong model, misunderstanding some core concepts of machine learning or doing something wrong in lasagne/theano?</p> <p>Quick links to most relevant (in my opinion) code parts: </p> <ul> <li><a href="https://gist.github.com/anonymous/198b260ed50195e1cf2b63ad3501cafd#file-neurobot-py-L57-L66" rel="nofollow">MLP Geometry definition</a></li> <li><a href="https://gist.github.com/anonymous/198b260ed50195e1cf2b63ad3501cafd#file-neurobot-py-L69-L103" rel="nofollow">Functions compilation</a></li> <li><a href="https://gist.github.com/anonymous/198b260ed50195e1cf2b63ad3501cafd#file-neurobot-py-L125-L210" rel="nofollow">Training and validation</a></li> <li><a href="https://gist.github.com/anonymous/198b260ed50195e1cf2b63ad3501cafd#file-guimodule-py-L1-L13" rel="nofollow">Instantiating MLP</a></li> <li><a href="https://gist.github.com/anonymous/198b260ed50195e1cf2b63ad3501cafd#file-csvparser-py-L20-L60" rel="nofollow">CSV training data parsing</a></li> </ul> <p>And here's full, more or less, sources: </p> <ul> <li><a href="https://gist.github.com/anonymous/077206b76b38d9dc30a751de2908cf23" rel="nofollow">Data used for training</a> in format - date;open;high;low;close;volume - only date, high and low are used </li> <li><a href="https://gist.github.com/anonymous/198b260ed50195e1cf2b63ad3501cafd#file-neurobot-py" rel="nofollow">MLP module</a> </li> <li>Gui module's relevant <a href="https://gist.github.com/anonymous/198b260ed50195e1cf2b63ad3501cafd#file-guimodule-py" rel="nofollow">MLP interaction parts</a> </li> </ul>
7
2016-10-06T13:12:17Z
39,947,694
<p>First of all, I want to commend you for usage non linear rectifying. According to what Geoffrey Hinton inventor of Boltzmann machine believe, non linear rectifier is a best feet for activities of human brain. </p> <p>But for other parts you've chosen I propose you to change NN architecture. For predictions of stock market you should use some recurrent NN: easiest candidates could be Elman or Jordan networks. Or you can try more complicated, like LSTM network. </p> <p>Another part of advice, I propose to modify what you feed in NN. In general, I recommend you to apply scaling and normalization. For example don't feed in NN raw price. Modify it in one of the following ways ( those proposals are not written in stone ): 1. feed in NN percentages of changes of price. 2. If you feed in NN 30 values, and want to predict two values, then subtract from 30 + 2 values minimums of all 32 values, and try to predict 2 values, but basing on 30. Then just add to result the minimum of 32 values.</p> <p>Don't feed just dates in the NN. It says to NN nothing about making prediction. Instead feed in NN date and time as categorical value. Categorical means that you transform datetime in more then one entry. For example instead of giving to NN 2016/09/10 you can consider some of the following.</p> <ol> <li>year of trading most probably will not give any useful information. So you can omit year of trading.</li> <li>09 stands for number of month or about September. You have choice either feed in NN number of month, but I strongly recommend you make 12 inputs in NN, and in case of January give at first NN input 1, and zeros for other eleven. In this way you'll train your network to separate trading period in January from trading period in June or December. Also I propose to do categorical input of day of week in the same way. Because trading in Monday differs from trading on Friday, especially in the day of NFP. </li> <li>For hours I propose to use encoding by periods of 6 - 8 hours. It will help you to train network to take into account different trading sessions: Asia, Frankfurt, London, New-York.</li> <li>If you decide to feed in NN some indicators then for some indicators consider thermometer encoding. As usually thermometer encoding is needed for indicators like ADX.</li> </ol> <p>According to your question in comments about how to use minimum I'll give you simplified example. Let's say you want to use for training NN following close prices for eur/usd:<br/> 1.1122, 1.1132, 1.1152, 1.1156, 1.1166, 1.1173, 1.1153, 1.1150, 1.1152, 1.1159. Instead of windows size for learning 30 I'll demonstrate learning with window size 3 ( just for simplicity sake ) and prediction window size 2.<br/> In total data used for prediction equals to 3. Output will be 2. For learning we will use first 5 values, or:<br/> 1.1122, 1.1132, 1.1152, 1.1156, 1.1166<br/> then another 5 values or:<br/> 1.1132, 1.1152, 1.1156, 1.1166, 1.1173<br/> In the first window minimal value is: 1.1122.<br/> Then you subtract 1.1122 from each value:<br/> 0, 0.002, 0.003, 0.0033, 0.0034. As input you feed in NN 0, 0.002, 0.003. As output from NN you expect 0.0033, 0.0034. If you want to make it learn much faster, feed in NN normalized and scaled values. Then each time you'll need to make de-normalization and de-scaling of inputs. <br/><br/></p> <p>Another way, feed in NN percentage of changes of price. Let me know if you need sample for it.<br/><br/></p> <p>And one more important piece of advice. Don't use just NN for making trading. Never!!! Better way to do it is invent some system with some percentage of success. For example 30%. Then use NN in order to increase success percentage of success to 60%. <br/><br/></p> <p>I also want to provide for you also example of thermometer encoding for some indicators. Consider ADX indicator and following examples:<br/><br/></p> <p>a.>10 >20 >30 >40 <br /> 1 0 0 0<br /> b. >10 >20 >30 >40<br /> 1 1 0 0<br /> example a provides input in NN with ADX greater then 10. Example b provides input in NN with ADX greater then 20. <br/> You can modify thermometer encoding for providing inputs for stochastic. As usually stochastic has meaning in ranges 0 - 20, and 80 - 100 and in seldom cases in range 20 - 80. But as always you can try and see.</p>
2
2016-10-09T19:32:02Z
[ "python", "neural-network", "deep-learning", "theano", "lasagne" ]
Make a filter to one color
39,896,995
<p>I tried to make a function to detect some word from browser. My current solution is take the screenshot in location where the text can appear.</p> <pre><code> im = ImageGrab.grab(bbox=(1229, 11, 1233, 20)) im = im.convert('1') pixels = im.getdata() </code></pre> <p>But, it work with only small picture what capture by <code>grab</code> function. And, the text i want to detect have an unique color. So, have anyway to make a filter can make all diffrent colors disappear and show only white and that text?</p>
0
2016-10-06T13:12:36Z
39,900,753
<p>You can use filtering on each point of image using the code below:</p> <pre><code>output = pixels.point(lambda x: 1 if x==REQUIREDCOLOR else 0, '1') </code></pre>
0
2016-10-06T16:03:23Z
[ "python", "python-imaging-library" ]
Pass data from a template tag to a django view
39,897,013
<p>I'd like to pass a parameter with data, like category_id=2 from my template to the view. Here is how I think it should work (which obviously doesn't)...</p> <p>The view </p> <pre><code>def category_detail(request, category_id): return_list = Category.objects.filter(category_id=category_id) return render(request, 'expense_list.html', { 'expense_list' : return_list }) </code></pre> <p>HTML in the template:</p> <pre><code>&lt;a href="{% url 'category_detail' category_id=2 %}"&gt;Blah&lt;/a&gt; </code></pre> <p>Urls file:</p> <pre><code>url(r'^detail/(?P&lt;category_id&gt;[0-9]+)/$', views.category_detail, name='category_detail'), </code></pre>
0
2016-10-06T13:13:27Z
39,897,399
<p>You can build a list of urls by doing something like:</p> <pre><code>{% for category in expense_list.all %} &lt;a href="{% url 'app_label:view_name' category_id=category.id %}"&gt;{{ category.name }}&lt;/a&gt; {% endfor %} </code></pre> <p>Where app_label is the label/name of the app and view_name in this case category_detail.</p>
0
2016-10-06T13:30:00Z
[ "python", "django" ]
Python: If Condition then skip to return
39,897,333
<p>I wondered if there is a nice way to tell the python interpreter to <strong>skip to the next/last return statement of a function</strong>.</p> <p>Lets assume the following dummy code:</p> <pre class="lang-py prettyprint-override"><code>def foo(bar): do(stuff) if condition: do(stuff) if condition2: do(stuff) if condition3: ... return (...) </code></pre> <p>Sometimes this gets really messy with many conditions that i cant chain because they rely on on the block <code>do(stuff)</code> above. I could now do this:</p> <pre class="lang-py prettyprint-override"><code>def foo(bar): do(stuff) if not condition: return (...) do(stuff) if not condition2: return (...) do(stuff) if not condition3: return (...) ... return (...) </code></pre> <p>It looks a little less messy but i would have to repeat the return statement again and again which is somwhat anoying and if its a long tuple or similar it even looks worse. The perfect solution would be to say "if not condition, skip to the final return statement". Is this somehow possible?</p> <p><strong>edit:</strong> to make this clear: my goal is to improve readability while avoiding a drop in performance</p>
4
2016-10-06T13:26:55Z
39,897,500
<p>I think I would create a list of functions (I assume that all the <code>do(stuff)</code> in your example are actually different functions). Then you can use a <code>for</code> loop:</p> <pre><code>list_of_funcs = [func1, func2, func3] for func in list_of_funcs: func(stuff) if not condition: break return (...) </code></pre> <p>If the conditions are different then you can also create a list of conditions (which will be a list of functions that return <code>True</code> or <code>False</code>), then you can use <code>zip</code> in the following manner:</p> <pre><code>list_of_funcs = [func1, func2, func3] list_of_conditions = [cond1, cond2, cond3] for func, cond in zip(list_of_funcs, list_of_conditions): func(stuff) if not cond(): break return (...) </code></pre> <p>This way your actual code stays the same length and in the same indentation level, no matter how many functions and conditions you may have.</p>
5
2016-10-06T13:34:03Z
[ "python", "return", "indentation" ]
Python: If Condition then skip to return
39,897,333
<p>I wondered if there is a nice way to tell the python interpreter to <strong>skip to the next/last return statement of a function</strong>.</p> <p>Lets assume the following dummy code:</p> <pre class="lang-py prettyprint-override"><code>def foo(bar): do(stuff) if condition: do(stuff) if condition2: do(stuff) if condition3: ... return (...) </code></pre> <p>Sometimes this gets really messy with many conditions that i cant chain because they rely on on the block <code>do(stuff)</code> above. I could now do this:</p> <pre class="lang-py prettyprint-override"><code>def foo(bar): do(stuff) if not condition: return (...) do(stuff) if not condition2: return (...) do(stuff) if not condition3: return (...) ... return (...) </code></pre> <p>It looks a little less messy but i would have to repeat the return statement again and again which is somwhat anoying and if its a long tuple or similar it even looks worse. The perfect solution would be to say "if not condition, skip to the final return statement". Is this somehow possible?</p> <p><strong>edit:</strong> to make this clear: my goal is to improve readability while avoiding a drop in performance</p>
4
2016-10-06T13:26:55Z
39,897,551
<p>Refactoring your code is a <em>much</em> better idea than what I am about to suggest, but this is an option.</p> <pre><code>class GotoEnd(Exception): pass def foo(bar): try: do(stuff) if not condition: raise GotoEnd do(stuff) if not condition2: raise GotoEnd do(stuff) if not condition3: raise GotoEnd ... except GotoEnd: pass return (...) </code></pre>
0
2016-10-06T13:36:36Z
[ "python", "return", "indentation" ]
Insert data row-wise instead of column-wise and 1 blank row after each record
39,897,370
<p>Here is my code:</p> <pre><code>wb = Workbook() dest_filename = 'book.xlsx' th_list = ["this", "that", "what", "is", "this"] ws1 = wb.active ws1.title = 'what' for row in range(1, 2): for col in range(1, len(th_list)): _ = ws1.cell(column=col, row=row, value="{0}".format(th_list[col].encode('utf-8'))) wb.save(filename = dest_filename) </code></pre> <p>After running the py file I get the data this way:</p> <pre><code> A B C D E 1 this that what is this </code></pre> <p>While I want the data this way:</p> <pre><code> A 1 this 2 that 3 what 4 is 5 this </code></pre> <p>and also insert 1 empty row between each row like this:</p> <pre><code> A 1 this 2 3 that 4 5 what 6 7 is 8 9 this </code></pre> <p>I am trying to change my code to fulfill the requirement. I will also post my code as answer if I find the solution.</p> <p><strong>EDIT:</strong> Okay I have successfully converted data from row-wise into column-wise with modifying for loops. But still unable to add empty rows after each record. Here is the code:</p> <pre><code>wb = Workbook() dest_filename = 'book.xlsx' th_list = ["this", "that", "what", "is", "this"] ws1 = wb.active ws1.title = 'what' for col in range(1, 2): for row in range(1, len(th_list)+1): _ = ws1.cell(column=col, row=row, value="{0}".format(th_list[row-1].encode('utf-8'))) wb.save(filename = dest_filename) </code></pre>
-1
2016-10-06T13:28:36Z
39,897,834
<p>Why are you writing something so incredibly complicated?</p> <pre><code>for v in th_list: ws.append([v]) # pad as necessary, never encode ws.append() # blank row </code></pre>
0
2016-10-06T13:50:51Z
[ "python", "python-2.7", "openpyxl" ]
Insert data row-wise instead of column-wise and 1 blank row after each record
39,897,370
<p>Here is my code:</p> <pre><code>wb = Workbook() dest_filename = 'book.xlsx' th_list = ["this", "that", "what", "is", "this"] ws1 = wb.active ws1.title = 'what' for row in range(1, 2): for col in range(1, len(th_list)): _ = ws1.cell(column=col, row=row, value="{0}".format(th_list[col].encode('utf-8'))) wb.save(filename = dest_filename) </code></pre> <p>After running the py file I get the data this way:</p> <pre><code> A B C D E 1 this that what is this </code></pre> <p>While I want the data this way:</p> <pre><code> A 1 this 2 that 3 what 4 is 5 this </code></pre> <p>and also insert 1 empty row between each row like this:</p> <pre><code> A 1 this 2 3 that 4 5 what 6 7 is 8 9 this </code></pre> <p>I am trying to change my code to fulfill the requirement. I will also post my code as answer if I find the solution.</p> <p><strong>EDIT:</strong> Okay I have successfully converted data from row-wise into column-wise with modifying for loops. But still unable to add empty rows after each record. Here is the code:</p> <pre><code>wb = Workbook() dest_filename = 'book.xlsx' th_list = ["this", "that", "what", "is", "this"] ws1 = wb.active ws1.title = 'what' for col in range(1, 2): for row in range(1, len(th_list)+1): _ = ws1.cell(column=col, row=row, value="{0}".format(th_list[row-1].encode('utf-8'))) wb.save(filename = dest_filename) </code></pre>
-1
2016-10-06T13:28:36Z
39,913,364
<p>I have found the solution to both of my queries myself. Here it is:</p> <pre><code>wb = Workbook() dest_filename = 'book.xlsx' th_list = ["this", "that", "what", "is", "this"] ws1 = wb.active ws1.title = 'what' for col in range(1, 2): for row in range(1, len(th_list)+1): _ = ws1.cell(column=col, row=(row*2)-1, value="{0}".format(th_list[row-1].encode('utf-8'))) wb.save(filename = dest_filename) </code></pre>
0
2016-10-07T08:58:43Z
[ "python", "python-2.7", "openpyxl" ]
Python and Node.js on Heroku
39,897,505
<p>I have started to make a Node server which runs on Heroku. It was working fine until I tried to use the (unofficial) Duolingo API. I wrote the following Python script to connect to the API:</p> <pre><code>import duolingo import simplejson as json lingo = duolingo.Duolingo('harleyrowland') print json.dumps(lingo.get_user_info()) </code></pre> <p>and my Node server uses it using the following commands:</p> <pre><code>var python = require('python-shell'); module.exports = { getData: function(callback){ python.run('duoScript.py', function (err, results) { console.log(err); console.log(results); var res = JSON.parse(results); var language = res.language_data.es.language_string; var streak = res.language_data.es.streak; var level = res.language_data.es.level; var levelPerecentage = res.language_data.es.level_percent; var fluency = res.language_data.es.fluency_score; var nextLesson = res.language_data.es.next_lesson.skill_title; return callback({language, streak, level, levelPerecentage, fluency, nextLesson}); }); } } </code></pre> <p>which all works totally fine locally. </p> <p>When I pushed this to Heroku, the code didn't work and I started to get the following error in the Heroku logs:</p> <pre><code>{ [Error: ImportError: No module named duolingo] 2016-10-06T00:02:32.133315+00:00 app[web.1]: traceback: 'Traceback (most recent call last):\n File "duoScript.py", line 1, in &lt;module&gt;\n import duolingo\nImportError: No module named duolingo\n', executable: 'python', options: null, script: 'duoScript.py', args: null, exitCode: 1 } </code></pre> <p>Because of this, I went on the <a href="https://devcenter.heroku.com/articles/python-pip#the-basics" rel="nofollow">Heroku API</a> and found that I needed to add a requirements.txt file. So I did:</p> <pre><code>duolingo-api==0.3 simplejson==3.8.2 </code></pre> <p>which still didn't work. I then found <a href="http://stackoverflow.com/questions/36167012/node-app-with-python-module-in-project-on-heroku-not-installing">this</a> answer and added a .buildpacks file:</p> <pre><code>https://github.com/heroku/heroku-buildpack-python.git https://github.com/heroku/heroku-buildpack-nodejs.git </code></pre> <p>and I still get the same error. </p> <p>Any idea what is causing this error?</p> <h1>Update 1</h1> <p>Thought I would show my Procfile too incase this was the problem:</p> <pre><code>web: node index.js pipinstall: pip install -r requirements.txt </code></pre> <h1>Update 2</h1> <p>Output of <code>git push heroku master</code> without <code>pipinstall</code>:</p> <pre><code>$ git push heroku master Counting objects: 3, done. Delta compression using up to 4 threads. Compressing objects: 100% (2/2), done. Writing objects: 100% (3/3), 288 bytes | 0 bytes/s, done. Total 3 (delta 1), reused 0 (delta 0) remote: Compressing source files... done. remote: Building source: remote: remote: -----&gt; Node.js app detected remote: remote: -----&gt; Creating runtime environment remote: remote: NPM_CONFIG_LOGLEVEL=error remote: NPM_CONFIG_PRODUCTION=true remote: NODE_ENV=production remote: NODE_MODULES_CACHE=true remote: remote: -----&gt; Installing binaries remote: engines.node (package.json): 5.9.1 remote: engines.npm (package.json): unspecified (use default) remote: remote: Downloading and installing node 5.9.1... remote: Using default npm version: 3.7.3 remote: remote: -----&gt; Restoring cache remote: Loading 2 from cacheDirectories (default): remote: - node_modules remote: - bower_components (not cached - skipping) remote: remote: -----&gt; Building dependencies remote: Installing node modules (package.json) remote: remote: -----&gt; Caching build remote: Clearing previous node cache remote: Saving 2 cacheDirectories (default): remote: - node_modules remote: - bower_components (nothing to cache) remote: remote: -----&gt; Build succeeded! remote: ├── [email protected] extraneous remote: ├── [email protected] extraneous remote: ├── [email protected] remote: ├── [email protected] remote: ├── [email protected] remote: ├── [email protected] remote: ├── [email protected] remote: └── [email protected] remote: remote: -----&gt; Discovering process types remote: Procfile declares types -&gt; web remote: remote: -----&gt; Compressing... remote: Done: 13M remote: -----&gt; Launching... remote: Released v25 remote: https://arcane-anchorage-33274.herokuapp.com/ deployed to Heroku remote: remote: Verifying deploy... done. </code></pre>
0
2016-10-06T13:34:22Z
39,947,385
<p>Try to remove the deprecated <a href="https://github.com/ddollar/heroku-buildpack-multi" rel="nofollow">heroku-buildpack-multi</a> and use the Heroku <a href="https://devcenter.heroku.com/articles/using-multiple-buildpacks-for-an-app" rel="nofollow"><code>buildpacks</code></a> command:</p> <pre><code>$ heroku buildpacks:set heroku/nodejs $ heroku buildpacks:add --index 1 heroku/python </code></pre>
1
2016-10-09T19:01:49Z
[ "python", "node.js", "heroku" ]
Unable to set manual scaling on a google app engine service
39,897,559
<p>I am unable to set manual scaling on a google app engine service (Previously called module). Using python on app engine. </p> <p><strong><em>app.yaml:</em></strong></p> <pre><code>application: xxx-xxxx version: 2 runtime: python27 module: xxbackend instance_class: F4 api_version: 1 threadsafe: true handlers: - url: /taskcontroller\.py script: TaskController.app so on... libraries: - name: webapp2 version: latest - name: numpy version: "1.6.1" - name: PIL version: latest inbound_services: - warmup </code></pre> <p><strong><em>xxbackend.yaml:</em></strong></p> <pre><code>application: xxx-xxxx version: uno module: xxbackend runtime: python27 api_version: 1 instance_class: B4 manual_scaling: instances: 5 </code></pre> <p>Even though I have specified instance class and manual scaling settings in xxbackend.yaml, the xxbackend instances are still autoscaled. Can someone point out where I am going wrong?</p>
2
2016-10-06T13:36:53Z
39,899,666
<p>You have the same <code>module:</code> name is both yamls. <code>app.yaml</code> should not specify a module, so it uses the <code>default</code> module. So remove <code>module: xxbackend</code> from <code>app.yaml</code>. Otherwise, you are overriding the expected config.</p> <p>Then, when you deploy, use a command like:</p> <p><code>appcfg.py update app.yaml xxbackend.yaml</code></p> <p>That deploys both updated yaml files.</p>
1
2016-10-06T15:11:28Z
[ "python", "python-2.7", "google-app-engine" ]
Convert a string with ns precision to datetime in a panda dataframe
39,897,698
<p>I'm having a hard time converting a string with ns precision in a datetime format in a panda dataframe.</p> <p>I have a data frame like the following :</p> <pre><code>print df Event Time 0 A 08:00:00.123456789 1 B 08:00:00.234567890 2 C 08:00:00.345678901 </code></pre> <p>I would like to convert the Time column from string to datetime without losing the ns precision. I tried following :</p> <pre><code>df['Time'] = pd.to_datetime(df['Time']) </code></pre> <p>but when I print the <code>df</code> I see that I only have up to <code>us</code> precision.</p> <p><code>df['Time'] = df['Time'].astype('datetime64[ns]')</code> </p> <p>but here I get an error like </p> <blockquote> <p>"Error parsing datetime string "08:00:00.345678901" at position 2"</p> </blockquote>
2
2016-10-06T13:44:09Z
39,899,576
<p>The following did the trick for me:</p> <pre><code>&gt;&gt;&gt; df['Time'] = pd.to_datetime(df['Time'], format='%H:%M:%S.%f') &gt;&gt;&gt; df Event Time 0 A 1900-01-01 08:00:00.123456789 1 B 1900-01-01 08:00:00.234567890 2 C 1900-01-01 08:00:00.345678901 </code></pre> <p>As noted in the <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html" rel="nofollow">documentation for <code>pd.to_datetime</code></a> concerning the <code>format</code> argument:</p> <blockquote> <p>strftime to parse time, eg “%d/%m/%Y”, <strong>note that “%f” will parse all the way up to nanoseconds</strong>.</p> </blockquote>
0
2016-10-06T15:07:45Z
[ "python", "pandas" ]
PyBluez doesn'y find a nBlue device
39,897,711
<p>I am trying to connect though Python BlueZ using the Linux Bluetooth stach to a small round nBlue device which works on Bluetooth, but the python program only finds devices like my phone or other laptops. What could be a potential problem?</p>
0
2016-10-06T13:44:49Z
39,984,040
<p>Your python programming is scanning for normal Bluetooth devices. You have to make it scan for BLE devices to see your small round nBlue device.</p> <p>For example, on my Raspberry Pi 3 with BlueZ installed:</p> <pre><code>sudo hcitool scan </code></pre> <p>sees <em>only</em> 'normal' bluetooth devices like phones, whereas:</p> <pre><code>sudo hcitool lescan </code></pre> <p>sees <em>only</em> BLE Bluetooth devices.</p> <p>Your python program has to scan specifically for BLE devices. In bluepy this is the <code>Scanner</code> class see <a href="http://ianharvey.github.io/bluepy-doc/scanner.html" rel="nofollow">HERE</a> for docs including this example (haven't run it but looks plausible):</p> <pre><code>from bluepy.btle import Scanner, DefaultDelegate class ScanDelegate(DefaultDelegate): def __init__(self): DefaultDelegate.__init__(self) def handleDiscovery(self, dev, isNewDev, isNewData): if isNewDev: print "Discovered device", dev.addr elif isNewData: print "Received new data from", dev.addr scanner = Scanner().withDelegate(ScanDelegate()) devices = scanner.scan(10.0) for dev in devices: print "Device %s (%s), RSSI=%d dB" % (dev.addr, dev.addrType, dev.rssi) for (adtype, desc, value) in dev.getScanData(): print " %s = %s" % (desc, value) </code></pre>
0
2016-10-11T18:20:25Z
[ "python", "bluetooth", "iot", "bluez", "pybluez" ]
Python-Create array from txt
39,897,913
<p>I'm trying to create an array of stock tickers in Python 2.7 from a txt file. The txt file simply has 1 ticker per line like:</p> <pre><code>SRCE ABTX AMBC ATAX </code></pre> <p>The code I'm using looks like:</p> <pre><code>FinTick= [] def parseRus(): try: readFile=open(r'filename.txt','r').read() splitFile=readFile.split('\n') FinTick.append(splitFile) print FinTick except Exception, e: print str(e) </code></pre> <p>When I call 'parseRus()' I get an output that looks like:</p> <pre><code>'\xff\xfeS\x00R\x00C\x00E\x00\r\x00', '\x00A\x00B\x00T\x00X\x00\r\x00', '\x00A\x00M\x00B\x00C\x00\r\x00', '\x00A\x00T\x00A\x00X\x00\r\x00' </code></pre> <p>The correct letters are present but not printing in plane text. I've used a couple other logic methods to populate the array but still get the same output format.</p>
2
2016-10-06T13:54:37Z
39,898,102
<pre><code>&gt;&gt;&gt; tickers = [] &gt;&gt;&gt; with open("filename.txt", "r") as f: for ticker in f.readlines(): tickers.append(ticker.strip()) &gt;&gt;&gt; tickers ['SRCE', 'ABTX', 'AMBC', 'ATAX'] </code></pre> <p>Try using <code>readlines()</code> and <code>strip()</code> instead.</p> <p>Edit: Some clarity around <code>f.readlines()</code> and <code>strip()</code>:</p> <pre><code>&gt;&gt;&gt; with open("filename.txt", "r") as f: print(f.readlines()) ['SRCE\n', 'ABTX\n', 'AMBC\n', 'ATAX'] </code></pre> <p>So, when we're iterating through the <code>list</code> object returned by <code>f.readlines()</code>, we will need to strip the newline <code>\n</code> characters. Use the <code>strip()</code> method for <code>str</code> types to do this.</p> <p>Edit 2: @Eli is right. We can just use <code>for ticker in f</code> instead of <code>for ticker in f.readlines()</code>, too.</p> <pre><code>&gt;&gt;&gt; tickers = [] &gt;&gt;&gt; with open("filename.txt", "r") as f: for ticker in f: tickers.append(ticker.strip()) &gt;&gt;&gt; tickers ['SRCE', 'ABTX', 'AMBC', 'ATAX'] </code></pre>
2
2016-10-06T14:02:31Z
[ "python", "arrays", "python-2.7" ]
Python-Create array from txt
39,897,913
<p>I'm trying to create an array of stock tickers in Python 2.7 from a txt file. The txt file simply has 1 ticker per line like:</p> <pre><code>SRCE ABTX AMBC ATAX </code></pre> <p>The code I'm using looks like:</p> <pre><code>FinTick= [] def parseRus(): try: readFile=open(r'filename.txt','r').read() splitFile=readFile.split('\n') FinTick.append(splitFile) print FinTick except Exception, e: print str(e) </code></pre> <p>When I call 'parseRus()' I get an output that looks like:</p> <pre><code>'\xff\xfeS\x00R\x00C\x00E\x00\r\x00', '\x00A\x00B\x00T\x00X\x00\r\x00', '\x00A\x00M\x00B\x00C\x00\r\x00', '\x00A\x00T\x00A\x00X\x00\r\x00' </code></pre> <p>The correct letters are present but not printing in plane text. I've used a couple other logic methods to populate the array but still get the same output format.</p>
2
2016-10-06T13:54:37Z
39,900,261
<p>I finally figured a fix.</p> <p>I had to modify the text file from 1 column to 1 row then saved as a .csv and modified the code to:</p> <pre><code>FinTick= [] def parseRus(): try: readFile=open(r'filename.csv','r').read() splitFile=readFile.split(',') for eachLine in splitFile: splitLine=eachLine.split(',') ticker=splitLine[0] FinTick.append(ticker.strip()) except Exception, e: print str(e) </code></pre>
0
2016-10-06T15:39:26Z
[ "python", "arrays", "python-2.7" ]
I am having diffculty to understand this program
39,897,974
<p>i just came across this program and it seems to me very difficult to understand. which is calculating the Fibonacci boundary for a positive number, returns a 2-tuple. The first element is the Largest Fibonacci Number smaller than x and the second component is the Smallest Fibonacci Number larger than x. The return value is immediately stored via unpacking into the variables lub and sup:</p> <pre><code>def fib_intervall(x): """ returns the largest fibonacci number smaller than x and the lowest fibonacci number higher than x""" if x &lt; 0: return -1 (old,new, lub) = (0,1,0) while True: if new &lt; x: lub = new (old,new) = (new,old+new) else: return (lub, new) while True: x = int(input("Your number: ")) if x &lt;= 0: break (lub, sup) = fib_intervall(x) print("Largest Fibonacci Number smaller than x: " + str(lub)) print("Smallest Fibonacci Number larger than x: " + str(sup)) </code></pre> <p>I am trying to understand but i am lacking somewhere to understand it properly some big doubts:</p> <p>why its returning -1 ? what this line <code>(old,new, lub) = (0,1,0)</code> doing ?? what this piece of code intend to do ? </p> <pre><code> if new &lt; x: lub = new (old,new) = (new,old+new) else: return (lub, new) </code></pre> <p>How this assignment works in python ?? <code>(lub, sup) = fib_intervall(x)</code></p> <p>overall if you explain whole program with deep explanation that would be so helpful.</p> <p>Thanks in advance.</p>
-2
2016-10-06T13:57:30Z
39,898,202
<blockquote> <p>Why is it returning -1</p> </blockquote> <p>It validates the input. There is no sensible result if <code>x</code> is less than zero so in that case it returns -1 which will cause the calling code to throw an exception when it fails to unpack the result. This is poor code, it would be much more normal in Python to throw a meaningful exception directly such as <code>ValueError</code> if the arguments are invalid.</p> <pre><code>(old,new, lub) = (0,1,0) </code></pre> <p>would more usually be written as:</p> <pre><code>old, new, lub = 0, 1, 0 </code></pre> <p>as the parentheses are redundant here. It simply assigns to all three variables in parallel so in this case it is a shorthand for:</p> <pre><code>old = 0 new = 1 lub = 0 </code></pre> <p>But in this case:</p> <pre><code>(old,new) = (new,old+new) </code></pre> <p>this would be equivalent to:</p> <pre><code>tmp = old + new old = new new = tmp </code></pre> <p>The shorthand works out the values before it does the assignment so if you are updating existing variables with an expression that depends on their current value it allows you to avoid using a temporary variable to store the intermediate result. Again you can omit the parentheses:</p> <pre><code>old, new = new, old+new </code></pre> <p>Internally these compound assignments work by creating a tuple and then unpacking it into the values named on the left hand side. You must have the same number of elements on both sides.</p> <pre><code>(lub, sup) = fib_intervall(x) </code></pre> <p>This is just another unpacking assignment. The only difference here is that instead of specifying the tuple on the right hand side as a literal value it is returned from a function call.</p> <p>There is nothing special here about it being a tuple, you can use an unpacking assignment on any sequence so long as the sequence contains the correct number of elements. If you have a varying number of elements then in Python 3 you can use the star operator to pick up any extras in a list. So here using a string for the sequence:</p> <pre><code>&gt;&gt;&gt; a, b, *c = "hello" &gt;&gt;&gt; print(a, b, c) h e ['l', 'l', 'o'] &gt;&gt;&gt; a, *b, c = "hello" &gt;&gt;&gt; print(a, b, c) h ['e', 'l', 'l'] o </code></pre>
1
2016-10-06T14:06:18Z
[ "python", "python-2.7", "python-3.x" ]
I am having diffculty to understand this program
39,897,974
<p>i just came across this program and it seems to me very difficult to understand. which is calculating the Fibonacci boundary for a positive number, returns a 2-tuple. The first element is the Largest Fibonacci Number smaller than x and the second component is the Smallest Fibonacci Number larger than x. The return value is immediately stored via unpacking into the variables lub and sup:</p> <pre><code>def fib_intervall(x): """ returns the largest fibonacci number smaller than x and the lowest fibonacci number higher than x""" if x &lt; 0: return -1 (old,new, lub) = (0,1,0) while True: if new &lt; x: lub = new (old,new) = (new,old+new) else: return (lub, new) while True: x = int(input("Your number: ")) if x &lt;= 0: break (lub, sup) = fib_intervall(x) print("Largest Fibonacci Number smaller than x: " + str(lub)) print("Smallest Fibonacci Number larger than x: " + str(sup)) </code></pre> <p>I am trying to understand but i am lacking somewhere to understand it properly some big doubts:</p> <p>why its returning -1 ? what this line <code>(old,new, lub) = (0,1,0)</code> doing ?? what this piece of code intend to do ? </p> <pre><code> if new &lt; x: lub = new (old,new) = (new,old+new) else: return (lub, new) </code></pre> <p>How this assignment works in python ?? <code>(lub, sup) = fib_intervall(x)</code></p> <p>overall if you explain whole program with deep explanation that would be so helpful.</p> <p>Thanks in advance.</p>
-2
2016-10-06T13:57:30Z
39,898,281
<pre><code>if x &lt; 0: return -1 </code></pre> <p>This is checking if the number is a positive integer bigger than one. Since Fib needs to be a positive integer. </p> <pre><code> if x &lt;= 0: break </code></pre> <p>Uses the above to check if it should print anything out (if there is a valid output to print out) If the input is not valid, it won't print anything out. </p> <pre><code> (old,new, lub) = (0,1,0) </code></pre> <p>Is a silly way to unpack the tuple <code>(0,1,0)</code> to the variables <code>old,new,lub</code>. The <code>(old,new,lub)</code> is a tuple of variables but we aren't interested in that. Since this code still work with just rewriting it to be:</p> <pre><code> old,new,lub = 0,1,0 </code></pre> <p>You can think of it as doing:</p> <pre><code> old = 0 new = 1 lub = 0 </code></pre> <p>Same thing in this case. </p> <p>The overall program just checks if there's a valid input and outputs the correct values according to what the strings says. </p> <pre><code>while True: if new &lt; x: lub = new (old,new) = (new,old+new) else: return (lub, new) </code></pre> <p>This is the heart of the program, it loops until <code>new</code> is smaller than <code>x</code>. If it's not it makes <code>lub</code> to the current <code>new</code> and just increment <code>old</code> and <code>new</code> to be the new values of <code>new</code> and <code>old+new</code>. In basic terms, it's doing calculation on what the biggest value and smallest number. Just read the code, it seems very self explaining after the first two questions </p> <pre><code>(old,new) = (new,old+new) </code></pre> <p>Is like above, where the <code>()</code> are useless here since it's not doing anything. The above can be rewritten or thought as </p> <pre><code>old = new new = old+new </code></pre> <p>Edited for more questions in Comments: </p> <pre><code>(lub, sup) = fib_intervall(x) </code></pre> <p>This is calling the function fib_intervalls, and unpacking the return values of what it returns <code>return (lub, new)</code>. Notice the function returns 2 variables in a tuple: <code>lub, new</code>. So when you call the function <code>fib_intervall(x)</code> it returns <code>(lub,new)</code> which is now unpacked and assign to <code>lub,sup</code>. Basically you can think of it like doing:</p> <pre><code>returned_values = fib_intervall(x) lub = returned_values[0] sup = returned_values[1] </code></pre> <p>This code is calling the function under the while condition because it wants the user to be able to loop and asking multiple inputs until an input is invalid. That's the point of functions, reuse able code. </p> <p>Also you only <code>def function():</code> when you are making a new function. Look at the first line of code:</p> <pre><code> def fib_intervall(x): </code></pre> <p>This is how you define a function, and to call it you simply use <code>fib_intervall(input)</code>. Make sure you get the return values like the script is or running the function here will be pointless. </p>
0
2016-10-06T14:09:09Z
[ "python", "python-2.7", "python-3.x" ]
I am having diffculty to understand this program
39,897,974
<p>i just came across this program and it seems to me very difficult to understand. which is calculating the Fibonacci boundary for a positive number, returns a 2-tuple. The first element is the Largest Fibonacci Number smaller than x and the second component is the Smallest Fibonacci Number larger than x. The return value is immediately stored via unpacking into the variables lub and sup:</p> <pre><code>def fib_intervall(x): """ returns the largest fibonacci number smaller than x and the lowest fibonacci number higher than x""" if x &lt; 0: return -1 (old,new, lub) = (0,1,0) while True: if new &lt; x: lub = new (old,new) = (new,old+new) else: return (lub, new) while True: x = int(input("Your number: ")) if x &lt;= 0: break (lub, sup) = fib_intervall(x) print("Largest Fibonacci Number smaller than x: " + str(lub)) print("Smallest Fibonacci Number larger than x: " + str(sup)) </code></pre> <p>I am trying to understand but i am lacking somewhere to understand it properly some big doubts:</p> <p>why its returning -1 ? what this line <code>(old,new, lub) = (0,1,0)</code> doing ?? what this piece of code intend to do ? </p> <pre><code> if new &lt; x: lub = new (old,new) = (new,old+new) else: return (lub, new) </code></pre> <p>How this assignment works in python ?? <code>(lub, sup) = fib_intervall(x)</code></p> <p>overall if you explain whole program with deep explanation that would be so helpful.</p> <p>Thanks in advance.</p>
-2
2016-10-06T13:57:30Z
39,901,687
<p>If you are wondering, the reason why it has two output parameters and one output is since two numbers are being generated inside the function itself.</p> <p>If I have said program:</p> <pre><code>def diameter(x): diameter = x * 2 return diameter, x diameter, radius = diameter(radius) </code></pre> <p>then two values, diameter and radius, are being returned, despite only one being inputted. To distinguish the inputted value, you can also rename it internally in the function, where x corresponds to the value of radius. This allows two variables to be defined from just one function.</p> <p>Also, for future reference, if you need to swap two values, then you can use:</p> <pre><code>value1, value2 = value2, value1 </code></pre> <p>which is just a simple way to swap values in one line.</p>
0
2016-10-06T16:56:14Z
[ "python", "python-2.7", "python-3.x" ]
Python Scipy Optimize with Lower bounds (instead of A_ub)
39,897,984
<p>I spent about 4-5 hours last night searching Stack Overflow, going through scipy optimize documents etc and could not find an answer to my problem. My question is, how do I set a lower bounds for the optimization equation when the option only seems to be for upper bound? Please see my equation and code below.</p> <pre><code>import numpy as np from scipy.optimize import linprog from numpy.linalg import solve c = np.array([4,7,5]) A = np.array([[4,1,10],[3,2,1],[0,4,5]]) b = np.array([10,12,20]) res = linprog(c,A_ub = A,b_ub = b) print(res) </code></pre> <h1>minimizing (4,7,5)</h1> <pre><code>('Optimal value:', -0.0, '\nX:', array([ 0., 0., 0.])) fun: -0.0 message: 'Optimization terminated successfully.' nit: 0 slack: array([ 10., 12., 20.]) status: 0 success: True x: array([ 0., 0., 0.]) </code></pre> <h1>maximizing (-4,-7,-5)</h1> <pre><code>('Optimal value:', -37.666666666666664, '\nX:', array([ 0.66666667, 5. ` , 0. ]))` fun: -37.666666666666664 message: 'Optimization terminated successfully.' nit: 2 slack: array([ 2.33333333, 0. , 0. ]) status: 0 success: True x: array([ 0.66666667, 5. , 0. ]) </code></pre> <p>It is giving me an answer in the first one to minimize x1,x2,x3 which obviously shows all zeros. The 2nd answer maximizes the function if each is &lt;=10,&lt;=12,&lt;=20 because obviously it is an upper bound. What I need is the best possible answer based on being >=10,>=12,>=20 minimizing on the function.</p> <p>Sorry if this is easy! I spent many hours crawling the web on this...</p>
0
2016-10-06T13:58:01Z
39,898,430
<p><code>a'x &gt;= b</code> is the same as <code>-a'x &lt;= -b</code>. I.e. multiply the <code>&gt;=</code> inequality by -1.</p>
0
2016-10-06T14:15:53Z
[ "python", "optimization" ]
Traversing json array in python
39,898,068
<p>I'm using urllib.request.urlopen to get a JSON response that looks like this:</p> <pre><code>{ "batchcomplete": "", "query": { "pages": { "76972": { "pageid": 76972, "ns": 0, "title": "Title", "thumbnail": { "original": "https://linktofile.com" } } } } </code></pre> <p>The relevant code to get the response:</p> <pre><code>response = urllib.request.urlopen("https://example.com?title="+object.title) data = response.read() encoding = response.info().get_content_charset('utf-8') json_object = json.loads(data.decode(encoding)) </code></pre> <p>I'm trying to retrieve the value of "original", but I'm having a hard time getting there. I can do <code>print(json_object['query']['pages']</code> but once I do <code>print(json_object['query']['pages'][0]</code> I run into a KeyError: 0.</p> <p>How would I be able to, with python retrieve the value of <code>original</code>?</p>
0
2016-10-06T14:01:15Z
39,898,142
<p>Do this instead:</p> <pre><code>my_content = json_object['query']['pages']['76972']['thumbnail']['original'] </code></pre> <p>The reason is, you need to mention <code>index</code> as <code>[0]</code> only when you have list as the object. But in your case, every item is of <code>dict</code> type. You need to specify <code>key</code> instead of <code>index</code></p> <p>If number is dynamic, you may do:</p> <pre><code>page_content = json_object['query']['pages'] for content in page_content.values(): my_content = content['thumbnail']['original'] </code></pre> <p>where <code>my_content</code> is the required information.</p>
2
2016-10-06T14:03:58Z
[ "python", "json", "django", "urllib" ]
Traversing json array in python
39,898,068
<p>I'm using urllib.request.urlopen to get a JSON response that looks like this:</p> <pre><code>{ "batchcomplete": "", "query": { "pages": { "76972": { "pageid": 76972, "ns": 0, "title": "Title", "thumbnail": { "original": "https://linktofile.com" } } } } </code></pre> <p>The relevant code to get the response:</p> <pre><code>response = urllib.request.urlopen("https://example.com?title="+object.title) data = response.read() encoding = response.info().get_content_charset('utf-8') json_object = json.loads(data.decode(encoding)) </code></pre> <p>I'm trying to retrieve the value of "original", but I'm having a hard time getting there. I can do <code>print(json_object['query']['pages']</code> but once I do <code>print(json_object['query']['pages'][0]</code> I run into a KeyError: 0.</p> <p>How would I be able to, with python retrieve the value of <code>original</code>?</p>
0
2016-10-06T14:01:15Z
39,898,148
<p>Doing <code>[0]</code> is looking for that key - which doesn't exist. Assuming you don't always know what the key of the page is, Try this:</p> <pre><code>pages = json_object['query']['pages'] for key, value in pages.items(): # this is python3 original = value['thumbnail']['original'] </code></pre> <p>Otherwise you can simply grab it by the key if you do know (what appears to be) the <code>pageid</code>:</p> <pre><code>json_object['query']['pages']['76972']['thumbnail']['original'] </code></pre>
0
2016-10-06T14:04:11Z
[ "python", "json", "django", "urllib" ]
Traversing json array in python
39,898,068
<p>I'm using urllib.request.urlopen to get a JSON response that looks like this:</p> <pre><code>{ "batchcomplete": "", "query": { "pages": { "76972": { "pageid": 76972, "ns": 0, "title": "Title", "thumbnail": { "original": "https://linktofile.com" } } } } </code></pre> <p>The relevant code to get the response:</p> <pre><code>response = urllib.request.urlopen("https://example.com?title="+object.title) data = response.read() encoding = response.info().get_content_charset('utf-8') json_object = json.loads(data.decode(encoding)) </code></pre> <p>I'm trying to retrieve the value of "original", but I'm having a hard time getting there. I can do <code>print(json_object['query']['pages']</code> but once I do <code>print(json_object['query']['pages'][0]</code> I run into a KeyError: 0.</p> <p>How would I be able to, with python retrieve the value of <code>original</code>?</p>
0
2016-10-06T14:01:15Z
39,898,166
<p>You can iterate over keys:</p> <pre><code>for page_no in json_object['query']['pages']: page_data = json_object['query']['pages'][page_no] </code></pre>
0
2016-10-06T14:05:06Z
[ "python", "json", "django", "urllib" ]
How to Login, Logout and User Registration through in build Authentication method?
39,898,103
<p>view.py</p> <pre><code>from django.contrib.auth import authenticate, login, logout from django.contrib.auth.decorators import login_required from django.contrib import messages # Create your views here. def signin(request): if request.method=='POST': username=request.POST['username'] password=request.POST['password'] user=authenticate(username=username,password=password) if user !=None: login(request,user) else: return HttpResponseRedirect('signin') else: messages.add_message(request, messages.ERROR, "Incorrect user or password") return render(request,'customer/login.html') def signout(request): logout(request) @login_required(login_url='customer/login.html') def createcustomer(request): if request.method == 'POST': form = CustomerForm(request.POST) if form.is_valid(): customer_save=Customer.objects.create( fname=form.cleaned_data['fname'], lname = form.cleaned_data['lname'], email= form.cleaned_data['email'], address= form.cleaned_data['address'], city=form.cleaned_data['city'], state=form.cleaned_data['state'], zip=form.cleaned_data['zip'], uname=form.cleaned_data['uname'], password=form.cleaned_data['password'], age=form.cleaned_data['age'], mobile=form.cleaned_data['mobile'], phone=form.cleaned_data['phone'], ) customer_save.save() return HttpResponseRedirect('thanks') else: form = CustomerForm() return render(request, 'customer/createcustomer.html', {'form': form}) </code></pre> <p>login.html</p> <pre><code> &lt;!DOCTYPE html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;meta charset="UTF-8"&gt; &lt;title&gt;Edit Custmer Tasks&lt;/title&gt; &lt;meta name="viewport" content="width=device-width, initial-scale=1"&gt; &lt;link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"&gt; &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"&gt;&lt;/script&gt; &lt;script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"&gt;&lt;/script&gt; &lt;title&gt;Login&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;div class="container-fluid" style="background-color: #f2f2f2;border:solid;" &gt; &lt;div class="col-md-4"&gt;&lt;/div&gt; &lt;div class="col-md-4"&gt; &lt;form class="login-page" method="post" action=""&gt; &lt;div class="input-group margin-bottom-20"&gt; &lt;span class="input-group-addon"&gt; &lt;i class="fa fa-user"&gt;&lt;/i&gt; &lt;/span&gt; &lt;input type="text" name="username" class="form-control" placeholder="Username/Email"&gt; &lt;/div&gt; &lt;div class="input-group margin-bottom-20"&gt; &lt;span class="input-group-addon"&gt; &lt;i class="fa fa-lock"&gt;&lt;/i&gt; &lt;/span&gt; &lt;input type="password" name="password" class="form-control" placeholder="Password"&gt; &lt;/div&gt; &lt;div class="row"&gt; &lt;div class="col-md-6"&gt; &lt;label class="checkbox"&gt; &lt;input type="checkbox"&gt;Stay signed in&lt;/label&gt; &lt;/div&gt; &lt;div class="col-md-6"&gt; &lt;button class="btn btn-primary pull-right" type="submit"&gt;Login&lt;/button&gt; &lt;/div&gt; &lt;/div&gt; &lt;/form&gt; &lt;/div&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>url.py</p> <pre><code>from views import signin from django.contrib.auth import views as auth_views from django.conf.urls import url from django.contrib.auth.views import login from views import createcustomer, customerlist, customerdetails,thanks, editcustomer, createtasks, listtasks, edittasks, viewtasks, customertable, tasktable from views import signin from django.contrib.auth import views as auth_views urlpatterns = [ url(r'^signin$', signin, name="signin"), url(r'^customer/login/$', auth_views.login), #url(r'^login/$', login, name="login"), url(r'^create/$', createcustomer, name="createcustomer"), url(r'^list/$', customerlist, name="customerlist"), url(r'^edit/(?P&lt;pk&gt;[0-9]+)/', editcustomer, name="editcustomer"), url(r'^view/(?P&lt;id&gt;[0-9]+)/', customerdetails, name="customerdetails"), ...... ] </code></pre> <p>What I am Doing is: I want to add a customer from a web page to database, but i want that only registerd person can post the Customer details in database. So i want to add new authenticate user using authnticate method. Login the authenticate user, then uthenticate user cand add after login.</p> <p>Basically i want a simple sign in, sign out and registrasion using Authentication. Please comment or send me mail ([email protected]) if you want other code</p>
2
2016-10-06T14:02:32Z
39,917,110
<blockquote> <p>Use this code for signin in views.py file</p> </blockquote> <pre><code>def signin(request): if request.method=='POST': username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username, password=password) if user is not None: login(request, user) return HttpResponseRedirect('/customer/create/') else: return render(request, 'customer/createcustomer.html', { "user": user}) else: user=UserForm() return render(request, 'customer/login.html', {"user": user, }) </code></pre>
3
2016-10-07T12:16:59Z
[ "python", "django" ]
No module named statistics.distributions
39,898,133
<p>I was trying to use Sympy stats library when i encountered this problem:</p> <pre><code>&gt;&gt;&gt; from sympy.statistics.distributions import Sample Traceback (most recent call last): File "&lt;string&gt;", line 1, in &lt;module&gt; ImportError: No module named statistics.distributions </code></pre> <p>The problem is not only in my system as the same happened in their SymPy Live Shell. You can see it <a href="http://docs.sympy.org/0.7.2/modules/statistics.html#sample" rel="nofollow">here</a>. Can you please help me fix this.</p>
2
2016-10-06T14:03:30Z
39,923,316
<p><code>sympy.statistics</code> has been removed in favor of <code>sympy.stats</code>. Here is the documentation: <a href="http://docs.sympy.org/latest/modules/stats.html" rel="nofollow">http://docs.sympy.org/latest/modules/stats.html</a>. </p> <p>For producing the mean of a list of numbers, you can use <code>DiscreteUniform</code>:</p> <pre><code>In [8]: from sympy.stats import DiscreteUniform, E In [9]: X = DiscreteUniform("X", [1, 2, 3]) In [10]: E(X) Out[10]: 2 </code></pre>
3
2016-10-07T17:59:50Z
[ "python", "python-3.x", "statistics", "sympy" ]
simplify numpy array representation of image
39,898,151
<p>I have an image, read into <code>np.array</code> by PIL. In my case, it's a<code>(1000, 1500)</code> <code>np.array</code>.</p> <p>I'd like to simplify it for visualisation purposes. By simplification, I following transformation from this matrix</p> <pre><code>1 1 1 1 0 0 1 0 1 0 0 0 </code></pre> <p>to </p> <pre><code>1 1 0 </code></pre> <p>so, essentially, look at every <code>2*2</code> sample, if it satisfies some criteria, like more than 50% of 1's -> count it as a 1, if not, count is as a 0.</p> <p>I don't know how to call it properly, but I believe there should be some well known mathematic procedure for doing so.</p>
0
2016-10-06T14:04:30Z
39,898,302
<p>Use a combination of <code>np.reshape()</code> and <code>np.sum(array)</code> with <code>axis</code> argument.:</p> <pre><code>import numpy as np a = np.array([[1, 1, 1, 1, 0, 0], [1, 0, 1, 0, 0, 0]]) a = np.reshape(a, (a.shape[0]/2, 2, a.shape[1]/2, 2)) a = np.sum(a, axis=(1, 3)) &gt;= 2 </code></pre> <p>The reshaping groups your array into small 2x2 blocks (the orginals axis lengths must be multiples of 2), I then use sum along the created axis to check that at least of the 4 values in the group is 1.</p> <p>See <a href="http://stackoverflow.com/questions/32319036/computing-average-for-numpy-array/32319504#32319504">Computing average for numpy array</a> for similar question.</p>
1
2016-10-06T14:09:54Z
[ "python", "arrays", "image", "numpy", "image-processing" ]
simplify numpy array representation of image
39,898,151
<p>I have an image, read into <code>np.array</code> by PIL. In my case, it's a<code>(1000, 1500)</code> <code>np.array</code>.</p> <p>I'd like to simplify it for visualisation purposes. By simplification, I following transformation from this matrix</p> <pre><code>1 1 1 1 0 0 1 0 1 0 0 0 </code></pre> <p>to </p> <pre><code>1 1 0 </code></pre> <p>so, essentially, look at every <code>2*2</code> sample, if it satisfies some criteria, like more than 50% of 1's -> count it as a 1, if not, count is as a 0.</p> <p>I don't know how to call it properly, but I believe there should be some well known mathematic procedure for doing so.</p>
0
2016-10-06T14:04:30Z
39,898,414
<p>You could use <a href="http://pillow.readthedocs.io/en/3.1.x/reference/Image.html#PIL.Image.fromarray" rel="nofollow"><code>PIL.Image.fromarray</code></a> to take the image into PIL, then <a href="http://pillow.readthedocs.io/en/3.1.x/reference/Image.html#PIL.Image.Image.resize" rel="nofollow">resize</a> or convert that image into a <a href="http://pillow.readthedocs.io/en/3.1.x/reference/Image.html#PIL.Image.Image.thumbnail" rel="nofollow">thumbnail</a> of your desired size. one benefit is this can be easily saved to file, drawn to a canvas, or displayed for debugging. only be aware of numeric types and image modes (a pitfall I often fall into). </p> <p>creating the image is done by:</p> <pre><code>from PIL import Image image = Image.fromarray(arr).astype(np.uint8) #unsigned bytes for 8-bit grayscale smallerImage = image.resize(desired_size, resample=Image.BILINEAR) #resize returns a copy thumbnail modifies in place </code></pre> <p>Getting the image back to a numpy array is as simple as: <code>np.array(image.getdata()).reshape(image.size)</code></p>
1
2016-10-06T14:15:19Z
[ "python", "arrays", "image", "numpy", "image-processing" ]
heroku django server error
39,898,182
<p>Trying to deploy django project on heroku: <a href="https://crmtestnewone.herokuapp.com/crm/" rel="nofollow">https://crmtestnewone.herokuapp.com/crm/</a></p> <p>Do all as this instruction said but getting error (Server Error (500)) <a href="https://github.com/DjangoGirls/tutorial-extensions/blob/master/heroku/README.md" rel="nofollow">https://github.com/DjangoGirls/tutorial-extensions/blob/master/heroku/README.md</a></p> <pre><code>2016-10-06T14:01:38.045036+00:00 heroku[router]: at=info method=GET path="/crm/" host=crmtestnewone.herokuapp.com request_id=4981504b-0314-48ee-8a1b-ef7c51062b8f fwd="95.108.174.232" dyno=web.1 connect=1ms service=53ms status=500 bytes=253 </code></pre> <p>I only can enter /admin page</p> <pre><code>2016-10-06T14:03:37.432783+00:00 heroku[router]: at=info method=GET path="/admin/" host=crmtestnewone.herokuapp.com request_id=854e9324-a660-4a4e-ac19-8a9e693331c2 fwd="95.108.174.232" dyno=web.1 connect=0ms service=85ms status=200 bytes=4891 2016-10-06T14:03:37.596058+00:00 heroku[router]: at=info method=GET path="/static/admin/css/dashboard.css" host=crmtestnewone.herokuapp.com request_id=65fcb7df-bbe8-4731-aabc-24c1886c7300 fwd="95.108.174.232" dyno=web.1 connect=0ms service=2ms status=404 bytes=304 2016-10-06T14:03:37.597996+00:00 heroku[router]: at=info method=GET path="/static/admin/css/base.css" host=crmtestnewone.herokuapp.com request_id=2ed877bd-c9f7-4b3d-b613-c479d75d1ef1 fwd="95.108.174.232" dyno=web.1 connect=0ms service=3ms status=404 bytes=299 </code></pre> <p>Can you give any advice to me? Why admin page working (i can create objects in my models), but look like pure html without any style and my other pages dont work at all?</p> <p>UPDATE:</p> <p>settings.py</p> <pre><code>INSTALLED_APPS = ( 'crm', 'bootstrapform', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles',) MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware',) ROOT_URLCONF = 'dive_into.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'dive_into.wsgi.application' import os BASE_DIR = os.path.dirname(os.path.dirname(__file__)) DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True STATIC_URL = '/static/' LOGIN_REDIRECT_URL = '/crm/' PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__)) STATIC_ROOT = os.path.join(BASE_DIR, 'static') import dj_database_url DATABASES['default'] = dj_database_url.config() SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') ALLOWED_HOSTS = ['*'] DEBUG = False try: from .local_settings import * except ImportError: pass </code></pre> <p>requirements.txt</p> <pre><code>Django==1.10.1 django-bootstrap-form==3.2.1 gunicorn==19.4.5 psycopg2==2.6.1 whitenoise==2.0.6 dj-database-url==0.4.0 </code></pre>
0
2016-10-06T14:05:44Z
39,899,982
<p>change to debug=true, got error: Could not parse the remainder: '=' from '=' in<br> problem was in: {% if search_clients = 'no auth'%} it should be == It works fine localy throught.</p> <p>Newtt thanks for your help!</p>
0
2016-10-06T15:25:56Z
[ "python", "django", "heroku" ]
Turning table data into columns and counting by frequency
39,898,338
<p>I have a dataframe in the following form:</p> <p><a href="http://i.stack.imgur.com/Ej9td.png" rel="nofollow"><img src="http://i.stack.imgur.com/Ej9td.png" alt="enter image description here"></a></p> <p>shape is 2326 x 1271</p> <p>Column names are just serialized from 0-1269 while rows are categories that could repeat like "apple" in the example. The internal data points can represent anything (let's say they represent stores in this example) and I'm trying to convert them into columns and having the data points become the number of times that category shows up in that "store". Visually, here is the table I'm trying to get to:</p> <p><a href="http://i.stack.imgur.com/2tuZQ.png" rel="nofollow"><img src="http://i.stack.imgur.com/2tuZQ.png" alt="enter image description here"></a></p> <p>Note that Apple shows up in AA and RR twice</p>
0
2016-10-06T14:11:59Z
39,899,507
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.stack.html" rel="nofollow"><code>stack</code></a> along with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.crosstab.html" rel="nofollow"><code>crosstab</code></a> to compute the frequency counts:</p> <p><strong>Data:</strong></p> <pre><code>index= ['Apple', 'Orange', 'Apple', 'Banana', 'Kiwi'] data = [['AA', 'DD', 'RR', ''], ['DD', 'PP', '', ''], ['AA', 'RR', 'TT', 'SS'], ['EE', 'NN', '',''], ['NN', 'WW','', '']] frame = pd.DataFrame(data, index, columns=np.arange(4)) frame </code></pre> <p><a href="http://i.stack.imgur.com/IXe0D.png" rel="nofollow"><img src="http://i.stack.imgur.com/IXe0D.png" alt="Image"></a></p> <p><strong>Operations:</strong></p> <pre><code>df = frame.stack().reset_index(0, name='values') df = pd.crosstab(df['level_0'], df['values']).drop('', axis=1).replace(0, '') df.index.name=None; df.columns.name=None df </code></pre> <p><a href="http://i.stack.imgur.com/zorwe.png" rel="nofollow"><img src="http://i.stack.imgur.com/zorwe.png" alt="Image"></a></p>
1
2016-10-06T15:04:59Z
[ "python", "pandas", "reshape" ]
How to type python file in cmd?
39,898,375
<p>I have completed a py file as follow:</p> <pre><code>import re file = open('/Path/text1.txt') word = 'summer flowers' try : flag = 0 for line in file : lines = line.lower() x=re.findall('.*'+word+'\s.*',lines) if len(x)&gt;0: flag =1 print line else: flag = flag if flag == 0: print 'No match!' except: print 'No enough arguments!' </code></pre> <p>I have saved above py file as test1.py. My question is that: How to type above code in the cmd line?</p> <p>e.g. I hope to input the code: " <strong>test1.py 'summer flowers', text1.txt</strong> " in the cmd to execute above code </p> <p>where test1.py is the file name of the py file, 'summer flowers' is the key word I want to search and match in the txt file and text1.txt is the txt file name.</p>
0
2016-10-06T14:13:35Z
39,898,548
<pre><code>import re import sys file = sys.argv[2] word = sys.argv[1] try : flag = 0 for line in file : lines = line.lower() x=re.findall('.*'+word+'\s.*',lines) if len(x)&gt;0: flag =1 printline else: flag = flag if flag == 0: print 'No match!' except: print 'No enough arguments!' </code></pre> <p>Use <code>sys</code> to deal with command line stuff. <code>sys.argv</code> returns a list of the arguments from the command line and since you wanted to run it in cmd line use <code>python script_name.py keyword filename</code> don't need quotes for single words or commas. Also note <code>sys.argv[0]</code> is reserved for the file name so <code>sys.argv</code> returns <code>['script_name.py', 'keyword', 'filename']</code> if you ran the command above.</p> <p>Edit: </p> <p>Like the comment says if you want a phrase instead of a word you can use <code>quotes</code> in the commend line so: </p> <p><code>python script_name.py "my phrase" filename</code></p> <p>will return in <code>sys.argv</code> as <code>['script_name.py', 'my phrase', 'filename']</code></p>
2
2016-10-06T14:22:10Z
[ "python", "python-2.7", "text-mining" ]
How to type python file in cmd?
39,898,375
<p>I have completed a py file as follow:</p> <pre><code>import re file = open('/Path/text1.txt') word = 'summer flowers' try : flag = 0 for line in file : lines = line.lower() x=re.findall('.*'+word+'\s.*',lines) if len(x)&gt;0: flag =1 print line else: flag = flag if flag == 0: print 'No match!' except: print 'No enough arguments!' </code></pre> <p>I have saved above py file as test1.py. My question is that: How to type above code in the cmd line?</p> <p>e.g. I hope to input the code: " <strong>test1.py 'summer flowers', text1.txt</strong> " in the cmd to execute above code </p> <p>where test1.py is the file name of the py file, 'summer flowers' is the key word I want to search and match in the txt file and text1.txt is the txt file name.</p>
0
2016-10-06T14:13:35Z
39,898,553
<p>Using the <code>sys</code> module. Specifically, <a href="https://docs.python.org/2/library/sys.html#sys.argv" rel="nofollow"><code>sys.argv</code></a></p> <p>From the docs:</p> <blockquote> <p>sys.argv</p> <p>The list of command line arguments passed to a Python script. argv[0] is the script name (it is operating system dependent whether this is a full pathname or not). If the command was executed using the -c command line option to the interpreter, argv[0] is set to the string '-c'. If no script name was passed to the Python interpreter, argv[0] is the empty string.</p> </blockquote>
0
2016-10-06T14:22:18Z
[ "python", "python-2.7", "text-mining" ]
I need to host node js through python
39,898,439
<pre><code>var util = require('util'); var exec = require('child_process').spawn; var run = exec('/usr/bin/python', ['-m', 'SimpleHTTPServer', '9002']); run.stdout.on('data', function(data){ console.log('stdout: ' + data.toString()); }); run.stderr.on('data', function (data) { console.log('stderr: ' + data.toString()); }); </code></pre> <p>test.py</p> <pre><code>from bottle import route, run, template @route('/hello/&lt;name&gt;') def index(name): return template('&lt;b&gt;Hello {{name}}&lt;/b&gt;!', name=name) run(host='localhost', port=9002) </code></pre> <p>I am new to node js and python just i want do communicate between node js to python with localhost. A simple python script with localhost url to hit node js url after running node js scrpit whih call python script in node and host the same on web browser.</p>
-2
2016-10-06T14:16:20Z
39,901,825
<p>Not entirely sure I see the problem. Your code works. </p> <p>1) Make sure you access <code>localhost:9002</code><br> 2) If you meant to run your bottle code, then use </p> <pre><code>var run = exec('/usr/bin/python', ['/path/to/bottle_server.py']); </code></pre> <p><a href="http://i.stack.imgur.com/EEGKK.png" rel="nofollow"><img src="http://i.stack.imgur.com/EEGKK.png" alt="img1"></a></p> <p>As for communicating back and forth between the Python code and the Node.js code, then you need sockets. Some libraries to look at could include <code>socket.io</code> or use a messaging queue like <code>zmq</code>.</p> <p>If you want one-way communication to your python API, then you need to perform HTTP requests to <code>http://localhost:9002</code> from the Node code. Alternatively, Node is very much capable of the same functionality you've included in the Python code on its own.</p> <p><strong>EDIT</strong></p> <p>Regarding below comments, here is an updated script. You need to <code>inherit</code> the parent's <code>stdout</code> and <code>stderr</code>, otherwise, as you see in the image above, it thinks python is printing to <code>stderr</code></p> <pre><code>var util = require('util'); const spawn = require('child_process').spawn; var run = spawn('/usr/bin/python', ['-m', 'SimpleHTTPServer', '9002'], { stdio: ['ignore', 'inherit', 'inherit' ] }); run.on('exit', (code) =&gt; { console.log(`Child exited with code ${code}`); }); </code></pre> <p><a href="http://i.stack.imgur.com/egaQf.png" rel="nofollow"><img src="http://i.stack.imgur.com/egaQf.png" alt="img2"></a></p>
0
2016-10-06T17:03:14Z
[ "python", "node.js", "client-server" ]
Understanding numpy condition on array
39,898,467
<p>I don't understand some code from Kaggle's solution. </p> <p>Here is an example of the data: </p> <pre><code>PassengerId,Survived,Pclass,Name,Sex,Age,SibSp,Parch,Ticket,Fare,Cabin,Embarked 1,0,3,"Braund, Mr. Owen Harris",male,22,1,0,A/5 21171,7.25,,S 2,1,1,"Cumings, Mrs. John Bradley (Florence Briggs Thayer)",female,38,1,0,PC 17599,71.2833,C85,C 3,1,3,"Heikkinen, Miss. Laina",female,26,0,0,STON/O2. 3101282,7.925,,S </code></pre> <p>The goal is to extract an array with only the female, and they do it like this: </p> <pre><code># data contains all the passengers women_only_stats = data[0::,4] == "female" females_data = data[women] print(data[women][0]) # Will print the first women of the dataset of only women. </code></pre> <p>I understand that <code>women_data_only</code> will be an array of <code>True</code> and <code>False</code> which is the result of the evaluation of the expression <code>data[0::,4] == "female"</code>. <br> What I do not understand is why data[women] is an array of only women? <br> <br> <br>How is <code>numpy</code> evaluate that?</p>
0
2016-10-06T14:18:06Z
39,898,675
<p>Here's how it works:</p> <p><code>women_only_stats = data[0::,4] == "female"</code> will create a <strong>mask</strong> (array of <code>booleans</code>) for the indices of your dataframe.</p> <p>When passed to <code>data</code>, the mask will do a <strong>projection</strong> on the samples where <code>women_only_stats</code> is <code>True</code>, thus keeping only women.</p> <p>You can have a look <a href="http://docs.scipy.org/doc/numpy/user/basics.indexing.html#boolean-or-mask-index-arrays" rel="nofollow">here</a> about mask indexing.</p>
1
2016-10-06T14:28:03Z
[ "python", "arrays", "numpy" ]
TF-IDF score from TfIdfTransformer in sklearn on same word in two sentences with same frequency
39,898,477
<p>If I have two sentences containing the same word, and this word appears with the same counts (frequency) in both sentences, why is the Tf-Idf score I get different for them?</p> <p>Consider this list of texts:</p> <pre><code>data = [ 'Jumper in knit.', 'A sweater in knit, black sweater.', ] </code></pre> <p>and consider that I fit and transform a <code>CountVectorizer</code> and a <code>TfIdfTransformer</code> on it, as in </p> <pre><code>count_vec = CountVectorizer(stop_words='english') tf_transformer = TfidfTransformer(use_idf=True) X_counts = count_vec.fit_transform(x_data_manual) X_tfidf = tf_transformer.fit_transform(X_counts) </code></pre> <p>Then I print the features with their IDFs scores:</p> <pre><code>print zip(count_vec.get_feature_names(), tf_transformer.idf_) </code></pre> <p>obtaining</p> <blockquote> <p>[(u'black', 1.4054651081081644), (u'jumper', 1.4054651081081644), (u'knit', 1.0), (u'sweater', 1.4054651081081644)]</p> </blockquote> <p>so we can see that all tokens have the same IDF except 'knit', all legit.</p> <p>If I now ask for printing both the counts matrix and the TF-IDFs matrix, </p> <pre><code>print X_counts.todense() print X_tfidf.todense() </code></pre> <p>what I get is, respectively </p> <blockquote> <p>[[0 1 1 0]<br> [1 0 1 2]]</p> </blockquote> <p>(which is legit), and</p> <blockquote> <p>[[ 0. 0.815 0.58 0. ] </p> <p>[ 0.426 0. 0.303 0.852]]</p> </blockquote> <p>Now, I thought the TF-IDF score would be a multiplication of the term frequency (however calculated from the count/raw frequency) and the IDF, but I'm seeing 'knit' having a different score in the two sentences despite the frequencies are the same. </p> <p>So what I'm missing/misunderstanding?</p>
1
2016-10-06T14:18:29Z
39,899,936
<p>Reason is, after some more digging, that in the default configuration of the <code>TfIdfTransformer</code>, the scores get normalised in L2 norm at the end, per row.</p> <p>In fact, the kwarg <code>norm</code> is documents in the <a href="http://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.TfidfTransformer.html" rel="nofollow">docs</a>, but when reading I didn't properly understand what was being normalised, maybe a few more words would help.</p> <p>A step by step explanation is reported <a href="http://scikit-learn.org/stable/modules/feature_extraction.html#text-feature-extraction" rel="nofollow">here</a>.</p>
0
2016-10-06T15:23:47Z
[ "python", "scikit-learn", "tf-idf" ]
Spyder 3.0 won't let me run file
39,898,490
<p>Spyder 3.0, Windows 10 64-bit</p> <p>Hello everyone, I used to be able to write code and run the files in Spyder without a problem but now the button to run the code is greyed out and I can't run the file. Not even using F5 or clicking Run from the Run menu tab.</p> <p><a href="http://i.stack.imgur.com/BIPMN.png" rel="nofollow">View my Spyder menu tab</a></p> <p>Additionally, Spyder used to color my text in different ways but now it's all black. I don't know what happened, I didn't change any settings. Doing some research I found out this can be edited by accessing the Preferences tab (Code Introspection) but that option does not even show up in my menu bar.</p> <p><a href="http://i.stack.imgur.com/sxpbh.png" rel="nofollow">Another view of my Spyder menu tab</a></p> <p>How do I get Spyder 3.0 to run my files again? Thank you, world.</p>
-1
2016-10-06T14:19:03Z
39,963,557
<p>I'm having the exact same problem. Once I save my code turns white (I have a "skin" which is why its different) And it wouldn't let me run the file. I noticed that the saved file was in a different format which is probably be the cause. But I just did a simple factory reset and it works for me now.</p>
0
2016-10-10T17:21:58Z
[ "python", "menu", "spyder" ]
Python: How to initialize a list with generator function
39,898,514
<p>Let's say i have 2 following functions:</p> <pre><code>def get_items(): items = [] for i in xrange(2, 10): items.append(i) return items def gen_items(): for i in xrange(2, 10): yield i </code></pre> <p>I know i can use both of them in a for loop like this</p> <pre><code>for item in gen_items(): do something </code></pre> <p>But now i need to initialize a variable as list, like this</p> <pre><code>mylist = get_items() </code></pre> <p>but with the generator function. Is there a way to do it without a for loop appending the items from generator?</p>
3
2016-10-06T14:20:28Z
39,898,547
<p>The list builtin will accept any iterator: </p> <pre><code>l = list(gen_items()) </code></pre>
4
2016-10-06T14:22:05Z
[ "python", "generator" ]
Python: How to initialize a list with generator function
39,898,514
<p>Let's say i have 2 following functions:</p> <pre><code>def get_items(): items = [] for i in xrange(2, 10): items.append(i) return items def gen_items(): for i in xrange(2, 10): yield i </code></pre> <p>I know i can use both of them in a for loop like this</p> <pre><code>for item in gen_items(): do something </code></pre> <p>But now i need to initialize a variable as list, like this</p> <pre><code>mylist = get_items() </code></pre> <p>but with the generator function. Is there a way to do it without a for loop appending the items from generator?</p>
3
2016-10-06T14:20:28Z
39,898,551
<p>You can just directly create it using <code>list</code> which will handle iterating for you</p> <pre><code>&gt;&gt;&gt; list(gen_items()) [2, 3, 4, 5, 6, 7, 8, 9] </code></pre>
3
2016-10-06T14:22:14Z
[ "python", "generator" ]
'Wrong number of dimensions' error in Theano - LSTM
39,898,576
<p>I am trying to recreate <a href="http://christianherta.de/lehre/dataScience/machineLearning/neuralNetworks/LSTM.php" rel="nofollow">this</a> LSTM example for my own data. </p> <pre><code>Traceback (most recent call last): File "lstm.py", line 124, in &lt;module&gt; train_rnn(train_data) File "lstm.py", line 120, in train_rnn train_cost = learn_rnn_fn(i, o) File "/usr/local/lib/python3.5/site-packages/theano/compile/function_module.py", line 788, in __call__ allow_downcast=s.allow_downcast) File "/usr/local/lib/python3.5/site-packages/theano/tensor/type.py", line 178, in filter data.shape)) TypeError: ('Bad input argument to theano function with name "lstm.py:108" at index 0 (0-based)', 'Wrong number of dimensions: expected 2, got 0 with shape ().') </code></pre> <p>My code is provided as follows:</p> <pre><code>import numpy as np import theano import theano.tensor as T import pandas dtype=theano.config.floatX def create_dataset(dataset, look_back=1): data = [] for dx in range(len(dataset) - look_back - 1): data.append([dataset[dx], dataset[dx + 1]]) return np.array(data, dtype=dtype) raw_data = pandas.read_csv('international-airline-passengers.csv', usecols=[1]) train_data = create_dataset(raw_data.as_matrix()[:,0]) </code></pre> <p><code>train_data</code> becomes a 2-D numpy matrix after this transformation. </p> <pre><code>sigma = lambda x: 1 / (1 + T.exp(-x)) act = T.tanh def one_lstm_step(x_t, h_tm1, c_tm1, W_xi, W_hi, W_ci, b_i, W_xf, W_hf, W_cf, b_f, W_xc, W_hc, b_c, W_xy, W_ho, W_cy, b_o, W_hy, b_y): i_t = sigma(theano.dot(x_t, W_xi) + theano.dot(h_tm1, W_hi) + theano.dot(c_tm1, W_ci) + b_i) f_t = sigma(theano.dot(x_t, W_xf) + theano.dot(h_tm1, W_hf) + theano.dot(c_tm1, W_cf) + b_f) c_t = f_t * c_tm1 + i_t * act(theano.dot(x_t, W_xc) + theano.dot(h_tm1, W_hc) + b_c) o_t = sigma(theano.dot(x_t, W_xo)+ theano.dot(h_tm1, W_ho) + theano.dot(c_t, W_co) + b_o) h_t = o_t * act(c_t) y_t = sigma(theano.dot(h_t, W_hy) + b_y) return [h_t, c_t, y_t] def sample_weights(sizeX, sizeY): values = np.ndarray([sizeX, sizeY], dtype=dtype) for dx in range(sizeX): vals = np.random.uniform(low=-1., high=1., size=(sizeY,)) values[dx,:] = vals _,svs,_ = np.linalg.svd(values) values = values / svs[0] return values n_in = 1 n_hidden = n_i = n_c = n_o = n_f = 10 n_y = 1 W_xi = theano.shared(sample_weights(n_in, n_i)) W_hi = theano.shared(sample_weights(n_hidden, n_i)) W_ci = theano.shared(sample_weights(n_c, n_i)) b_i = theano.shared(np.cast[dtype](np.random.uniform(-0.5,.5,size = n_i))) W_xf = theano.shared(sample_weights(n_in, n_f)) W_hf = theano.shared(sample_weights(n_hidden, n_f)) W_cf = theano.shared(sample_weights(n_c, n_f)) b_f = theano.shared(np.cast[dtype](np.random.uniform(0, 1.,size = n_f))) W_xc = theano.shared(sample_weights(n_in, n_c)) W_hc = theano.shared(sample_weights(n_hidden, n_c)) b_c = theano.shared(np.zeros(n_c, dtype=dtype)) W_xo = theano.shared(sample_weights(n_in, n_o)) W_ho = theano.shared(sample_weights(n_hidden, n_o)) W_co = theano.shared(sample_weights(n_c, n_o)) b_o = theano.shared(np.cast[dtype](np.random.uniform(-0.5,.5,size = n_o))) W_hy = theano.shared(sample_weights(n_hidden, n_y)) b_y = theano.shared(np.zeros(n_y, dtype=dtype)) c0 = theano.shared(np.zeros(n_hidden, dtype=dtype)) h0 = T.tanh(c0) params = [W_xi, W_hi, W_ci, b_i, W_xf, W_hf, W_cf, b_f, W_xc, W_hc, b_c, W_xo, W_ho, W_co, b_o, W_hy, b_y, c0] v = T.matrix(dtype=dtype) target = T.matrix(dtype=dtype) [h_vals, _, y_vals], _ = theano.scan(fn=one_lstm_step, sequences = dict(input=v, taps=[0]), outputs_info = [h0, c0, None ], # corresponds to return type of fn non_sequences = [W_xi, W_hi, W_ci, b_i, W_xf, W_hf, W_cf, b_f, W_xc, W_hc, b_c, W_xo, W_ho, W_co, b_o, W_hy, b_y] ) cost = -T.mean(target * T.log(y_vals)+ (1.- target) * T.log(1. - y_vals)) updates=[] learn_rnn_fn = theano.function(inputs = [v, target], outputs = cost, updates = updates) nb_epochs=1 train_errors = np.ndarray(nb_epochs) def train_rnn(train_data): for x in range(nb_epochs): error = 0. print(train_data) for j in range(len(train_data)): index = np.random.randint(0, len(train_data)) i, o = train_data[index] train_cost = learn_rnn_fn(i, o) error += train_cost train_errors[x] = error train_rnn(train_data) </code></pre> <p>Debugging shows that the shape of variables <code>i</code> and <code>o</code> is not appropriate. I tried to reshape the data, but it leads to other data type problems.</p>
1
2016-10-06T14:23:17Z
39,949,934
<p>The function create_dataset is returning one numpy array. However, when you call i, o = train_data[index], you are trying to obtain two values. You can for example assigning the value to a temporal variable, and then split it as you need.</p> <p><strong>EDIT</strong> the variables <code>i</code> and <code>o</code> were not of the same type expected by the function <code>learn_rnn_fn</code>. It was expecting numpy matrices.</p>
0
2016-10-10T00:38:21Z
[ "python", "numpy", "deep-learning", "theano", "lstm" ]
Python: List youtube videos titles and url from an extracted HTML
39,898,644
<p>I'm making a simple script with Python 3.5, it asks a title (e.g. a song), it goes on youtube.com/results?search_query=my+title and extracts the html code.</p> <p>That's what I did, but now i'm facing a problem: I want my script to list the videos propositions title and register the corresponding link, so e.g it gives me a list like this</p> <blockquote> <p>Search: "eazy e"</p> <ol> <li>Eazy E - Real muthaf***** G's</li> <li>Eazy E - Boys In Da Hood etc..</li> </ol> <p>Insert the number of the video:</p> </blockquote> <p>The problem here is that I have a HUGE load of html code and I don't know how to list what I want to have...</p> <p>I used urlib.request.urlopen('<a href="http://youtube.com/results?search_query=" rel="nofollow">http://youtube.com/results?search_query=</a>'+url_search_content) to extract the html code</p> <p>Please help</p>
0
2016-10-06T14:26:20Z
39,899,009
<p>You can use the built in htmlparser library in python to extract the tags that contain the titles of the videos that you want. This library will be give you multiple ways to parse through tags as well as provide you with a clearer readable output.</p> <p><a href="https://docs.python.org/3/library/html.parser.html" rel="nofollow">https://docs.python.org/3/library/html.parser.html</a></p> <p>Keep in mind though that youtube search results are often multiple pages of content, and your html results will only be for one of these pages.</p>
0
2016-10-06T14:43:00Z
[ "python", "html", "video", "youtube" ]
I have a dictionary stored as numpy array a typical key is in the format of
39,898,668
<p>I have a dictionary of data stored as a numpy array. A typical key in the dictionary is in the format of:</p> <pre><code>('Typical Key', {'a': 100 'b': 'NaN', 'c': 'NaN', 'e': 360300, 'f': 8308552, 'g': 'NaN', 'h': 3576206, 'i': True, 'j': 'NaN', 'k': 'NaN', 'l': 'NaN', 'm': '[email protected]', 'x': 'NaN'}) </code></pre> <p>I am trying to find which key in the dictionary contains an element with the maximum value in order to identify an outlier in my dataset which I can see on a graph. I know what the key of the data point SHOULD be from working through a tutorial (I know the answer)</p> <p>I have tried a few ways of doing this but I'm consistently getting an unexpected result - I have been basing my code around using <code>max()</code> function. For instance see examples below:</p> <pre><code>inverse = [(value, key) for key, value in data_dict.items()] print max(inverse)[1] xx = max(data_dict, key=lambda i: data_dict[i]) print xx import operator result = max(data_dict.iteritems(), key=operator.itemgetter(1))[0] print result </code></pre> <p>I have a feeling that I'm not looking at the elements and that's the problem. Any help is appreciated!</p>
2
2016-10-06T14:27:39Z
39,898,851
<pre><code>import sys Max = -sys.maxint best_key = None for k, v in data_dict: # k refers to each 'typical key' inner_dict = v for key, value in inner_dict.items(): if isinstance(value, int) and Max &lt; value: Max = value best_key = key print best_key </code></pre>
0
2016-10-06T14:36:03Z
[ "python", "pandas", "numpy", "dictionary", "regression" ]
I have a dictionary stored as numpy array a typical key is in the format of
39,898,668
<p>I have a dictionary of data stored as a numpy array. A typical key in the dictionary is in the format of:</p> <pre><code>('Typical Key', {'a': 100 'b': 'NaN', 'c': 'NaN', 'e': 360300, 'f': 8308552, 'g': 'NaN', 'h': 3576206, 'i': True, 'j': 'NaN', 'k': 'NaN', 'l': 'NaN', 'm': '[email protected]', 'x': 'NaN'}) </code></pre> <p>I am trying to find which key in the dictionary contains an element with the maximum value in order to identify an outlier in my dataset which I can see on a graph. I know what the key of the data point SHOULD be from working through a tutorial (I know the answer)</p> <p>I have tried a few ways of doing this but I'm consistently getting an unexpected result - I have been basing my code around using <code>max()</code> function. For instance see examples below:</p> <pre><code>inverse = [(value, key) for key, value in data_dict.items()] print max(inverse)[1] xx = max(data_dict, key=lambda i: data_dict[i]) print xx import operator result = max(data_dict.iteritems(), key=operator.itemgetter(1))[0] print result </code></pre> <p>I have a feeling that I'm not looking at the elements and that's the problem. Any help is appreciated!</p>
2
2016-10-06T14:27:39Z
39,900,559
<p>O.K sorted it by tweaking the code proplerly - possibly because i had not articulated what i wanted to do properly Had to tweak the code slightly but this did work - i need to work to understand why my other code was not returning the expected value </p> <pre><code>import sys Max = -sys.maxint best_key = None for k, v in data_dict.iteritems(): # k refers to each 'typical key' inner_dict = v for key, value in inner_dict.iteritems(): if isinstance(value, int) and Max &lt; value: Max = value best_key = k` </code></pre>
1
2016-10-06T15:54:18Z
[ "python", "pandas", "numpy", "dictionary", "regression" ]
I have a dictionary stored as numpy array a typical key is in the format of
39,898,668
<p>I have a dictionary of data stored as a numpy array. A typical key in the dictionary is in the format of:</p> <pre><code>('Typical Key', {'a': 100 'b': 'NaN', 'c': 'NaN', 'e': 360300, 'f': 8308552, 'g': 'NaN', 'h': 3576206, 'i': True, 'j': 'NaN', 'k': 'NaN', 'l': 'NaN', 'm': '[email protected]', 'x': 'NaN'}) </code></pre> <p>I am trying to find which key in the dictionary contains an element with the maximum value in order to identify an outlier in my dataset which I can see on a graph. I know what the key of the data point SHOULD be from working through a tutorial (I know the answer)</p> <p>I have tried a few ways of doing this but I'm consistently getting an unexpected result - I have been basing my code around using <code>max()</code> function. For instance see examples below:</p> <pre><code>inverse = [(value, key) for key, value in data_dict.items()] print max(inverse)[1] xx = max(data_dict, key=lambda i: data_dict[i]) print xx import operator result = max(data_dict.iteritems(), key=operator.itemgetter(1))[0] print result </code></pre> <p>I have a feeling that I'm not looking at the elements and that's the problem. Any help is appreciated!</p>
2
2016-10-06T14:27:39Z
39,901,951
<p>With your sample dictionary:</p> <pre><code>In [684]: dd Out[684]: {'a': 100, 'b': 'NaN', 'c': 'NaN', 'e': 360300, 'f': 8308552, 'g': 'NaN', 'h': 3576206, 'i': True, 'j': 'NaN', 'k': 'NaN', 'l': 'NaN', 'm': '[email protected]', 'x': 'NaN'} </code></pre> <p>I can easily pull out a list of the values - but with those strings, I can't do a <code>max</code>.</p> <pre><code>In [685]: list(dd.values()) Out[685]: ['NaN', '[email protected]', 3576206, 'NaN', 8308552, 'NaN', 100, 'NaN', 'NaN', 360300, 'NaN', True, 'NaN'] </code></pre> <p>so as you discovered I have to first filter out the <code>ints</code>:</p> <pre><code>In [687]: max([i for i in dd.values() if isinstance(i,int)]) Out[687]: 8308552 </code></pre> <p>Or a list of tuples of candidates for max:</p> <pre><code>In [692]: [(v,k) for k,v in dd.items() if isinstance(v,int)] Out[692]: [(3576206, 'h'), (8308552, 'f'), (100, 'a'), (360300, 'e'), (True, 'i')] </code></pre> <p>and taking the max with a <code>lambda</code> <code>key</code>:</p> <pre><code>In [693]: max([(k,v) for k,v in dd.items() if isinstance(v,int)], key=lambda x:x[1]) Out[693]: ('f', 8308552) </code></pre> <p>=============</p> <p>from your comment (reformatted for clarity)</p> <pre><code>import pickle import sys import matplotlib.pyplot import numpy as np sys.path.append("../tools/") from feature_format import featureFormat, targetFeatureSplit #added ### read in data dictionary, convert to numpy array data_dict = pickle.load(open("../final_project/final_project_dataset.pkl", "r") ) features = ["salary", "bonus"] data = featureFormat(data_dict, features) print type(data) </code></pre> <p>You may import <code>numpy</code>, but the sample data is not an array. You gave us a tuple that contains a dictionary. And your code is all Python list and dictionary work, nothing using <code>numpy</code>.</p>
0
2016-10-06T17:10:37Z
[ "python", "pandas", "numpy", "dictionary", "regression" ]
MLP in tensorflow for regression... not converging
39,898,696
<p>Hello it is my first time working with tensorflow, i try to adapt the example here <a href="https://github.com/aymericdamien/TensorFlow-Examples/blob/master/examples/3_NeuralNetworks/multilayer_perceptron.py" rel="nofollow">TensorFlow-Examples</a> to use this code for regression problems with boston database. Basically, i only change the cost function ,the database, the inputs number, and the target number but when i run the MPL doesn't converge (i use a very low rate). I test it with Adam Optimization and descend gradient optimization but i have the same behavior. I appreciate your suggestions and ideas...!!!</p> <p><em>Observation: When i ran this program without the modifications described above, the cost function value always decrease.</em></p> <p>Here the evolution when i run the model, the cost function oscillated even with a very low learning rate.In the worst case, i hope the model converge in a value, for example the epoch 944 shows a value 0.2267548 if not other better value is find then this value must stay until the optimization is finished.</p> <p>Epoch: 0942 cost= 0.445707272</p> <p>Epoch: 0943 cost= 0.389314095</p> <p>Epoch: 0944 cost= 0.226754842</p> <p>Epoch: 0945 cost= 0.404150135</p> <p>Epoch: 0946 cost= 0.382190095</p> <p>Epoch: 0947 cost= 0.897880572</p> <p>Epoch: 0948 cost= 0.481954243</p> <p>Epoch: 0949 cost= 0.269408980</p> <p>Epoch: 0950 cost= 0.427961614</p> <p>Epoch: 0951 cost= 1.206053280</p> <p>Epoch: 0952 cost= 0.834200084</p> <pre><code>from __future__ import print_function # Import MNIST data #from tensorflow.examples.tutorials.mnist import input_data #mnist = input_data.read_data_sets("/tmp/data/", one_hot=True) import tensorflow as tf import ToolInputData as input_data ALL_DATA_FILE_NAME = "boston_normalized.csv" ##Load complete database, then this database is splitted in training, validation and test set completedDatabase = input_data.Databases(databaseFileName=ALL_DATA_FILE_NAME, targetLabel="MEDV", trainPercentage=0.70, valPercentage=0.20, testPercentage=0.10, randomState=42, inputdataShuffle=True, batchDataShuffle=True) # Parameters learning_rate = 0.0001 training_epochs = 1000 batch_size = 5 display_step = 1 # Network Parameters n_hidden_1 = 10 # 1st layer number of neurons n_hidden_2 = 10 # 2nd layer number of neurons n_input = 13 # number of features of my database n_classes = 1 # one target value (float) # tf Graph input x = tf.placeholder("float", [None, n_input]) y = tf.placeholder("float", [None, n_classes]) # Create model def multilayer_perceptron(x, weights, biases): # Hidden layer with RELU activation layer_1 = tf.add(tf.matmul(x, weights['h1']), biases['b1']) layer_1 = tf.nn.relu(layer_1) # Hidden layer with RELU activation layer_2 = tf.add(tf.matmul(layer_1, weights['h2']), biases['b2']) layer_2 = tf.nn.relu(layer_2) # Output layer with linear activation out_layer = tf.matmul(layer_2, weights['out']) + biases['out'] return out_layer # Store layers weight &amp; bias weights = { 'h1': tf.Variable(tf.random_normal([n_input, n_hidden_1])), 'h2': tf.Variable(tf.random_normal([n_hidden_1, n_hidden_2])), 'out': tf.Variable(tf.random_normal([n_hidden_2, n_classes])) } biases = { 'b1': tf.Variable(tf.random_normal([n_hidden_1])), 'b2': tf.Variable(tf.random_normal([n_hidden_2])), 'out': tf.Variable(tf.random_normal([n_classes])) } # Construct model pred = multilayer_perceptron(x, weights, biases) # Define loss and optimizer cost = tf.reduce_mean(tf.square(pred-y)) #cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(pred, y)) optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost) # Initializing the variables init = tf.initialize_all_variables() # Launch the graph with tf.Session() as sess: sess.run(init) # Training cycle for epoch in range(training_epochs): avg_cost = 0. total_batch = int(completedDatabase.train.num_examples/batch_size) # Loop over all batches for i in range(total_batch): batch_x, batch_y = completedDatabase.train.next_batch(batch_size) # Run optimization op (backprop) and cost op (to get loss value) _, c = sess.run([optimizer, cost], feed_dict={x: batch_x, y: batch_y}) # Compute average loss avg_cost += c / total_batch # Display logs per epoch step if epoch % display_step == 0: print("Epoch:", '%04d' % (epoch+1), "cost=", \ "{:.9f}".format(avg_cost)) print("Optimization Finished!") </code></pre>
1
2016-10-06T14:28:59Z
39,900,746
<p>A couple of points. </p> <p>Your model is quite shallow being only two layers. Granted you'll need more data to train a larger model so I don't know how much data you have in the Boston data set.</p> <p>What are your labels? That would better inform whether squared error is better for your model.</p> <p>Also your learning rate is quite low.</p>
0
2016-10-06T16:03:04Z
[ "python", "machine-learning", "tensorflow", "multi-layer" ]
Logger to not show INFO from external libaries
39,898,754
<p>I want logger to print INFO messages from all my code but not from 3rd party libraries. This is discussed in multiple places, but the suggested solution does not work for me. Here is my simulation of external library, <code>extlib.py</code>:</p> <pre><code>#!/usr/bin/env python3 from logging import info def f(): info("i am extlib f()") </code></pre> <p>My module:</p> <pre><code>#!/usr/bin/env python3 import logging from logging import info import extlib logging.basicConfig(level=logging.INFO) info("I am mymodule") extlib.f() </code></pre> <p>Output:</p> <blockquote> <p>INFO:root:I am mymodule </p> <p>INFO:root:i am extlib f()</p> </blockquote> <p>My attempt to only enable INFO for local module:</p> <pre><code>#!/usr/bin/env python3 import logging from logging import info import extlib logging.getLogger(__name__).setLevel(logging.INFO) info("I am mymodule") extlib.f() </code></pre> <p>Output: nothing</p> <p>Desired output:</p> <blockquote> <p>INFO:root:I am mymodule </p> </blockquote> <p>What am I doing wrong?</p>
0
2016-10-06T14:31:56Z
39,898,805
<p>The problem is that they aren't using the logger class in the external library. If they were then you could filter it out. I'm not certain you can stop them from logging information since they are using the <code>info</code> function call. Here is a workaround though.</p> <p><a href="http://stackoverflow.com/questions/4178614/suppressing-output-of-module-calling-outside-library">Suppressing output of module calling outside library</a></p> <p>Update:</p> <p>here's how you do loggers</p> <pre><code>import logging # create logger logger = logging.getLogger('simple_example') logger.setLevel(logging.DEBUG) # create console handler and set level to debug ch = logging.StreamHandler() ch.setLevel(logging.DEBUG) # create formatter formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') # add formatter to ch ch.setFormatter(formatter) # add ch to logger logger.addHandler(ch) # 'application' code logger.debug('debug message') logger.info('info message') logger.warn('warn message') logger.error('error message') logger.critical('critical message') </code></pre>
2
2016-10-06T14:34:11Z
[ "python", "logging" ]
Django: how to add compare condition in annotate queryset
39,898,782
<p>I want to add compare operations in annotate queryset to calculate value for specific field. How can I do that? This is my annotate queryset</p> <pre><code>sale_item_list = OrderItem.objects.filter(order_id=order.id) \ .values('item__name') \ .annotate(price=F('price')) \ .annotate(exchange_rate=F('exchange_rate')) \ .annotate(quantity=F('quantity') \ .annotate(amount=Case( When(F('quantity') &lt; F('inventory'), then=Sum(F('quantity') * F('price'))), When(F('quantity') &gt; F('inventory'), then=Sum(F('inventory') * F('price'))), output_field=IntegerField())) </code></pre> <p>Conditional Expressions of my queryset above run error. Please help me fix it?</p>
1
2016-10-06T14:32:49Z
39,899,080
<p>Try using the lesser and greater than field lookups <code>__gt</code> and <code>__lt</code>:</p> <pre><code>When(quantity__lt=inventory, then=Sum(F('quantity') * F('price'))), When(quantity__gt=inventory, then=Sum(F('inventory') * F('price'))), </code></pre> <p>See <a href="https://docs.djangoproject.com/el/1.10/ref/models/querysets/#gt" rel="nofollow">https://docs.djangoproject.com/el/1.10/ref/models/querysets/#gt</a></p>
1
2016-10-06T14:46:04Z
[ "python", "django", "python-3.x" ]
How to Print a Path in Python?
39,898,784
<p>I want to make a script open the CMD and then enter a path:</p> <pre><code>import pyautogui as pag pag.hotkey('win','r') pag.typewrite('cmd') pag.press('enter') pag.typewrite('C:\Users\XY\AppData\') </code></pre> <p>that doesn't work. So, I tried this:</p> <pre><code>import pyautogui as pag pag.hotkey('win','r') pag.typewrite('cmd') pag.press('enter') pag.typewrite('C:\\Users\\huba5_000\\AppData\\') </code></pre> <p>However, this entered <code>C:?Users?XY?AppData?</code></p> <p>What I want it to enter is <code>C:\Users\XY\AppData\</code>. Do you know what I should write instead of '\\' ? </p> <p>Thank you in advance!</p>
0
2016-10-06T14:33:02Z
39,899,011
<p>when a string is read in from <code>input()</code> or from text boxes in gui's (in general.. idk about pag) the extra slashes are automatically put in. They are not automatically put in for string literals in your code however and must be escaped (hence the double slash). Here is a short console session (python 2.7) showing that functionality:</p> <pre class="lang-python prettyprint-override"><code>>>> s = raw_input('enter a path: ') #change raw_input to input() for python 3.x enter a path: \usr\var >>> s '\\usr\\var' >>> print s \usr\var</code></pre> <p>notice when I entered the path, I did not escape my backslashes, yet when I call the internal representation of <code>s</code> they have been put in for me. when I want the output format, I call print to execute any formatting (escapes) contained within the string</p>
0
2016-10-06T14:43:07Z
[ "python", "python-3.x", "printing", "pyautogui" ]
SFTP via Paramiko to ipv6 linux machine
39,898,819
<p>I am relatively new to python and am trying sftp for the first time via python script. I want my python script to get a file from a <strong>Dual Stack Machine (Both IPv4 and IPv6 present)</strong>. Below is the code snippet I am using for Paramiko:</p> <pre><code>host = ip #ip is a string that has the value of IP port = 22 transport = paramiko.Transport((host, port)) transport.connect(username = username, password = password) sftp = paramiko.SFTPClient.from_transport(transport </code></pre> <p>When I use the code with IPv4 it works fine. But when I replace the ip with IPv6 address, following error is thrown:</p> <pre><code>Traceback (most recent call last): File "MyFile.py", line 92, in &lt;module&gt; putFile() File "MyFile.py", line 29, in analyzeLogs transport = paramiko.Transport((host, port)) File "/usr/lib/python2.6/site-packages/paramiko/transport.py", line 289, in __init__ sock.connect((hostname, port)) File "&lt;string&gt;", line 1, in connect socket.gaierror: [Errno -2] Name or service not known </code></pre> <p>I checked for a solution and found someone suggesting to add the interface along with the IP but while trying the same I got the following error:</p> <pre><code>Traceback (most recent call last): File "MyFile.py", line 92, in &lt;module&gt; putFile() File "MyFile.py", line 29, in analyzeLogs transport = paramiko.Transport((host, port)) File "/usr/lib/python2.6/site-packages/paramiko/transport.py", line 289, in __init__ sock.connect((hostname, port)) File "&lt;string&gt;", line 1, in connect socket.gaierror: [Errno -9] Address family for hostname not supported </code></pre> <p>My original server will not be a dual stack machine and hence I need the file transfer via IPv6 only. </p> <p><strong>NOTE</strong>:When I use sftp command in linux, it works for both ipv4 and ipv6</p> <p>Any possible solution or additional suggestions would be really appreciated</p>
0
2016-10-06T14:34:37Z
39,922,784
<p>Paramiko's <code>Transport</code> class supports passing in a socket object as well as a tuple. So maybe try specifically passing in an ipv6 socket?</p> <pre><code>import socket sock = socket.socket(socket.AF_INET6, socket.SOCK_STREAM) sock.connect((hostname, port)) transport = paramiko.Transport(sock) </code></pre>
1
2016-10-07T17:21:31Z
[ "python", "linux", "python-2.7", "paramiko" ]
Python callback variable scope
39,898,876
<p>I have a function <code>fun()</code> that binds a callback <code>callback()</code> when a matplotlib figure is clicked. I want this callback to be able to access the variable space of <code>fun()</code> to make changes. How can I go about this?</p> <pre><code>import numpy as np import matplotlib.pyplot as plt def callback(event): data = event.xdata def fun(): data = 0 fig, ax = plt.subplots() ax.plot(np.random.rand(12), np.random.rand(12), 'go') fig.canvas.mpl_connect('button_release_event', callback) plt.show() return data print fun() </code></pre> <p>Putting <code>data</code> in the <code>global</code> scope is not an acceptable solution. The function should be self-contained. The answer <a href="https://stackoverflow.com/questions/24960910/how-can-i-pass-parameters-to-on-key-in-fig-canvas-mpl-connectkey-press-event">here</a> would allow me to pass variables to <code>callback()</code>, but would not let me edit them.</p>
0
2016-10-06T14:37:04Z
39,899,375
<p>I understand you would like to have some state, that can be changed during runtime. One option might be to use a callable object, that is not a function (I have not tested it):</p> <pre><code>class Callback(object): def __init__(self, data): self.data = data def __call__(self, event): # Manipulate the data self.data += 1 ... datacallback = Callback(0) fig.canvas.mpl_connect('button_release_event', datacallback) print datacallback.data </code></pre> <p>That way we would have a counter how often the event is raised. But it works with any kind of data, also more complex than an integer.</p>
1
2016-10-06T14:58:58Z
[ "python", "matplotlib", "scope" ]
Python sqlite3: INSERT into table WHERE NOT EXISTS, using ? substitution parameter
39,898,887
<p>I'm creating a table of descriptions from a list of not necessarily unique descriptions. I would like the table to contain only distinct descriptions, so while inserting descriptions into the table, I need to check to see if they already exist. My code(simplified) looks something like as follows:</p> <pre><code>cur.execute(''' CREATE TABLE descriptions (id INTEGER PRIMARY KEY AUTOINCREMENT, desc TEXT)''') descripts = ["d1", "d2", "d3", "d4", "d3", "d1", "d5", "d6", "d7", "d2"] cur.executemany(''' INSERT INTO descriptions(desc) VALUES (?) WHERE NOT EXISTS ( SELECT * FROM descriptions as d WHERE d.desc=?) ''', zip(descripts, descripts)) </code></pre> <p>The result is <code>OperationalError: near "WHERE": syntax error</code>, and I'm not sure exactly where I'm going wrong.</p> <p>Just a note: I realize I could solve this using a <code>set()</code> structure in python, but for academic reasons this is not permitted.</p> <p>Thanks</p>
0
2016-10-06T14:37:39Z
39,900,386
<p>To replace <code>VALUES</code> by <code>SELECT</code> should work</p> <pre><code>cursor.executemany(''' INSERT INTO descriptions(desc) SELECT (?) WHERE NOT EXISTS ( SELECT * FROM descriptions as d WHERE d.desc=?)''', zip(descripts, descripts)) </code></pre>
1
2016-10-06T15:45:36Z
[ "python", "python-2.7", "sqlite", "sqlite3" ]
Python Case Matching Input and Output
39,898,890
<p>I'm doing the pig latin question that I'm sure everyone here is familiar with it. The only thing I can't seem to get is matching the case of the input and output. For example, when the user enters Latin, my code produces <code>atinLay</code>. I want it to produce <code>Atinlay</code>.</p> <pre><code>import string punct = string.punctuation punct += ' ' vowel = 'aeiouyAEIOUY' consonant = 'bcdfghjklmnpqrstvwxzBCDFGHJKLMNPQRSTVWXZ' final_word = input("Please enter a single word. ") first_letter = final_word[:1] index = 0 if any((p in punct) for p in final_word): print("You did not enter a single word!") else: while index &lt; len(final_word) and (not final_word[index] in vowel): index = index+1 if any((f in vowel) for f in first_letter): print(final_word + 'yay') elif index &lt; len(final_word): print(final_word[index:]+final_word[:index]+'ay') </code></pre>
2
2016-10-06T14:37:46Z
39,898,991
<p>simply use the built in string functions.</p> <pre><code>s = "Hello".lower() s == "hello" s = "hello".upper() s == "HELLO" s = "elloHay".title() s == "Ellohay" </code></pre>
0
2016-10-06T14:42:08Z
[ "python", "string" ]
Python Case Matching Input and Output
39,898,890
<p>I'm doing the pig latin question that I'm sure everyone here is familiar with it. The only thing I can't seem to get is matching the case of the input and output. For example, when the user enters Latin, my code produces <code>atinLay</code>. I want it to produce <code>Atinlay</code>.</p> <pre><code>import string punct = string.punctuation punct += ' ' vowel = 'aeiouyAEIOUY' consonant = 'bcdfghjklmnpqrstvwxzBCDFGHJKLMNPQRSTVWXZ' final_word = input("Please enter a single word. ") first_letter = final_word[:1] index = 0 if any((p in punct) for p in final_word): print("You did not enter a single word!") else: while index &lt; len(final_word) and (not final_word[index] in vowel): index = index+1 if any((f in vowel) for f in first_letter): print(final_word + 'yay') elif index &lt; len(final_word): print(final_word[index:]+final_word[:index]+'ay') </code></pre>
2
2016-10-06T14:37:46Z
39,899,077
<p>What you need is <a href="http://docs.python/3/library/stdtypes.html#str.title" rel="nofollow"><code>str.title()</code></a>. Once you have done your piglatin conversion, you can use <code>title()</code> built-in function to produce the desired output, like so:</p> <pre><code>&gt;&gt;&gt; "atinLay".title() 'Atinlay' </code></pre> <p>To check if a string is lower case, you can use <a href="http://docs.python/3/library/library/stdtypes.html#str.islower" rel="nofollow"><code>str.islower()</code></a>. Take a peek at the docs.</p>
1
2016-10-06T14:45:55Z
[ "python", "string" ]
Global name 'camera' is not defined in python
39,898,927
<p>In this script :-</p> <pre><code>camera_port = 0 ramp_frames = 400 camera = cv2.VideoCapture(camera_port) def get_image(): global camera retval, im = camera.read() return im def Camera(): global camera for i in xrange(ramp_frames): temp = get_image() print("Taking image...") camera_capture = get_image() file = "opencv.png" cv2.imwrite(file, camera_capture) del(camera) def Sendmail(): loop_value = 1 while loop_value==1: try: urllib2.urlopen("https://google.com") except urllib2.URLError, e: print "Network currently down." sleep(20) else: print "Up and running." loop_value = 0 def Email(): loop_value = 2 while loop_value==2: try: Camera() Sendmail() yag = yagmail.SMTP('email', 'pass') yag.send('[email protected]', subject = "This is opencv.png", contents = 'opencv.png') print "done" except smtplib.SMTPAuthenticationError: print 'Retrying in 30 seconds' sleep(30) else: print 'Sent!' sleep(20) loop_value = 2 </code></pre> <p>I get this error :-</p> <p>What am I doing wrong. I have even defined camera globally, that to TWICE. Can somone please point out my mistake in the code? I use python 2.7 with Opencv module</p> <pre><code>File "C:\Python27\Scripts\Servers.py", line 22, in Camera temp = get_image() File "C:\Python27\Scripts\Servers.py", line 16, in get_image retval, im = camera.read() NameError: global name 'camera' is not defined </code></pre> <p><em>UPDATE</em> Look above for updated code</p>
6
2016-10-06T14:39:13Z
39,899,081
<p>You need to have defined <code>camera</code> outside the scope of your methods as well. What the <code>global</code> keyword does is tell Python that you will modify that variable which you defined externally. If you haven't, you get this error.</p> <p><strong>EDIT</strong></p> <p>I didn't notice that you had already declared <code>camera</code> externally. However, you delete the variable inside the <code>Camera()</code> method, which has pretty much the same effect when you try to modify the variable again.</p> <p><strong>EDIT 2</strong></p> <p>Now that I can see what your code really does and what you intend to do, I don't think you should be working with a global <code>camera</code> at all, but pass it as parameter instead. This should work:</p> <pre><code>camera_port = 0 ramp_frames = 400 def get_image(camera): retval, im = camera.read() return im def Camera(camera): for i in xrange(ramp_frames): temp = get_image(camera) print("Taking image...") camera_capture = get_image(camera) file = "opencv.png" cv2.imwrite(file, camera_capture) def Sendmail(): loop_value = 1 while loop_value==1: try: urllib2.urlopen("https://google.com") except urllib2.URLError, e: print "Network currently down." sleep(20) else: print "Up and running." loop_value = 0 def Email(): loop_value = 2 while loop_value==2: try: camera = cv2.VideoCapture(camera_port) Camera(camera) Sendmail() yag = yagmail.SMTP('email', 'pass') yag.send('[email protected]', subject = "This is opencv.png", contents = 'opencv.png') print "done" except smtplib.SMTPAuthenticationError: print 'Retrying in 30 seconds' sleep(30) else: print 'Sent!' sleep(20) loop_value = 2 </code></pre>
4
2016-10-06T14:46:14Z
[ "python", "python-2.7", "opencv" ]
Changing string to an existing variable name to create 1 function for multiple variables (Inside class, using root from Tkinter)
39,898,992
<pre><code>from tkinter import * class App: def __init__(self, master): frame = Frame(master) frame.pack() self.plot = Canvas(master, width=500, height=120) self.plot.pack() self.1 = self.plot.create_text(10,10, text = "0") self.2 = self.plot.create_text(30,10, text = "0") self.3 = self.plot.create_text(50,10, text = "0") def txt_change(self,name,value): self.plot.itemconfigure(self.name, text=value) </code></pre> <p>So here I want to create just 1 function that can change the value of multiple variables by including a name. This name is however a string,but I want python to interpret the string as a variable name. I have 20 variables like this, and creating a new function for every variable doesn't look very clean. Is there a smart way to do this?</p> <p>I was hoping that in the end I could use something like this: txt_change("1",20)</p>
0
2016-10-06T14:42:26Z
39,899,135
<p>This is called <code>setattr()</code> in python:</p> <pre><code>&gt;&gt;&gt; a = App(...) &gt;&gt;&gt; setattr(a, "name", "foo") &gt;&gt;&gt; a.name "foo" </code></pre>
1
2016-10-06T14:47:59Z
[ "python", "string", "variables", "tkinter", "tkinter-canvas" ]
Changing string to an existing variable name to create 1 function for multiple variables (Inside class, using root from Tkinter)
39,898,992
<pre><code>from tkinter import * class App: def __init__(self, master): frame = Frame(master) frame.pack() self.plot = Canvas(master, width=500, height=120) self.plot.pack() self.1 = self.plot.create_text(10,10, text = "0") self.2 = self.plot.create_text(30,10, text = "0") self.3 = self.plot.create_text(50,10, text = "0") def txt_change(self,name,value): self.plot.itemconfigure(self.name, text=value) </code></pre> <p>So here I want to create just 1 function that can change the value of multiple variables by including a name. This name is however a string,but I want python to interpret the string as a variable name. I have 20 variables like this, and creating a new function for every variable doesn't look very clean. Is there a smart way to do this?</p> <p>I was hoping that in the end I could use something like this: txt_change("1",20)</p>
0
2016-10-06T14:42:26Z
39,899,219
<p>Create a function within your class using <code>setattr()</code> as:</p> <pre><code>def update_property(self, name, value): self.setattr(name, value) </code></pre> <p>Here, <code>name</code> is the class's <code>peoperty</code> and <code>value</code> is the value you want to set for the previosu property </p>
0
2016-10-06T14:52:20Z
[ "python", "string", "variables", "tkinter", "tkinter-canvas" ]
Changing string to an existing variable name to create 1 function for multiple variables (Inside class, using root from Tkinter)
39,898,992
<pre><code>from tkinter import * class App: def __init__(self, master): frame = Frame(master) frame.pack() self.plot = Canvas(master, width=500, height=120) self.plot.pack() self.1 = self.plot.create_text(10,10, text = "0") self.2 = self.plot.create_text(30,10, text = "0") self.3 = self.plot.create_text(50,10, text = "0") def txt_change(self,name,value): self.plot.itemconfigure(self.name, text=value) </code></pre> <p>So here I want to create just 1 function that can change the value of multiple variables by including a name. This name is however a string,but I want python to interpret the string as a variable name. I have 20 variables like this, and creating a new function for every variable doesn't look very clean. Is there a smart way to do this?</p> <p>I was hoping that in the end I could use something like this: txt_change("1",20)</p>
0
2016-10-06T14:42:26Z
39,902,027
<p>The proper solution isn't to translate strings to variable names. Instead, store the items in a list or dictionary.</p> <p>For example, this uses a dictionary:</p> <pre><code>class App: def __init__(self, master): ... self.items = {} self.items[1] = self.plot.create_text(10,10, text = "0") self.items[2] = self.plot.create_text(30,10, text = "0") self.items[3] = self.plot.create_text(50,10, text = "0") def txt_change(self,name,value): item_id = self.items[name] self.plot.itemconfigure(item_id, text=value) ... app=App(...) app.txt_change(2, "this is the new text") </code></pre>
0
2016-10-06T17:15:17Z
[ "python", "string", "variables", "tkinter", "tkinter-canvas" ]
How to flatten a pandas dataframe with some columns as json?
39,899,005
<p>I have a dataframe <code>df</code> that loads data from a database. Most of the columns are json strings while some are even list of jsons. For example:</p> <pre><code>id name columnA columnB 1 John {"dist": "600", "time": "0:12.10"} [{"pos": "1st", "value": "500"},{"pos": "2nd", "value": "300"},{"pos": "3rd", "value": "200"}, {"pos": "total", "value": "1000"}] 2 Mike {"dist": "600"} [{"pos": "1st", "value": "500"},{"pos": "2nd", "value": "300"},{"pos": "total", "value": "800"}] ... </code></pre> <p>AS you can see, all the rows don't have the same number of elements in the json strings for a column. </p> <p>What I need to do is keep the normal columns like <code>id</code> and <code>name</code>, as it is and flatten the json columns like so</p> <pre><code>id name columnA.dist columnA.time columnB.pos.1st columnB.pos.2nd columnB.pos.3rd columnB.pos.total 1 John 600 0:12.10 500 300 200 1000 2 Mark 600 NaN 500 300 Nan 800 </code></pre> <p>I have tried using <code>json_normalize</code> like so</p> <pre><code>from pandas.io.json import json_normalize json_normalize(df) </code></pre> <p>But there seems to be some problems with <code>keyerror</code>. What is the correct way of doing this?</p>
3
2016-10-06T14:42:52Z
39,899,896
<p>create a custom function to flatten <code>columnB</code> then use <code>pd.concat</code></p> <pre><code>def flatten(js): return pd.DataFrame(js).set_index('pos').squeeze() pd.concat([df.drop(['columnA', 'columnB'], axis=1), df.columnA.apply(pd.Series), df.columnB.apply(flatten)], axis=1) </code></pre> <p><a href="http://i.stack.imgur.com/FVzRP.png" rel="nofollow"><img src="http://i.stack.imgur.com/FVzRP.png" alt="enter image description here"></a></p>
2
2016-10-06T15:21:36Z
[ "python", "json", "pandas", "flatten" ]
How to flatten a pandas dataframe with some columns as json?
39,899,005
<p>I have a dataframe <code>df</code> that loads data from a database. Most of the columns are json strings while some are even list of jsons. For example:</p> <pre><code>id name columnA columnB 1 John {"dist": "600", "time": "0:12.10"} [{"pos": "1st", "value": "500"},{"pos": "2nd", "value": "300"},{"pos": "3rd", "value": "200"}, {"pos": "total", "value": "1000"}] 2 Mike {"dist": "600"} [{"pos": "1st", "value": "500"},{"pos": "2nd", "value": "300"},{"pos": "total", "value": "800"}] ... </code></pre> <p>AS you can see, all the rows don't have the same number of elements in the json strings for a column. </p> <p>What I need to do is keep the normal columns like <code>id</code> and <code>name</code>, as it is and flatten the json columns like so</p> <pre><code>id name columnA.dist columnA.time columnB.pos.1st columnB.pos.2nd columnB.pos.3rd columnB.pos.total 1 John 600 0:12.10 500 300 200 1000 2 Mark 600 NaN 500 300 Nan 800 </code></pre> <p>I have tried using <code>json_normalize</code> like so</p> <pre><code>from pandas.io.json import json_normalize json_normalize(df) </code></pre> <p>But there seems to be some problems with <code>keyerror</code>. What is the correct way of doing this?</p>
3
2016-10-06T14:42:52Z
39,906,235
<p>Here's a solution using <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.io.json.json_normalize.html" rel="nofollow"><code>json.normalize</code></a> again by using a custom function to get the data in the correct format understood by <code>json.normalize</code> function.</p> <pre><code>import ast from pandas.io.json import json_normalize def only_dict(d): ''' Convert json string representation of dictionary to a python dict ''' return ast.literal_eval(d) def list_of_dicts(ld): ''' Create a mapping of the tuples formed after converting json strings of list to a python list ''' return dict([(list(d.values())[1], list(d.values())[0]) for d in ast.literal_eval(ld)]) A = json_normalize(df['columnA'].apply(only_dict).tolist()).add_prefix('columnA.') B = json_normalize(df['columnB'].apply(list_of_dicts).tolist()).add_prefix('columnB.pos.') </code></pre> <p>Finally, join the <code>DFs</code> on the common index to get:</p> <pre><code>df[['id', 'name']].join([A, B]) </code></pre> <p><a href="http://i.stack.imgur.com/SpBIg.png" rel="nofollow"><img src="http://i.stack.imgur.com/SpBIg.png" alt="Image"></a></p>
3
2016-10-06T21:57:45Z
[ "python", "json", "pandas", "flatten" ]
Communicate multiple times with a subprocess in Python
39,899,074
<p>This question is NOT a duplicate of </p> <p><a href="http://stackoverflow.com/questions/3065060/communicate-multiple-times-with-a-process-without-breaking-the-pipe">Communicate multiple times with a process without breaking the pipe?</a></p> <p>That question is solved because its use case allows inputs to be sent together, but this is not true if your program is interactive (as illustrated in the use case here).</p> <hr> <p>Document <code>subprocess.Popen</code> says:</p> <pre><code>communicate(input=None) Interact with process: Send data to stdin. Read data from stdout and stderr, until end-of-file is reached. Wait for process to terminate. ... </code></pre> <p>Is it possible to communicate multiple times with the subprocess before its termination, like with a terminal or with a network socket?</p> <p>For example, if the subprocess is <code>bc</code>, the parent process may want to send it different inputs for calculation as needed. Since inputs send to <code>bc</code> may depend on user inputs, it is not possible to send all inputs at once.</p>
0
2016-10-06T14:45:45Z
39,909,410
<p>Basicly <a href="http://stackoverflow.com/questions/375427/non-blocking-read-on-a-subprocess-pipe-in-python">Non-blocking read on a subprocess.PIPE in python</a></p> <p>Set the proc pipes (proc.stdout, proc.stdin, ...) to nonblocking mode via <code>fnctl</code> and then write/read them directly.</p> <p>You might want to use epoll or select via the <code>select</code> or <code>io</code> modules for more efficiency.</p>
0
2016-10-07T04:30:15Z
[ "python" ]
Import CSV file into SQL Server using Python
39,899,088
<p>I am having trouble uploading a CSV file into a table in MS SQL Server, The CSV file has 25 columns and the header has the same name as table in SQL which also has 25 columns. When I run the script it throws an error </p> <pre><code>params arg (&lt;class 'list'&gt;) can be only a tuple or a dictionary </code></pre> <p>What is the best way to import this data into MS SQL? Both the CSV and SQL table have the exact same column names. </p> <p>Here is the code:</p> <pre><code>import csv import pymssql conn = pymssql.connect( server="xx.xxx.xx.90", port = 2433, user='SQLAdmin', password='xxxxxxxx', database='NasrWeb' ) cursor = conn.cursor() customer_data = csv.reader('cleanNVG.csv') #25 columns with same header as SQL for row in customer_data: cursor.execute('INSERT INTO zzzOracle_Extract([Customer Name]\ ,[Customer #]\ ,[Account Name]\ ,[Identifying Address Flag]\ ,[Address1]\ ,[Address2]\ ,[Address3]\ ,[Address4]\ ,[City]\ ,[County]\ ,[State]\ ,[Postal Code]\ ,[Country]\ ,[Category ]\ ,[Class]\ ,[Reference]\ ,[Party Status]\ ,[Address Status]\ ,[Site Status]\ ,[Ship To or Bill To]\ ,[Default Warehouse]\ ,[Default Order Type]\ ,[Default Shipping Method]\ ,[Optifacts Customer Number]\ ,[Salesperson])''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,)',row) conn.commit() cursor.close() print("Done") conn.close() </code></pre> <p>This is what the first rows of the CSV file looks like</p> <p><a href="http://i.stack.imgur.com/NA0je.png" rel="nofollow"><img src="http://i.stack.imgur.com/NA0je.png" alt="enter image description here"></a></p>
1
2016-10-06T14:46:28Z
39,904,616
<p>You are using <code>csv.reader</code> incorrectly. The first argument to <code>.reader</code> is not the path to the CSV file, it is</p> <blockquote> <p>[an] object which supports the iterator protocol and returns a string each time its <code>__next__()</code> method is called — file objects and list objects are both suitable.</p> </blockquote> <p>Hence, according to the example in the <a href="https://docs.python.org/3/library/csv.html" rel="nofollow">documentation</a>, you should be doing something like this:</p> <pre class="lang-python prettyprint-override"><code>import csv with open('cleanNVG.csv', newline='') as csvfile: customer_data = csv.reader(csvfile) for row in customer_data: cursor.execute(sql, tuple(row)) </code></pre>
0
2016-10-06T19:55:55Z
[ "python", "python-3.x", "pymssql" ]
How to send a repeat request in urllib2.urlopen in Python if the first call is just stuck?
39,899,092
<p>I am making a call to a URL in Python using urllib2.urlopen in a while(True) loop</p> <p>My URL keeps changing every time (as there is a change in a particular parameter of the URL every time).</p> <p>My code look as as follows:</p> <pre><code>def get_url(url): '''Get json page data using a specified API url''' response = urlopen(url) data = str(response.read().decode('utf-8')) page = json.loads(data) return page </code></pre> <p>I am calling the above method from the main function by changing the url every time I make the call.</p> <p>What I observe is that after few calls to the function, suddenly (I don;t know why), the code gets stuck at the statement</p> <pre><code>response = urlopen(url) </code></pre> <p>and it just waits and waits...</p> <p>How do I best handle this situation?</p> <p>I want to make sure that if it does not respond within say 10 seconds, I make the same call again.</p> <p>I read about </p> <pre><code>response = urlopen(url, timeout=10) </code></pre> <p>but then what about the repeated call if this fails?</p>
0
2016-10-06T14:46:31Z
39,899,347
<p>Depending on how many retries you want to attempt, use a try/catch inside a loop:</p> <pre><code>while True: try: response = urlopen(url, timeout=10) break except: # do something with the error pass # do something with response data = str(response.read().decode('utf-8')) ... </code></pre> <p>This will silence all exceptions, which may not be ideal (more on that here: <a href="http://stackoverflow.com/questions/2712524/handling-urllib2s-timeout-python">Handling urllib2&#39;s timeout? - Python</a>)</p>
1
2016-10-06T14:57:48Z
[ "python", "http", "urllib2" ]
How to send a repeat request in urllib2.urlopen in Python if the first call is just stuck?
39,899,092
<p>I am making a call to a URL in Python using urllib2.urlopen in a while(True) loop</p> <p>My URL keeps changing every time (as there is a change in a particular parameter of the URL every time).</p> <p>My code look as as follows:</p> <pre><code>def get_url(url): '''Get json page data using a specified API url''' response = urlopen(url) data = str(response.read().decode('utf-8')) page = json.loads(data) return page </code></pre> <p>I am calling the above method from the main function by changing the url every time I make the call.</p> <p>What I observe is that after few calls to the function, suddenly (I don;t know why), the code gets stuck at the statement</p> <pre><code>response = urlopen(url) </code></pre> <p>and it just waits and waits...</p> <p>How do I best handle this situation?</p> <p>I want to make sure that if it does not respond within say 10 seconds, I make the same call again.</p> <p>I read about </p> <pre><code>response = urlopen(url, timeout=10) </code></pre> <p>but then what about the repeated call if this fails?</p>
0
2016-10-06T14:46:31Z
39,899,854
<p>With this method you can retry once. </p> <pre><code>def get_url(url, trial=1): try: '''Get json page data using a specified API url''' response = urlopen(url, timeout=10) data = str(response.read().decode('utf-8')) page = json.loads(data) return page except: if trial == 1: return get_url(url, trial=2) else: return </code></pre>
0
2016-10-06T15:19:41Z
[ "python", "http", "urllib2" ]
How can I store in a variable certain lines in python?
39,899,142
<p>I have this code: </p> <pre><code>with open("/etc/network/interfaces", "r") as file: content = file.read() print content </code></pre> <p>it's working and showing this:</p> <p><a href="http://i.stack.imgur.com/Zauen.png" rel="nofollow"><img src="http://i.stack.imgur.com/Zauen.png" alt="enter image description here"></a></p> <p>How can I store in a variable any word and print that word?</p>
-3
2016-10-06T14:48:27Z
39,899,355
<pre><code>with open("/etc/network/interfaces", "r") as file: for line in file: words=line.split(' ')#break the line into a list of words. print(words[0],words[1]) # </code></pre> <p>I have not tested it, but gives you an idea.</p>
0
2016-10-06T14:58:08Z
[ "python", "linux", "python-2.7", "python-3.x", "debian" ]
How can I store in a variable certain lines in python?
39,899,142
<p>I have this code: </p> <pre><code>with open("/etc/network/interfaces", "r") as file: content = file.read() print content </code></pre> <p>it's working and showing this:</p> <p><a href="http://i.stack.imgur.com/Zauen.png" rel="nofollow"><img src="http://i.stack.imgur.com/Zauen.png" alt="enter image description here"></a></p> <p>How can I store in a variable any word and print that word?</p>
-3
2016-10-06T14:48:27Z
39,899,482
<blockquote> <p>For example, I want to store the word (lo) in the second line in a variable and then print that variable.</p> </blockquote> <p>Use the re module in Python's builtin library:</p> <pre><code>import re with open("/etc/network/interfaces", "r") as file: content = file.readlines() target_word = re.findall("lo()", content[3]) # save the string 'lo' into target word print ''.join(target_word) # prints: lo </code></pre> <p>If you plan on trying to find more words, just add more words to the regular expression. For example, if you wanted to find the words lo and auto, you would say <code>re.findall("lo|auto", content)</code>. If you use this method, I recommend reading the <a href="https://docs.python.org/3/library/re.html" rel="nofollow">official documentation on the <code>re</code> module</a>.</p>
0
2016-10-06T15:03:50Z
[ "python", "linux", "python-2.7", "python-3.x", "debian" ]
overlapping tick labels on plot consisting of several axis - tight_layout not working
39,899,145
<p>In a plot constructed by the code </p> <pre><code>left, width = 0.1, 0.8 rect1 = [left, 0.7, width, 0.2] rect2 = [left, 0.3, width, 0.4] rect3 = [left, 0.1, width, 0.2] fig = plt.figure(facecolor='white') ax1 = fig.add_axes(rect1) ax2 = fig.add_axes(rect2,sharex=ax1) ax3 = fig.add_axes(rect3,sharex=ax1) </code></pre> <p>The max-y-tick-labels of the outer axis (x1,x2) overlap with the max-tick-labels of the inner plot (ax2) which is marked by the red eclipses in the following image:</p> <p><a href="http://i.stack.imgur.com/EUnZQ.png" rel="nofollow"><img src="http://i.stack.imgur.com/EUnZQ.png" alt="enter image description here"></a></p> <p>How can that be prevented, if </p> <pre><code>plt.tight_layout() </code></pre> <p>doesn't work?</p>
-1
2016-10-06T14:48:28Z
39,899,708
<p>By setting the y-labels manually, using </p> <pre><code> ax1.set_yticks([30, 70]) </code></pre> <p>the overlap can be prevented. </p> <p>This solution is not completely satisfying however, since it is hardcoded and not very generic. But it works for this specific problem.</p> <p>Another solution would be to move the y-labels of the middle axis to the right side, as suggested in </p> <p><a href="http://stackoverflow.com/questions/10354397/python-matplotlib-y-axis-ticks-on-right-side-of-plot?rq=1">Python Matplotlib Y-Axis ticks on Right Side of Plot</a></p>
0
2016-10-06T15:13:06Z
[ "python", "matplotlib" ]
How Can I implement functions like mean.median and variance if I have a dictionary with 2 keys in Python?
39,899,162
<p>I have many files in a folder that like this one: <a href="http://i.stack.imgur.com/MitYd.png" rel="nofollow">enter image description here</a></p> <p>and I'm trying to implement a dictionary for data. I'm interested in create it with 2 keys (the first one is the http address and the second is the third field (plugin used), like adblock). The values are referred to different metrics so my intention is to compute the for each site and plugin the mean,median and variance of each metric, once the dictionary has been implemented. For example for the mean, my intention is to consider all the 4-th field values in the file, etc. I tried to write this code but, first of all, I'm not sure that it is correct. <a href="http://i.stack.imgur.com/Kjrqx.png" rel="nofollow">enter image description here</a></p> <p>I read others posts but no-one solved my problem, since they threats or only one key or they don't show how to access the different values inside the dictionary to compute the mean,median and variance. The problem is simple, admitting that the dictionary implementation is ok, in which way must I access the different values for the key1:www.google.it -> key2:adblock ? Any kind oh help is accepted and I'm available for any other answer.</p>
0
2016-10-06T14:49:08Z
39,900,206
<p>You can do what you want using a dictionary, but you should really consider using the <a href="http://pandas.pydata.org/" rel="nofollow">Pandas</a> library. This library is centered around tabular data structure called "DataFrame" that excels in column-wise and row-wise calculations such as the one that you seem to need.</p> <p>To get you started, here is the Pandas code that reads <em>one</em> text file using the <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_fwf.html#pandas.read_fwf" rel="nofollow">read_fwf()</a> method. It also displays the mean and variance for the fourth column:</p> <pre class="lang-py prettyprint-override"><code># import the Pandas library: import pandas as pd # Read the file 'table.txt' into a DataFrame object. Assume # a header-less, fixed-width file like in your example: df = pd.read_fwf("table.txt", header=None) # Show the content of the DataFrame object: print(df) # Print the fourth column (zero-indexed): print(df[3]) # Print the mean for the fourth column: print(df[3].mean()) # Print the variance for the fourth column: print(df[3].var()) </code></pre> <p>There are <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html" rel="nofollow">different ways of selecting columns and rows</a> from a DataFrame object. The square brackets <code>[ ]</code> in the previous examples selected a column in the data frame by column number. If you want to calculate the mean of the fourth column only from those rows that contain <code>adblock</code> in the third column, you can do it like so:</p> <pre class="lang-py prettyprint-override"><code># Print those rows from the data frame that have the value 'adblock' # in the third column (zero-indexed): print(df[df[2] == "adblock"]) # Print only the fourth column (zero-indexed) from that data frame: print(df[df[2] == "adblock"][3]) # Print the mean of the fourth column from that data frame: print(df[df[2] == "adblock"][3].mean()) </code></pre> <p><strong>EDIT:</strong> You can also calculate the mean or variance for more than one column at the same time:</p> <pre class="lang-py prettyprint-override"><code># Use a list of column numbers to calculate the mean for all of them # at the same time: l = [3, 4, 5] print(df[l].mean()) </code></pre> <p><strong>END EDIT</strong></p> <p>If you want to read the data from several files and do the calculations for the concatenated data, you can use the <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.concat.html#pandas.concat" rel="nofollow">concat()</a> method. This method takes a list of DataFrame objects and concatenates them (by default, row-wise). Use the following line to create a DataFrame from all <code>*.txt</code> files in your directory:</p> <pre class="lang-py prettyprint-override"><code>df = pd.concat([pd.read_fwf(file, header=None) for file in glob.glob("*.txt")], ignore_index=True) </code></pre>
1
2016-10-06T15:36:44Z
[ "python", "dictionary" ]
pandas fillna date from another column
39,899,396
<p>Get my test data:</p> <pre><code> import pandas as pd df = {'Id': {1762056: 2.0, 1762055: 1.0}, 'FillDate': {1762056: Timestamp('2015-08-01 00:00:00'), 1762055:Timestamp('2015-08-01 00:00:00')}, 'Date': {1762056: nan, 1762055: nan}, } df = pd.DataFrame(df) </code></pre> <p>Data looks like:</p> <pre><code> Id Date FillDate 1.0 NaN 2015-08-01 2.0 NaN 2015-08-01 </code></pre> <p>So to fill missing date, I do:</p> <pre><code>df['Date'].fillna(df['FillDate'], inplace=True) </code></pre> <p>which gives me</p> <pre><code> Id Date FillDate 1.0 1438387200000000000 2015-08-01 2.0 1438387200000000000 2015-08-01 </code></pre> <p>how to get <code>Date</code> column in date form</p>
1
2016-10-06T14:59:49Z
39,899,458
<p>This worked:</p> <pre><code> df['Date'].fillna(pd.to_datetime(df['FillDate']).dt.date, inplace=True) </code></pre> <p>which gives</p> <pre><code> Id Date FillDate 1.0 2015-08-01 2015-08-01 2.0 2015-08-01 2015-08-01 </code></pre>
3
2016-10-06T15:02:44Z
[ "python", "date", "datetime", "pandas", "data-manipulation" ]
IndentationError: unindent does not match any outer indentation level - tokenize, line 8
39,899,428
<pre><code>import calendar def leapyr(year1, year2): count = 0 while year1 &lt;= year2: if calendar.isleap(year1) == True: count = count + 1 year1 = year1 + 1 print count leapyr(2008, 1015) </code></pre> <p>i have no bloody idea why this doesnt work. I tried "python -m tabnanny thefile.py" it tells me "indentation error: ((tokenize), line 8)" but i have no idea what to make of that information. </p>
-2
2016-10-06T15:01:13Z
39,903,158
<p>Python allows mixing tabs and spaces. Before interpreting the source, python interpreter replaces tabs with spaces in such way that each tab is aligned to 8 spaces (see <a href="https://docs.python.org/2/reference/lexical_analysis.html#indentation" rel="nofollow">the doc on indentation</a>).</p> <p>If your editor is set to show tabs as 8 spaces, that should actually work as expected, but if it shows tabs as 4 spaces, then what it looks like is nothing like what the interpreter sees.</p> <p>The code from the question is:</p> <hr> <p><code>import calendar</code></p> <p><code>def leapyr(year1, year2):</code></p> <p><kbd>4 spaces</kbd><code>count = 0</code></p> <p><kbd>4 spaces</kbd><code>while year1 &lt;= year2:</code></p> <p><kbd>tab</kbd><kbd>4 spaces</kbd><code>if calendar.isleap(year1) == True:</code></p> <p><kbd>tab</kbd><kbd>tab</kbd><kbd>4 spaces</kbd><code>count = count + 1</code></p> <p><kbd>tab</kbd><kbd>tab</kbd><code>year1 = year1 + 1</code></p> <p><kbd>tab</kbd><code>print count</code></p> <p><kbd>tab</kbd></p> <p><code>leapyr(2008, 1015)</code></p> <hr> <p>That is interpreted by Python as:</p> <pre><code>import calendar def leapyr(year1, year2): count = 0 while year1 &lt;= year2: if calendar.isleap(year1) == True: count = count + 1 year1 = year1 + 1 print count leapyr(2008, 1015) </code></pre> <p>This has an indentation error in line 8, at <code>year1 = year1 + 1</code>.</p> <p>The solution is to configure the editor to always use spaces, i.e. to replace tabs with 4 spaces.</p>
0
2016-10-06T18:25:31Z
[ "python" ]
Match Making using GAE + ndb
39,899,451
<p>I have a game in which users contact a server to find a user of their level who wants to play a game. Here is the basic architecture of a game request.</p> <p><a href="http://i.stack.imgur.com/vMIHi.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/vMIHi.jpg" alt="enter image description here"></a></p> <p>I am using <code>ndb</code> to store a waiting queue for each user level in the Google DataStore.</p> <p>I am accessing these queues by their keys to ensure strong consistency (per <a href="https://cloud.google.com/datastore/docs/articles/balancing-strong-and-eventual-consistency-with-google-cloud-datastore/#eventual-consistency-in-cloud-datastore" rel="nofollow">this article</a>). The entities are stored in the queue using a repeated (list of) <a href="https://cloud.google.com/appengine/docs/python/ndb/entity-property-reference#types" rel="nofollow">LocalStructuredProperty</a>.</p> <p>Questions:</p> <ol> <li>An entity is deleted from a waiting queue because it is matched to a request. The transaction is committed but not yet applied. That same entity is matched with another request and deleted. Will this throw an error?</li> <li>These strongly consistent accesses are limited to ~1 write/sec. Is there a better architecture that would eliminate this constraint?</li> </ol> <p>One thing I've considered for the latter question is to maintain multiple queues (whose number grows and shrinks with demand).</p>
3
2016-10-06T15:02:29Z
39,902,281
<p>Not sure about your first question, but you might be able to simulate it with a sleep statement in your transaction.</p> <p>For your second question, there is another architecture that you could use. If the waiting queue duration is relatively short (minutes instead of hours), you might want to use memcache. It will be a lot faster than writing to disk and you can avoid dealing with consistency issues.</p>
2
2016-10-06T17:31:31Z
[ "python", "google-app-engine", "google-cloud-datastore", "app-engine-ndb" ]
Match Making using GAE + ndb
39,899,451
<p>I have a game in which users contact a server to find a user of their level who wants to play a game. Here is the basic architecture of a game request.</p> <p><a href="http://i.stack.imgur.com/vMIHi.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/vMIHi.jpg" alt="enter image description here"></a></p> <p>I am using <code>ndb</code> to store a waiting queue for each user level in the Google DataStore.</p> <p>I am accessing these queues by their keys to ensure strong consistency (per <a href="https://cloud.google.com/datastore/docs/articles/balancing-strong-and-eventual-consistency-with-google-cloud-datastore/#eventual-consistency-in-cloud-datastore" rel="nofollow">this article</a>). The entities are stored in the queue using a repeated (list of) <a href="https://cloud.google.com/appengine/docs/python/ndb/entity-property-reference#types" rel="nofollow">LocalStructuredProperty</a>.</p> <p>Questions:</p> <ol> <li>An entity is deleted from a waiting queue because it is matched to a request. The transaction is committed but not yet applied. That same entity is matched with another request and deleted. Will this throw an error?</li> <li>These strongly consistent accesses are limited to ~1 write/sec. Is there a better architecture that would eliminate this constraint?</li> </ol> <p>One thing I've considered for the latter question is to maintain multiple queues (whose number grows and shrinks with demand).</p>
3
2016-10-06T15:02:29Z
39,916,238
<p>1.- If you do the entity get and the post inside a transaction, then the same entity can not be matched for a game and therefore no error and it remains consistent.</p> <p>2.- The 1 write per second is sthe limit for transactions inside the same entity group. If you need more, you can shard the queue entity.</p> <p>You can use a dedicated memcache or a redis instance to avoid contention. This are much faster than the datastore.</p> <p>See how these guys use tree nodes to do the match making: <a href="https://www.youtube.com/watch?v=9nWyWwY2Onc" rel="nofollow">https://www.youtube.com/watch?v=9nWyWwY2Onc</a></p>
1
2016-10-07T11:33:51Z
[ "python", "google-app-engine", "google-cloud-datastore", "app-engine-ndb" ]
pyaes and the relationship between byte and str in Python 3?
39,899,477
<p>I'm trying to use pyaes (<a href="https://github.com/ricmoo/pyaes/blob/master/README.md" rel="nofollow">https://github.com/ricmoo/pyaes/blob/master/README.md</a>) in Python 3 to encrypt and decrypt text using pyaes. When I encrypt text, I give pyaes a <code>str</code> value i.e.</p> <pre><code>plaintext = 'plain text' key = os.urandom(16) aes = pyaes.AESModeOfOperationCTR(key) ciphertext = aes.encrypt(plaintext) </code></pre> <p>when I decrypt though, I get back a <code>bytes</code> type:</p> <pre><code>aes = pyaes.AESModeOfOperationCTR(key) decrypted_plaintext = aes.decrypt(ciphertext) </code></pre> <p>Printing <code>decrypted_plaintext</code> produces the following output, which seems to contain the original text:</p> <pre><code>b'plain text' </code></pre> <p>But its not quite the same; one is a <code>str</code> the other is a <code>bytes</code>:</p> <pre><code>plaintext == decrypted_plaintext # False </code></pre> <p>I'm struggling to understand the relationship between <code>bytes</code> and whatever Python 3's internal representation of <code>str</code> is. How do I convert the <code>bytes</code> type into <code>str</code> to get my plaintext? </p> <p>I have confirmed that running the examples on the pyaes readme page have the same problem. I'm guessing that is going to be something to do with encodings.</p>
2
2016-10-06T15:03:35Z
39,899,953
<p><code>decrypted_plaintext.decode()</code> will give you a <code>str</code>, which will most likely be what you want. A <code>bytes</code> object is a raw string of bytes in an unspecified encoding. To convert that to a <code>str</code>, you have to tell Python to decode it using <a href="https://docs.python.org/3/library/stdtypes.html#bytes.decode" rel="nofollow"><code>decode()</code></a>. <code>decode()</code> defaults to UTF-8, but you can tell it which encoding to use.</p> <p>I just took a glance at the <a href="https://github.com/ricmoo/pyaes/blob/master/pyaes/aes.py" rel="nofollow">source</a> and I see nothing encoding-specific, so the encoding of the decrypted string should match that of the encrypted string.</p>
0
2016-10-06T15:24:34Z
[ "python", "encryption" ]
pyaes and the relationship between byte and str in Python 3?
39,899,477
<p>I'm trying to use pyaes (<a href="https://github.com/ricmoo/pyaes/blob/master/README.md" rel="nofollow">https://github.com/ricmoo/pyaes/blob/master/README.md</a>) in Python 3 to encrypt and decrypt text using pyaes. When I encrypt text, I give pyaes a <code>str</code> value i.e.</p> <pre><code>plaintext = 'plain text' key = os.urandom(16) aes = pyaes.AESModeOfOperationCTR(key) ciphertext = aes.encrypt(plaintext) </code></pre> <p>when I decrypt though, I get back a <code>bytes</code> type:</p> <pre><code>aes = pyaes.AESModeOfOperationCTR(key) decrypted_plaintext = aes.decrypt(ciphertext) </code></pre> <p>Printing <code>decrypted_plaintext</code> produces the following output, which seems to contain the original text:</p> <pre><code>b'plain text' </code></pre> <p>But its not quite the same; one is a <code>str</code> the other is a <code>bytes</code>:</p> <pre><code>plaintext == decrypted_plaintext # False </code></pre> <p>I'm struggling to understand the relationship between <code>bytes</code> and whatever Python 3's internal representation of <code>str</code> is. How do I convert the <code>bytes</code> type into <code>str</code> to get my plaintext? </p> <p>I have confirmed that running the examples on the pyaes readme page have the same problem. I'm guessing that is going to be something to do with encodings.</p>
2
2016-10-06T15:03:35Z
39,900,016
<p>In Python 3 <code>str</code> type represents a string in unicode format. It is composed of relatively abstract codepoints, that is numbers coding characters. There are several ways to transform (encode) those codepoints to actual bytes which are known as "encodings". utf-8 and utf-16 are some encodings which allow to encode unicode characters.</p> <p><em>Note that some encoding (as ASCII) does <strong>not</strong> allow to encode unicode characters.</em></p> <p>When you encode a <code>str</code> string in Python, you obtain a list of bytes of type <code>bytes</code>. You can then decode this list of bytes to get a <code>str</code>string.</p> <p>The point to keep in mind is that you have to specify an encoding to encode a <code>str</code> string and you have to know the encoding of a <code>bytes</code>string to be able to decode it. If you don't specify encoding, Python will try to encode and decode with its default encoding and you could obtain "random" results.</p> <p>In you specific case, the difference is not visible because all the characters of your strings are ASCII chars and, fortunately, the 128 first codepoints of unicode match the ASCII table.</p> <p>Try to introduce some 'exeotic' characters (like é, ç or Ë) in your string and you will see a difference.</p> <hr> <p>Now, pyaes does not encrypt/decrypt unicode codepoints but bytes. So you have to encode the strings you encrypt and you have to know the used encoding to decode the decrypted strings.</p> <hr> <p>More information in the Python doc:</p> <ul> <li><a href="https://docs.python.org/3/library/stdtypes.html#bytes" rel="nofollow">bytes</a></li> <li><a href="https://docs.python.org/3/library/stdtypes.html#text-sequence-type-str" rel="nofollow">str</a></li> <li><a href="https://docs.python.org/3/reference/lexical_analysis.html#strings" rel="nofollow">strings and bytes litterals</a></li> </ul>
0
2016-10-06T15:27:49Z
[ "python", "encryption" ]