title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
listlengths
1
5
Python - Key detection with simple modules
38,843,224
<p>I'm trying to make a text editor for MicroPython. This 'nano'-like(or vim) text editor should be able to run <em>on</em> the device, what I'm not looking for is modules that would not run on the <strong>ESP8266</strong>.</p> <p>What I'm using at the moment is simple modules such as '<em>sys</em>' and '<em>os</em>'.</p> <p>Any help would be greatly appreciated.</p>
0
2016-08-09T06:07:04Z
38,844,113
<p><strong>EDIT: Added some content of the links to improve the answer</strong></p> <p>Extract of libs that MicroPython have</p> <p><strong>Builtin Functions</strong></p> <p><code>cmath</code> – mathematical functions for complex numbers</p> <p><code>gc</code> – control the garbage collector</p> <p><code>math</code> – mathematical functions</p> <p><code>select</code> – wait for events on a set of streams</p> <p><code>sys</code> – system specific functions</p> <p><code>ubinascii</code> – binary/ASCII conversions</p> <p><code>ucollections</code> – collection and container types</p> <p><code>uhashlib</code> – hashing algorithm</p> <p><code>uheapq</code> – heap queue algorithm</p> <p><code>uio</code> – input/output streams</p> <p><code>ujso</code>n – JSON encoding and decoding</p> <p><code>uos</code> – basic “operating system” services</p> <p><code>ure</code> – regular expressions</p> <p><code>usocket</code> – socket module</p> <p><code>ustruct</code> – pack and unpack primitive data types</p> <p><code>utime</code> – time related functions</p> <p><code>uzlib</code> – zlib decompression</p> <p><strong>MicroPython-specific libraries</strong></p> <p>Functionality specific to the MicroPython implementation is available in the following libraries.</p> <p><code>machine</code> — functions related to the board</p> <p><code>micropython</code> – access and control MicroPython internals</p> <p><code>network</code> — network configuration</p> <p><code>uctypes</code> – access binary data in a structured way</p> <p><strong>More info in:</strong></p> <p><a href="http://docs.micropython.org/en/v1.8.2/pyboard/library/index.html" rel="nofollow">MicroPython libs</a>, if you find it here you'll be able to use it.</p> <p><a href="http://docs.micropython.org/en/latest/esp8266/esp8266/tutorial/intro.html" rel="nofollow">MicroPython for ESP8266</a></p> <p><a href="http://docs.micropython.org/en/v1.8.2/pyboard/index.html" rel="nofollow">MicroPython docs</a></p>
1
2016-08-09T06:58:46Z
[ "python", "text", "editor", "esp8266", "micropython" ]
O_NONBLOCK does not raise exception in Python
38,843,278
<p>I am trying to write a "cleaner" program to release a potential writer which is blocked at a named pipe (because no reader is reading from the pipe). However, the cleaner itself <strong>should not</strong> block when no writer is blocked writing to the pipe. In other words, the "cleaner" must return/terminate immediately, whether there is a blocked writer or not.</p> <p>Therefore I searched for "Python non-blocking read from named pipe", and got these:</p> <ol> <li><a href="http://stackoverflow.com/questions/14345816/how-to-read-named-fifo-non-blockingly">How to read named FIFO non-blockingly?</a></li> <li><a href="http://stackoverflow.com/questions/17449110/fifo-reading-in-a-loop">fifo - reading in a loop</a></li> <li><a href="http://stackoverflow.com/questions/10021759/what-conditions-result-in-an-opened-nonblocking-named-pipe-fifo-being-unavai">What conditions result in an opened, nonblocking named pipe (fifo) being &quot;unavailable&quot; for reads?</a></li> <li><a href="http://stackoverflow.com/questions/5782279/why-does-a-read-only-open-of-a-named-pipe-block">Why does a read-only open of a named pipe block?</a></li> </ol> <p>It seems that they suggest simply using <code>os.open(file_name, os.O_RDONLY | os.O_NONBLOCK)</code> should be fine, which didn't really work on my machine. I think I may have messed up somewhere or misunderstood some of their suggestion/situation. However, I really couldn't figure out what's wrong myself.</p> <p>I found Linux man page (<a href="http://man7.org/linux/man-pages/man2/open.2.html" rel="nofollow">http://man7.org/linux/man-pages/man2/open.2.html</a>), and the explanation of O_NONBLOCK seems consistent with their suggestions but not with my observation on my machine...</p> <p>Just in case it is related, my OS is <strong>Ubuntu 14.04 LTS 64-bit</strong>.</p> <p>Here is my code:</p> <pre><code>import os import errno BUFFER_SIZE = 65536 ph = None try: ph = os.open("pipe.fifo", os.O_RDONLY | os.O_NONBLOCK) os.read(ph, BUFFER_SIZE) except OSError as err: if err.errno == errno.EAGAIN or err.errno == errno.EWOULDBLOCK: raise err else: raise err finally: if ph: os.close(ph) </code></pre> <p>(Don't know how to do Python syntax highlighting...)</p> <p>Originally there is only the second <code>raise</code>, but I found that <code>os.open</code> and <code>os.read</code>, though not blocking, don't raise any exception either... I don't really know how much the writer will write to the buffer! If the non blocking <code>read</code> does not raise exception, how should I know when to stop reading?</p> <hr> <p>Updated on 8/8/2016:</p> <p>This seems to be a workaround/solution that satisfied my need:</p> <pre><code>import os import errno BUFFER_SIZE = 65536 ph = None try: ph = os.open("pipe.fifo", os.O_RDONLY | os.O_NONBLOCK) while True: buffer = os.read(ph, BUFFER_SIZE) if len(buffer) &lt; BUFFER_SIZE: break except OSError as err: if err.errno == errno.EAGAIN or err.errno == errno.EWOULDBLOCK: pass # It is supposed to raise one of these exceptions else: raise err finally: if ph: os.close(ph) </code></pre> <p>It will loop on <code>read</code>. Every time it reads something, it compares the size of the content read with the specified <code>BUFFER_SIZE</code>, until it reaches EOF (writer will then unblock and continue/exit).</p> <p>I still want to know why no exception is raised in that <code>read</code>.</p> <hr> <p>Updated on 8/10/2016:</p> <p>To make it clear, my overall goal is like this.</p> <p>My main program (Python) has a thread serving as the reader. It normally blocks on the named pipe, waiting for "commands". There is a writer program (Shell script) which will write a one-liner "command" to the same pipe in each run.</p> <p>In some cases, a writer starts before my main program starts, or after my main program terminates. In this case, the writer will block on the pipe waiting for a reader. In this way, if later my main program starts, it will read immediately from the pipe to get that "command" from the blocked writer - this is NOT what I want. I want my program to disregard writers that started before it.</p> <p>Therefore, my solution is, during initialization of my reader thread, I do non-blocking read to release the writers, without really executing the "command" they were trying to write to the pipe.</p>
0
2016-08-09T06:10:43Z
38,860,390
<p>This solution is incorrect.</p> <pre><code>while True: buffer = os.read(ph, BUFFER_SIZE) if len(buffer) &lt; BUFFER_SIZE: break </code></pre> <p>This will not actually read everything, it will only read until it gets a partial read. Remember: You are only guaranteed to fill the buffer with regular files, in all other cases it is possible to get a partial buffer before EOF. The correct way to do this is to loop until the actual end of file is reached, which will give a read of length 0. The end of file indicates that there are no writers (they have all exited or closed the fifo).</p> <pre><code>while True: buffer = os.read(ph, BUFFER_SIZE) if not buffer: break </code></pre> <p>However, this will not work correctly in the face of non-blocking IO. It turns out non-blocking IO is completely unnecessary here.</p> <pre><code>import os import fcntl h = os.open("pipe.fifo", os.O_RDONLY | os.O_NONBLOCK) # Now that we have successfully opened it without blocking, # we no longer want the handle to be non-blocking flags = fcntl.fcntl(h, fcntl.F_GETFL) flags &amp;= ~os.O_NONBLOCK fcntl.fcntl(h, fcntl.F_SETFL, flags) try: while True: # Only blocks if there is a writer buf = os.read(h, 65536) if not buf: # This happens when there are no writers break finally: os.close(h) </code></pre> <p>The only scenario which will cause this code to block is if there is an active writer which has opened the fifo but is not writing to it. From what you've described, it doesn't sound like this is the case.</p> <h1>Non-blocking IO doesn't do that</h1> <p>Your program wants to do two things, depending on circumstance:</p> <ol> <li><p>If there are no writers, return immediately.</p></li> <li><p>If there are writers, read data from the FIFO until the writers are done.</p></li> </ol> <p>Non-blocking <code>read()</code> has <em>no effect whatsoever</em> on task #1. Whether you use <code>O_NONBLOCK</code> or not, <code>read()</code> will return <em>immediately</em> in situation #1. So the only difference is in situation #2.</p> <p>In situation #2, your program's goal is to read the entire block of data from the writers. That is exactly how blocking IO works: it waits for the writers to finish, and then <code>read()</code> returns. The whole point of non-blocking IO is to return early if the operation can't complete immediately, which is the opposite of your program's goal—which is to wait until the operation is complete.</p> <p>If you use non-blocking <code>read()</code>, in situation #2, your program will sometimes return early, before the writers have finished their jobs. Or maybe your program will return after reading half of a command from the FIFO, leaving the other (now corrupted) half there. This concern is expressed in your question:</p> <blockquote> <p>If the non blocking read does not raise exception, how should I know when to stop reading?</p> </blockquote> <p>You know when to stop reading because <code>read()</code> returns zero bytes when all writers have closed the pipe. (Conveniently, this is also what happens if there were no writers in the first place.) This is unfortunately not what happens if the writers do not close their end of the pipe when they are done. It is far simpler and more straightforward if the writers close the pipe when done, so this is the recommended solution, even if you need to modify the writers a little bit. If the writers cannot close the pipe for whatever reason, the solution is more complicated.</p> <p>The main use case for non-blocking <code>read()</code> is if your program has some other task to complete while IO goes on in the background.</p>
0
2016-08-09T21:03:44Z
[ "python", "linux", "system-calls" ]
Bug with radiobutton - tkinter
38,843,391
<p>I use Tkinter for make a GUI. I have a window with 2 radiobutton ('Yes' and 'No'), but when I select one, it don't run the script :</p> <pre><code>root = Tk() Button(root, text='TEST', command=root.quit).pack() root.mainloop() master = Tk() v = IntVar() Radiobutton(master, text='Yes', variable=v, value=0).pack() Radiobutton(master, text='No', variable=v, value=1).pack() Button(master, text='Exit', command=master.quit).pack() master.mainloop() print(v.get()) if v.get() == 0: testy = Tk() Label(testy, text='Bad').pack() testy.mainloop() else: testn = Tk() Label(testn, text='Bad').pack() testn.mainloop() </code></pre> <p>If I don't have the first window, it works but with it, it don't.</p> <p>Somebody know how to fix this problem ?</p>
0
2016-08-09T06:17:04Z
38,843,749
<ol> <li>You have initiated several <code>Tk()</code> systems, but there should be only one.</li> <li>If you want to get a new window then use <code>Toplevel()</code></li> <li>No code is executed after <code>mainloop()</code> except for events. The code continues to "flow" after <code>mainloop</code> only after closing the windows. </li> </ol> <p>So here is your code with fixes:</p> <pre><code>from tkinter import * root = Tk() Button(root, text='TEST', command=root.quit).pack() master = Toplevel() v = IntVar() def check_radio(): print(v.get()) if v.get() == 0: Label(Toplevel(), text='Bad').pack() else: Label(Toplevel(), text='Good').pack() Radiobutton(master, text='Yes', variable=v, value=0, command=check_radio).pack() Radiobutton(master, text='No', variable=v, value=1, command=check_radio).pack() Button(master, text='Exit', command=master.quit).pack() root.mainloop() </code></pre> <p>Check carefully, I changed the parents of widgets and other changes. </p>
1
2016-08-09T06:38:14Z
[ "python", "tkinter" ]
Trying to make a development instance for a Python pyramid project
38,843,404
<p>So I have this Python pyramid-based application, and my development workflow has basically just been to upload changed files directly to the production area.</p> <p>Coming close to launch, and obviously that's not going to work anymore.</p> <p>I managed to edit the connection strings and development.ini and point the development instance to a secondary database.</p> <p>Now I just have to figure out how to create another copy of the project somewhere where I can work on things and then make the changes live.</p> <p>At first, I thought that I could just make a copy of the project directory somewhere else and run it with different arguments pointing to the new location. That didn't work.</p> <p>Then, I basically set up an entirely new project called myproject-dev. I went through the setup instructions:</p> <p>I used pcreate, and then setup.py develop, and then I copied over my development.ini from my project and carefully edited the various references to myproject-dev instead of myproject. Then, initialize_myproject-dev_db /var/www/projects/myproject/development.ini</p> <p>Finally, I get a nice pyramid welcome page that everything is working correctly.</p> <p>I thought at that point I could just blow out everything in the project directory and copy over the main project files, but then I got that feeling in the pit of my stomach when I noticed that a lot of things weren't working, like static URLs.</p> <p>Apparently, I'm referencing myproject in includes and also static URLs, and who knows where else.</p> <p>I don't think this idea is going to work, so I've given up for now.</p> <p>Can anyone give me an idea of how people go about setting up a development instance for a Python pyramid project? </p>
2
2016-08-09T06:17:54Z
38,844,340
<p>The first thing you should do, if it's not the case, is version control your project. I'd recommend using git.</p> <p>In addition to the benefits of managing the changes made to the application when developing, it will aldo make it easier to share copies between developers... or with the production deployment. Indeed, production can just be a <code>git clone</code> of the project, just like your development instance.</p> <p>The second thing is you need to install the project in your Python library path. This is how all the <code>import</code>s and <code>include</code>s are going to work.</p> <p>I'd recommend creating a virtual environment for this, with either <code>virtualenv</code> or <code>pew</code>, so that your app (and its dependencies) are "isolated" from the rest of your system and other apps.</p> <p>You probably have a <code>setup.py</code> script in your project. If not, <a href="https://packaging.python.org/distributing/" rel="nofollow">create one</a>. Then install your project with <code>pip install .</code> in production, or <code>pip install -e .</code> in development.</p>
2
2016-08-09T07:13:00Z
[ "python", "pyramid", "pylons" ]
Trying to make a development instance for a Python pyramid project
38,843,404
<p>So I have this Python pyramid-based application, and my development workflow has basically just been to upload changed files directly to the production area.</p> <p>Coming close to launch, and obviously that's not going to work anymore.</p> <p>I managed to edit the connection strings and development.ini and point the development instance to a secondary database.</p> <p>Now I just have to figure out how to create another copy of the project somewhere where I can work on things and then make the changes live.</p> <p>At first, I thought that I could just make a copy of the project directory somewhere else and run it with different arguments pointing to the new location. That didn't work.</p> <p>Then, I basically set up an entirely new project called myproject-dev. I went through the setup instructions:</p> <p>I used pcreate, and then setup.py develop, and then I copied over my development.ini from my project and carefully edited the various references to myproject-dev instead of myproject. Then, initialize_myproject-dev_db /var/www/projects/myproject/development.ini</p> <p>Finally, I get a nice pyramid welcome page that everything is working correctly.</p> <p>I thought at that point I could just blow out everything in the project directory and copy over the main project files, but then I got that feeling in the pit of my stomach when I noticed that a lot of things weren't working, like static URLs.</p> <p>Apparently, I'm referencing myproject in includes and also static URLs, and who knows where else.</p> <p>I don't think this idea is going to work, so I've given up for now.</p> <p>Can anyone give me an idea of how people go about setting up a development instance for a Python pyramid project? </p>
2
2016-08-09T06:17:54Z
38,886,655
<p>Here's how I managed my last Pyramid app:</p> <p>I had both a <code>development.ini</code> and a <code>production.ini</code>. I actually had a <code>development.local.ini</code> in addition to the other two - one for local development, one for our "test" system, and one for production. I used git for version control, and had a main branch for production deployments. On my prod server I created the virtual environment, etc., then would pull my main branch and run using the <code>production.ini</code> config file. Updates basically involved jumping back into the virtualenv and pulling latest updates from the repo, then restarting the pyramid server. </p>
1
2016-08-11T03:11:20Z
[ "python", "pyramid", "pylons" ]
I'm trying to create ashapefile of x,y coordinates from a txt. file but am getting the following error
38,843,492
<p>Traceback (most recent call last): File "C:\Users\Brett\Desktop\Jefferson_final.py", line 31, in point = arcpy.Point(coordinate[0],coordinate[1]) IndexError: list index out of range</p> <p>Here is my script</p> <pre><code>import arcpy import fileinput import os import string arcpy.env.workspace = "C:\Users\Brett\Desktop\San Clemente" arcpy.env.overwriteOutput = True outFolder = "C:\Users\Brett\Desktop\San Clemente" output = open("result.txt", "w") fc = "metersSC1.shp" inputFile = "C:\Users\Brett\Desktop\San Clemente\San Clemente Lat Long.txt" name = "" for line in inputFile: lineSegment = line.split(": ") if lineSegment[0]== "spatialReference": spatRef = spatRef = arcpy.SpatialReference(26946) arcpy.CreateFeatureclass_management(outFolder, fc, "POINT", "", "", "", spatRef) arcpy.AddField_management(fc, "NAME", "TEXT") cursor = arcpy.da.InsertCursor(fc, ["","SHAPE@"]) array = arcpy.Array() elif lineSegment[0] =="NAME": if len(array) &gt; 0: polygon = arcpy.Polygon(pointList) cursor.insertRow((name,polygon)) name = lineSegment[0] else: coordinate = line.split(",") point = arcpy.Point(coordinate[0],coordinate[1]) pointList.add(point) polygon = arcpy.Polygon(array) cursor.insertRow((name, polygon)) print "COORDINATES ADDED" </code></pre>
-2
2016-08-09T06:23:01Z
38,843,661
<p>You are not opening the file input_data and reading the input data from it then splitting the data.</p> <pre><code>inputname = r"C:\Users\Brett\Desktop\San Clemente\San Clemente Lat Long.txt" inputdata = [l.spilt(',') for l in open(inputname).readlines()] </code></pre> <p>Should get you further - you will also have to convert x &amp; y to numeric values they will be strings to start with.</p>
2
2016-08-09T06:32:50Z
[ "python", "arcpy", "arcmap" ]
Function templates in python
38,843,599
<p>I would like to know how would I use similar code to <strong>template &lt; typename T></strong> in python, as it is used in the C++ code example:</p> <pre><code>template &lt;typename T&gt; unsigned int counting_bit(unsigned int v){ v = v - ((v &gt;&gt; 1) &amp; (T)~(T)0/3); // temp v = (v &amp; (T)~(T)0/15*3) + ((v &gt;&gt; 2) &amp; (T)~(T)0/15*3); // temp v = (v + (v &gt;&gt; 4)) &amp; (T)~(T)0/255*15; // temp return v; } </code></pre> <p>How would I typecast objects with variable typename in python the same way as it is mentioned in C++?</p>
-1
2016-08-09T06:29:47Z
38,843,653
<p>Just pass the type to the function.</p> <p>For example, see this (useless) function:</p> <pre><code>def converter(x, required_type): return required_type(x) converter('1', int) converter('1', float) </code></pre>
2
2016-08-09T06:32:34Z
[ "python", "c++", "templates", "function-templates" ]
Function templates in python
38,843,599
<p>I would like to know how would I use similar code to <strong>template &lt; typename T></strong> in python, as it is used in the C++ code example:</p> <pre><code>template &lt;typename T&gt; unsigned int counting_bit(unsigned int v){ v = v - ((v &gt;&gt; 1) &amp; (T)~(T)0/3); // temp v = (v &amp; (T)~(T)0/15*3) + ((v &gt;&gt; 2) &amp; (T)~(T)0/15*3); // temp v = (v + (v &gt;&gt; 4)) &amp; (T)~(T)0/255*15; // temp return v; } </code></pre> <p>How would I typecast objects with variable typename in python the same way as it is mentioned in C++?</p>
-1
2016-08-09T06:29:47Z
38,843,744
<p>Python is strongly, dynamically typed.</p> <p><strong>Dynamic</strong> typing means that runtime objects have a type, as opposed to static typing where variables have a type</p> <p><strong>Strong</strong> typing means that the type of a value doesn't suddenly change. A string containing only digits doesn't magically become a number, as may happen in Perl. Every change of type requires an explicit conversion.</p> <p>You dont need to have templates in python for different types to work with same function</p> <p>For example</p> <pre><code>#!/usr/bin/python def less(a,b): return a &lt; b; less(1,2) #returns True less("def","abc") #returns False less("def",1) #fails with error unorderable types: str() &lt; int() </code></pre>
0
2016-08-09T06:37:55Z
[ "python", "c++", "templates", "function-templates" ]
Function templates in python
38,843,599
<p>I would like to know how would I use similar code to <strong>template &lt; typename T></strong> in python, as it is used in the C++ code example:</p> <pre><code>template &lt;typename T&gt; unsigned int counting_bit(unsigned int v){ v = v - ((v &gt;&gt; 1) &amp; (T)~(T)0/3); // temp v = (v &amp; (T)~(T)0/15*3) + ((v &gt;&gt; 2) &amp; (T)~(T)0/15*3); // temp v = (v + (v &gt;&gt; 4)) &amp; (T)~(T)0/255*15; // temp return v; } </code></pre> <p>How would I typecast objects with variable typename in python the same way as it is mentioned in C++?</p>
-1
2016-08-09T06:29:47Z
38,844,698
<p>DeepSpace's answer could be embellished to make things more C++-like by using Python's closures to do something like the following to create functions for specific types by applying the template. It also shows how easy it is in Python to obtain and use the type of another variable. </p> <pre><code>def converter_template(typename): def converter(v): t = typename(v) # convert to numeric for multiply return type(v)(t * 2) # value returned converted back to original type return converter int_converter = converter_template(int) float_converter = converter_template(float) print('{!r}'.format(int_converter('21'))) # '42' print('{!r}'.format(float_converter('21'))) # '42.0' </code></pre>
1
2016-08-09T07:33:42Z
[ "python", "c++", "templates", "function-templates" ]
Converts a date from the form yyyy/mm/dd to the form month_name day, year
38,843,636
<pre><code>MONTHS = ['January', 'February', 'Match', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] def date_convert(s): y = s[:4] m = int(s[5:-3]) d = s[8:] if m &lt; 10: nm = int(m[1:]) month_name = MONTHS[nm - 1] else: month_name = MONTHS[m - 1] result= ?????? return result s = '2000/06/24' r = date_convert(s) print(r) </code></pre> <p>I am working on final exam view(python 3.0 +), and I have been doing practices all day. I suddenly don't know how to put month_name a , y together as a string use 'result' ( result = ???). and then return it to main program. Here is the result I need : convert 2000/06/24 to June 24, 2000. My brain is not working now, please someone helps me. Thank you so much. I cannot use any bulit-in functions. pleases just help me put anything together as a string. Thanks again.</p>
-2
2016-08-09T06:31:50Z
38,844,057
<p>Try this:</p> <pre><code>from datetime import datetime d = "2000/06/24" date_obj = datetime.strptime(d, "%Y/%m/%d") formatted_date = datetime.strftime(date_obj, "%B %d %Y") print(formatted_date) </code></pre> <p>So you can make d as a variable to be passed as an argument in the function you are using. </p> <pre><code>strptime(): is used to convert the string of the date to a date object. strftime(): is used to convert the date object to string. </code></pre>
0
2016-08-09T06:55:27Z
[ "python" ]
Converts a date from the form yyyy/mm/dd to the form month_name day, year
38,843,636
<pre><code>MONTHS = ['January', 'February', 'Match', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] def date_convert(s): y = s[:4] m = int(s[5:-3]) d = s[8:] if m &lt; 10: nm = int(m[1:]) month_name = MONTHS[nm - 1] else: month_name = MONTHS[m - 1] result= ?????? return result s = '2000/06/24' r = date_convert(s) print(r) </code></pre> <p>I am working on final exam view(python 3.0 +), and I have been doing practices all day. I suddenly don't know how to put month_name a , y together as a string use 'result' ( result = ???). and then return it to main program. Here is the result I need : convert 2000/06/24 to June 24, 2000. My brain is not working now, please someone helps me. Thank you so much. I cannot use any bulit-in functions. pleases just help me put anything together as a string. Thanks again.</p>
-2
2016-08-09T06:31:50Z
38,844,084
<p>Usually you don't parse/reformat/convert dates in Python manually. There are many beautiful functions and even modules for that. The problem is that the date conversion process though may seem simple is complicated and error prone. That's why it is not reimplemented every time, but implemented in so many details as possible in Python core modules (in <code>datetime</code> first of all).</p> <p>Use <code>strptime</code> to parse the date and <code>strftime</code> to format the date:</p> <pre><code>&gt;&gt;&gt; import datetime &gt;&gt;&gt; s = datetime.datetime.strptime("2000/06/24", "%Y/%m/%d") &gt;&gt;&gt; print s.strftime('%B %d %Y') </code></pre> <p>The both functions support special formating characters like <code>%Y</code> and <code>%m</code>:</p> <pre><code>%Y Year with century as a decimal number. %m Month as a decimal number [01,12]. %d Day of the month as a decimal number [01,31]. %B Locale’s full month name. </code></pre> <p>You can find more on it here:</p> <ul> <li><a href="https://docs.python.org/2/library/time.html" rel="nofollow">https://docs.python.org/2/library/time.html</a></li> </ul> <p>Also, please check this question, that it very close to yours for additional answers:</p> <ul> <li><a href="http://stackoverflow.com/questions/2316987/converting-a-string-to-a-formatted-date-time-string-using-python">Converting a string to a formatted date-time string using Python</a></li> </ul> <p>If it is an excercise, and you must implement the conversion function on your own, that's also fine. Your implementation is almost correct but you've missed some points:</p> <pre><code>def date_convert(s): "Manual date conversion" y = s[:4] m = int(s[5:-3]) d = s[8:] month_name = MONTHS[m - 1] return "%s %s, %s" % (month_name, d, y) </code></pre> <p>You don't need <code>if</code> in your function. And you don't need two int conversions, you need only the first one.</p> <p>You can write the same more briefly:</p> <pre><code>def date_convert(s): "Manual date conversion" return "%s %s, %s" % (MONTHS[int(s[5:-3])-1], s[8:], s[:4]) </code></pre>
0
2016-08-09T06:57:05Z
[ "python" ]
Converts a date from the form yyyy/mm/dd to the form month_name day, year
38,843,636
<pre><code>MONTHS = ['January', 'February', 'Match', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] def date_convert(s): y = s[:4] m = int(s[5:-3]) d = s[8:] if m &lt; 10: nm = int(m[1:]) month_name = MONTHS[nm - 1] else: month_name = MONTHS[m - 1] result= ?????? return result s = '2000/06/24' r = date_convert(s) print(r) </code></pre> <p>I am working on final exam view(python 3.0 +), and I have been doing practices all day. I suddenly don't know how to put month_name a , y together as a string use 'result' ( result = ???). and then return it to main program. Here is the result I need : convert 2000/06/24 to June 24, 2000. My brain is not working now, please someone helps me. Thank you so much. I cannot use any bulit-in functions. pleases just help me put anything together as a string. Thanks again.</p>
-2
2016-08-09T06:31:50Z
38,844,170
<pre><code>MONTHS = ['January', 'February', 'Match', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] def date_convert(s): y = s[:4] m = int(s[5:-3]) d = s[8:] month_name = MONTHS[m-1] result= month_name + ' ' + d + ' ' + y return result s = '2000/06/24' r = date_convert(s) print r </code></pre> <p>I did in python 2 just change print function</p>
0
2016-08-09T07:02:47Z
[ "python" ]
The sum of indexes within nested lists. Adding elements from separate lists
38,843,761
<p>Just doing an exercise question as follows: Take a ' number square' as a parameter and returns a list of the <strong>column sums</strong>.</p> <p>e.g</p> <pre><code>square = [ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16] ] </code></pre> <p>Result should be =</p> <pre><code>[28, 32, 36, 40] </code></pre> <p>What I have so far:</p> <pre><code>def column_sums(square): col_list = [] for i in range(len(square)): col_sum = 0 for j in range(len(square[i])): col_sum += square[j] col_list.append(col_sum) return col_list </code></pre> <p>So I think I have all the parameters laid out, with all the indexing correct, but I am stuck because I get an error</p> <pre><code>builtins.TypeError: unsupported operand type(s) for +=: 'int' and 'list' </code></pre> <p>Which shouldn't happen if I am referencing the element within the list I thought.</p> <p>Also it's probably easier to use the SUM command here, but couldn't figure out a way to use it cleanly.</p> <p>Adding elements from separate lists via indexing.</p>
1
2016-08-09T06:38:41Z
38,843,801
<p>It should be <code>col_sum += square[j][i]</code> since you want to access the element at position <code>j</code> of the list at position <code>i</code>.</p>
1
2016-08-09T06:40:46Z
[ "python", "python-3.x" ]
The sum of indexes within nested lists. Adding elements from separate lists
38,843,761
<p>Just doing an exercise question as follows: Take a ' number square' as a parameter and returns a list of the <strong>column sums</strong>.</p> <p>e.g</p> <pre><code>square = [ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16] ] </code></pre> <p>Result should be =</p> <pre><code>[28, 32, 36, 40] </code></pre> <p>What I have so far:</p> <pre><code>def column_sums(square): col_list = [] for i in range(len(square)): col_sum = 0 for j in range(len(square[i])): col_sum += square[j] col_list.append(col_sum) return col_list </code></pre> <p>So I think I have all the parameters laid out, with all the indexing correct, but I am stuck because I get an error</p> <pre><code>builtins.TypeError: unsupported operand type(s) for +=: 'int' and 'list' </code></pre> <p>Which shouldn't happen if I am referencing the element within the list I thought.</p> <p>Also it's probably easier to use the SUM command here, but couldn't figure out a way to use it cleanly.</p> <p>Adding elements from separate lists via indexing.</p>
1
2016-08-09T06:38:41Z
38,844,035
<p>You should change the line of summing to:</p> <pre><code>col_sum += square[j][i] </code></pre> <p>because square[j] is the <code>j'th</code> row (list), but you need the current column, which is the <code>i'th</code> element in that row.</p> <p>But here is my solution using <code>sum</code> and list comprehensions:</p> <pre><code>def column_sums2(square): def col(i): return [row[i] for row in square] return [sum(col(i)) for i in range(len(square))] </code></pre>
1
2016-08-09T06:54:28Z
[ "python", "python-3.x" ]
The sum of indexes within nested lists. Adding elements from separate lists
38,843,761
<p>Just doing an exercise question as follows: Take a ' number square' as a parameter and returns a list of the <strong>column sums</strong>.</p> <p>e.g</p> <pre><code>square = [ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16] ] </code></pre> <p>Result should be =</p> <pre><code>[28, 32, 36, 40] </code></pre> <p>What I have so far:</p> <pre><code>def column_sums(square): col_list = [] for i in range(len(square)): col_sum = 0 for j in range(len(square[i])): col_sum += square[j] col_list.append(col_sum) return col_list </code></pre> <p>So I think I have all the parameters laid out, with all the indexing correct, but I am stuck because I get an error</p> <pre><code>builtins.TypeError: unsupported operand type(s) for +=: 'int' and 'list' </code></pre> <p>Which shouldn't happen if I am referencing the element within the list I thought.</p> <p>Also it's probably easier to use the SUM command here, but couldn't figure out a way to use it cleanly.</p> <p>Adding elements from separate lists via indexing.</p>
1
2016-08-09T06:38:41Z
38,844,252
<p>A more simpler solution would be to <em>transpose</em> the list of lists with <code>zip</code> and take the <code>sum</code> across each new sublist:</p> <pre><code>def column_sums(square): return [sum(i) for i in zip(*square)] </code></pre> <p><code>zip(*square)</code> <em>unpacks</em> the list of lists and returns all items from each column (<em>zipped</em> as tuples) in successions.</p> <pre><code>&gt;&gt;&gt; column_sums(square) [28, 32, 36, 40] </code></pre> <hr> <p>You could also use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.sum.html" rel="nofollow"><code>numpy.sum</code></a> to do this by setting the <code>axis</code> parameter to <code>0</code>, meaning sum along rows (i.e. sum on each column):</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; square = np.array(square) &gt;&gt;&gt; square.sum(axis=0) array([28, 32, 36, 40]) </code></pre>
2
2016-08-09T07:08:06Z
[ "python", "python-3.x" ]
passing a 2D array from python to swagger
38,843,886
<p>I am confused by why this doesn't work. Here is my swagger.yaml part where it defines what a result is. The code that links to this returns an array of arrays: </p> <blockquote> <p>[[string,float],....]</p> </blockquote> <p>when i switch this array to </p> <blockquote> <p>[string,string,...]</p> </blockquote> <p>everything works.</p> <pre><code>results: type: "object" required: - "content" properties: content: type: "array" items: type: "array" items: {} </code></pre> <p>Not sure what is going on with the 2D array. The swagger keeps complaining:</p> <blockquote> <pre><code>raise TypeError('Expected bytes') TypeError: Expected bytes </code></pre> </blockquote>
1
2016-08-09T06:45:32Z
38,982,663
<p>Nested arrays were not permitted in swagger until 2.0.</p> <p>If you are using 1.2 or earlier then you cannot directly nest arrays. See <a href="http://docs.swagger.io/spec.html" rel="nofollow">section 4.3.3</a> of the 1.2 spec, specifically it indicates 'A container MUST NOT be nested in another container.'</p> <p>Nested arrays are now allowed for 2.0, but my <em>limited</em> understanding is that the array elements must all be of the same type. This comes from the section named 'ITEMS OBJECT' about a third of the way down <a href="http://swagger.io/specification/" rel="nofollow">the 2.0 spec</a>.</p> <p>I can't give you much useful advice beyond that. The github issues pages are quite interesting as a number of issues related to your problem are covered in a 'why not do it this way instead' type manner. <a href="https://github.com/OAI/OpenAPI-Specification/issues/53" rel="nofollow">Issue 53</a> seems relevant to your problem, for example and also describes the nested array of array limitations (pre 2.0) and describes ways around it.</p> <p>I hope this helps</p>
2
2016-08-16T19:07:08Z
[ "python", "multidimensional-array", "swagger" ]
Matching geographic time series to known ways
38,844,131
<p>I just started a project where I have a set of path data (given as points with timestamp) and want to match this data to given ways and points from other databases (such as openstreetmap). My task is to determine if a record matches a stored way and to correct for possible distortions in the data. The data size of my record is rather small (a time series of several hundred points), but the database of existing ways is much larger (e.g. the complete openstreetmap database).</p> <p>As this is the first time that I work with geometric data, I am a bit clueless how to implement this efficiently. I'm sure that there are already algorithms that I could use, but my Google searches so far didn't reveal anything. I want to avoid coming up with complicated solutions to later find out that there are much simpler solutions well known.</p> <p>What would be an efficient way of solving that problem? I tagged it with Python as this would be my preferred implementation, but I'm open to other languages as well.</p> <p>Thanks</p>
0
2016-08-09T06:59:58Z
38,845,058
<p>With the help from another user I found the answer to my question. The topic I was looking for is called map matching, and I found a Github page that gives an overview and some code to work with: <a href="https://github.com/graphhopper/map-matching" rel="nofollow">https://github.com/graphhopper/map-matching</a></p> <p>Here's the Wikipedia article for that topic: <a href="https://en.wikipedia.org/wiki/Map_matching" rel="nofollow">https://en.wikipedia.org/wiki/Map_matching</a></p>
0
2016-08-09T07:52:36Z
[ "python", "geolocation", "computational-geometry" ]
Send data from django to html
38,844,310
<p>I want to get data from database and send that to html page using django-python.</p> <p>What I'm doing in python file is</p> <pre><code>def module1(request): table_list=student.objects.all() context={'table_list' : table_list} return render(request,'index.html',context) </code></pre> <p>And in html is </p> <pre><code>&lt;div class="rightbox"&gt; In right box. data is :&lt;br&gt; &lt;br&gt; {% if table_list %} &lt;ul&gt; {% for item in table_list %} &lt;li&gt;{{ item.name }}&lt;/li&gt; &lt;li&gt;{{ item.address }}&lt;/li&gt; &lt;li&gt;{{ item.mob_no }}&lt;/li&gt; {% endfor %} &lt;/ul&gt; {% else %} &lt;p&gt;somethings is wrong&lt;/p&gt; {% endif %} &lt;/div&gt; </code></pre> <p>Nothing is being sent to html file. It is constantly going in else block. I don't know where I'm making mistake.Please help me.</p>
0
2016-08-09T07:11:13Z
38,845,084
<p>So far as we don't see your <code>student</code> model (which should be in your <code>models.py</code> and be imported in your <code>vievs.py</code>) and your code doesn't throw any exceptions it seems that your <code>table_list</code> is empty. To iterate it in more convenient way you can use built in <code>for ... empty</code> template tag:</p> <pre><code>&lt;div class="rightbox"&gt; In right box. data is :&lt;br&gt; &lt;br&gt; &lt;ul&gt; {% for item in table_list %} &lt;li&gt;{{ item.name }}&lt;/li&gt; &lt;li&gt;{{ item.address }}&lt;/li&gt; &lt;li&gt;{{ item.mob_no }}&lt;/li&gt; {% empty %} &lt;p&gt;somethings is wrong&lt;/p&gt; {% endfor %} &lt;/ul&gt; &lt;/div&gt; </code></pre> <p>Try this and see what happens. If you'll find yourself in <code>{% empty %}</code> block - your <code>table_list</code> is empty which is points to empty table in database.</p> <p>Also check <a href="https://docs.djangoproject.com/en/1.9/ref/templates/builtins/#for-empty" rel="nofollow">docs</a> for this tag.</p>
0
2016-08-09T07:54:48Z
[ "python", "html", "django" ]
filtering out some lines
38,844,451
<p>I have a text file (a.txt). here a small part of that:</p> <pre class="lang-none prettyprint-override"><code>ENSG00000060642.6 0,023999998 0,015999999 0,666666667 0,006410256 0,006410256 1,000000073 0,016393442 0,016393442 1 0,020202022 0,030303031 1,499999908 ENSG00000149136.3 0,03508772 0,01754386 0,5 0,068627447 0,029411765 0,428571456 0,078947365 0,065789476 0,833333396 0,066666663 0,066666663 1 ENSG00000104889.4 0 0 #DIV/0! 0 0 #DIV/0! 0 0 #DIV/0! 0 0 #DIV/0! ENSG00000157827.15 0,055555556 0,037037037 0,666666667 0,032258064 0,048387095 1,5 0,150000006 0,024999999 0,16666665 0,222222224 0,037037037 0,166666667 ENSG00000146067.11 0 0 #DIV/0! 0 0 #DIV/0! 0 0 #DIV/0! 0 0 #DIV/0! ENSG00000167700.4 0,299999982 0 0 0,071428567 0,071428567 1 0 0 #DIV/0! 0 0 #DIV/0! ENSG00000172137.14 0 0 #DIV/0! 0 0 #DIV/0! 0 0 #DIV/0! 1 0 0 ENSG00000178776.4 0 0 #DIV/0! 0 0 #DIV/0! 0 0 #DIV/0! 0 0 #DIV/0! </code></pre> <p>I want to filter out all lines including "#DIV/0!", even if there is only one "#DIV/0!", and make a new text file.</p>
2
2016-08-09T07:19:45Z
38,844,494
<pre><code>for line in open('a.txt').read().splitlines(): if '#DIV/0!' not in line: print(line) </code></pre>
0
2016-08-09T07:21:38Z
[ "python", "file" ]
filtering out some lines
38,844,451
<p>I have a text file (a.txt). here a small part of that:</p> <pre class="lang-none prettyprint-override"><code>ENSG00000060642.6 0,023999998 0,015999999 0,666666667 0,006410256 0,006410256 1,000000073 0,016393442 0,016393442 1 0,020202022 0,030303031 1,499999908 ENSG00000149136.3 0,03508772 0,01754386 0,5 0,068627447 0,029411765 0,428571456 0,078947365 0,065789476 0,833333396 0,066666663 0,066666663 1 ENSG00000104889.4 0 0 #DIV/0! 0 0 #DIV/0! 0 0 #DIV/0! 0 0 #DIV/0! ENSG00000157827.15 0,055555556 0,037037037 0,666666667 0,032258064 0,048387095 1,5 0,150000006 0,024999999 0,16666665 0,222222224 0,037037037 0,166666667 ENSG00000146067.11 0 0 #DIV/0! 0 0 #DIV/0! 0 0 #DIV/0! 0 0 #DIV/0! ENSG00000167700.4 0,299999982 0 0 0,071428567 0,071428567 1 0 0 #DIV/0! 0 0 #DIV/0! ENSG00000172137.14 0 0 #DIV/0! 0 0 #DIV/0! 0 0 #DIV/0! 1 0 0 ENSG00000178776.4 0 0 #DIV/0! 0 0 #DIV/0! 0 0 #DIV/0! 0 0 #DIV/0! </code></pre> <p>I want to filter out all lines including "#DIV/0!", even if there is only one "#DIV/0!", and make a new text file.</p>
2
2016-08-09T07:19:45Z
38,844,654
<pre><code>new_file = open('output.txt' , 'w') for line in open('a.txt').read().splitlines(): if '#DIV/0!' not in line: new_file.write(line) new_file.close() </code></pre>
0
2016-08-09T07:31:12Z
[ "python", "file" ]
filtering out some lines
38,844,451
<p>I have a text file (a.txt). here a small part of that:</p> <pre class="lang-none prettyprint-override"><code>ENSG00000060642.6 0,023999998 0,015999999 0,666666667 0,006410256 0,006410256 1,000000073 0,016393442 0,016393442 1 0,020202022 0,030303031 1,499999908 ENSG00000149136.3 0,03508772 0,01754386 0,5 0,068627447 0,029411765 0,428571456 0,078947365 0,065789476 0,833333396 0,066666663 0,066666663 1 ENSG00000104889.4 0 0 #DIV/0! 0 0 #DIV/0! 0 0 #DIV/0! 0 0 #DIV/0! ENSG00000157827.15 0,055555556 0,037037037 0,666666667 0,032258064 0,048387095 1,5 0,150000006 0,024999999 0,16666665 0,222222224 0,037037037 0,166666667 ENSG00000146067.11 0 0 #DIV/0! 0 0 #DIV/0! 0 0 #DIV/0! 0 0 #DIV/0! ENSG00000167700.4 0,299999982 0 0 0,071428567 0,071428567 1 0 0 #DIV/0! 0 0 #DIV/0! ENSG00000172137.14 0 0 #DIV/0! 0 0 #DIV/0! 0 0 #DIV/0! 1 0 0 ENSG00000178776.4 0 0 #DIV/0! 0 0 #DIV/0! 0 0 #DIV/0! 0 0 #DIV/0! </code></pre> <p>I want to filter out all lines including "#DIV/0!", even if there is only one "#DIV/0!", and make a new text file.</p>
2
2016-08-09T07:19:45Z
38,844,890
<pre><code>with open('a.txt') as f, open('b.txt', 'w') as new_file: new_file.writelines([line for line in f if '#DIV/0!' not in line]) </code></pre> <hr> <p>Edit:</p> <p>This method is probably the fastest. But as discussed with @martineau earlier, it could not be the best answer here depending of the size your file.</p> <ul> <li><p><a href="https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions" rel="nofollow"><code>list comprehension</code></a> <code>[line for line in f if '#DIV/0!' not in<br> line]</code> is very common in python, it replace the piece of code:</p> <pre><code>l = [] for line in f: if '#DIV/0!' not in line: l.append(line) </code></pre></li> </ul> <p>but it is more optimised (see here for an explanation: <a href="http://blog.cdleary.com/2010/04/efficiency-of-list-comprehensions/" rel="nofollow">Efficiency of list comprehensions</a>)</p> <p><a href="https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions" rel="nofollow"><code>list comprehension</code></a> load everything in memory and thus can cause a buffer overflow in the case of huge amount of data.</p> <p>That's why here, using an incremental method (@martineau's one) is safer when you are not sure how many data you will process!</p> <ul> <li>The <a href="https://docs.python.org/3/reference/compound_stmts.html#with" rel="nofollow"><code>with</code></a> statement replace a try and catch. It also automatically close the file after the block. As you can see, it could also be nested: you can open several file with one <a href="https://docs.python.org/3/reference/compound_stmts.html#with" rel="nofollow"><code>with</code></a> statement.</li> </ul>
1
2016-08-09T07:44:20Z
[ "python", "file" ]
filtering out some lines
38,844,451
<p>I have a text file (a.txt). here a small part of that:</p> <pre class="lang-none prettyprint-override"><code>ENSG00000060642.6 0,023999998 0,015999999 0,666666667 0,006410256 0,006410256 1,000000073 0,016393442 0,016393442 1 0,020202022 0,030303031 1,499999908 ENSG00000149136.3 0,03508772 0,01754386 0,5 0,068627447 0,029411765 0,428571456 0,078947365 0,065789476 0,833333396 0,066666663 0,066666663 1 ENSG00000104889.4 0 0 #DIV/0! 0 0 #DIV/0! 0 0 #DIV/0! 0 0 #DIV/0! ENSG00000157827.15 0,055555556 0,037037037 0,666666667 0,032258064 0,048387095 1,5 0,150000006 0,024999999 0,16666665 0,222222224 0,037037037 0,166666667 ENSG00000146067.11 0 0 #DIV/0! 0 0 #DIV/0! 0 0 #DIV/0! 0 0 #DIV/0! ENSG00000167700.4 0,299999982 0 0 0,071428567 0,071428567 1 0 0 #DIV/0! 0 0 #DIV/0! ENSG00000172137.14 0 0 #DIV/0! 0 0 #DIV/0! 0 0 #DIV/0! 1 0 0 ENSG00000178776.4 0 0 #DIV/0! 0 0 #DIV/0! 0 0 #DIV/0! 0 0 #DIV/0! </code></pre> <p>I want to filter out all lines including "#DIV/0!", even if there is only one "#DIV/0!", and make a new text file.</p>
2
2016-08-09T07:19:45Z
38,844,988
<p>You could do it this way which is incremental (so it doesn't read the entire file into memory at one time):</p> <pre><code>from itertools import ifilter with open('a.txt', 'r') as inf, open('new.txt', 'w') as outf: outf.writelines(ifilter(lambda line: '#DIV/0!' not in line, inf)) </code></pre>
1
2016-08-09T07:49:02Z
[ "python", "file" ]
yowsup2 no module named _sqlite3
38,844,477
<p>I'm having the below error when I try to run the yowsup-cli command to send a message. This is the command I'm running: </p> <pre><code>yowsup-cli demos -c /etc/yowsup-cli.conf -s 'phone number' "text" </code></pre> <p>I'm running it on Linux CentOS 5.11 which comes with python 2.4 preinstalled. I installed python 2.7 which is required for yowsup2 to run but I'm encountering the following error:</p> <p>ERROR:</p> <pre><code>Traceback (most recent call last): File "/usr/bin/yowsup-cli", line 368, in &lt;module&gt; if not parser.process(): File "/usr/bin/yowsup-cli", line 272, in process self.startSendClient() File "/usr/bin/yowsup-cli", line 323, in startSendClient not self.args["unmoxie"]) File "/usr/lib/python2.7/site-packages/yowsup/demos/sendclient/stack.py", line 20, in __init__ .pushDefaultLayers(encryptionEnabled)\ File "/usr/lib/python2.7/site-packages/yowsup/stacks/yowstack.py", line 51, in pushDefaultLayers defaultLayers = YowStackBuilder.getDefaultLayers(axolotl) File "/usr/lib/python2.7/site-packages/yowsup/stacks/yowstack.py", line 73, in getDefaultLayers from yowsup.layers.axolotl import AxolotlSendLayer, AxolotlControlLayer, AxolotlReceivelayer File "/usr/lib/python2.7/site-packages/yowsup/layers/axolotl/__init__.py", line 1, in &lt;module&gt; from .layer_send import AxolotlSendLayer File "/usr/lib/python2.7/site-packages/yowsup/layers/axolotl/layer_send.py", line 16, in &lt;module&gt; from .layer_base import AxolotlBaseLayer File "/usr/lib/python2.7/site-packages/yowsup/layers/axolotl/layer_base.py", line 1, in &lt;module&gt; from yowsup.layers.axolotl.store.sqlite.liteaxolotlstore import LiteAxolotlStore File "/usr/lib/python2.7/site-packages/yowsup/layers/axolotl/store/sqlite/liteaxolotlstore.py", line 6, in &lt;module&gt; from .litesenderkeystore import LiteSenderKeyStore File "/usr/lib/python2.7/site-packages/yowsup/layers/axolotl/store/sqlite/litesenderkeystore.py", line 3, in &lt;module&gt; import sqlite3 File "/usr/lib/python2.7/sqlite3/__init__.py", line 24, in &lt;module&gt; from dbapi2 import * File "/usr/lib/python2.7/sqlite3/dbapi2.py", line 28, in &lt;module&gt; from _sqlite3 import * ImportError: No module named _sqlite3 </code></pre> <p>Anyone that had this same error or might help me with it. Thanks. </p>
0
2016-08-09T07:20:51Z
38,847,994
<p>I managed to fix it by copying the module manually to the below path:</p> <pre><code>cp build/lib.linux-x86_64-2.7/_sqlite3.so /usr/lib/python2.7/lib-dynload/ </code></pre>
0
2016-08-09T10:14:03Z
[ "python", "yowsup" ]
CGI GET PHP to Python
38,844,501
<p>I currently have a HTML/PHP form redirect variables and it's values to Python via GET:</p> <pre><code> &lt;/script&gt; &lt;form id="form" target="_blank" style="display:none;" action="result.py" method="get"&gt; &lt;/form&gt; </code></pre> <p>The output of which results looking like this: <a href="http://www.server.com/result.py?option=1&amp;option2=2" rel="nofollow">http://www.server.com/result.py?option=1&amp;option2=2</a></p> <p>I'm able to catch the settings coming through with PHP:</p> <pre><code>&lt;?php if(isset($_GET)){ foreach($_GET as $k =&gt; $v){ echo $k . ' = ' .$v. '&lt;br/&gt;'; } } </code></pre> <p>But would really like to have this info capture in Python and I'm not sure where to start.</p> <p>The only thing I could think of is having all the possible variables in Python and filter the ones coming in.</p> <p>What I'm really after is a Python catching the variables given in the URL and nothing more.</p> <p>A push in the right direction would really be appreciated. Thanks!</p>
0
2016-08-09T07:22:00Z
38,844,657
<p>You want to use Python via CGI? It's been supported for a very long time.</p> <p>This tutorial should set you on the right path: <a href="http://www.tutorialspoint.com/python/python_cgi_programming.htm" rel="nofollow">http://www.tutorialspoint.com/python/python_cgi_programming.htm</a></p> <p>It answers your question, plus a whole lot more.</p>
0
2016-08-09T07:31:22Z
[ "php", "python", "cgi" ]
Can I convert an Odoo browse object to JSON
38,844,651
<p>I'm trying to integrate <code>reactjs</code> with <code>Odoo</code>, and successfully created components. Now my problem is that I cant get the JSON via odoo. The odoo programmer has to write special api request to make this happen. This is taking more time and code repetitions are plenty. </p> <p>I tried may suggestions and none worked.</p> <p>Is there a better way to convert the <code>browse objects</code>, that <code>odoo</code> generate, to <code>JSON</code> ?</p> <p>Note: Entirely new to python and odoo, please forgive my mistakes, if any mentioned above.</p>
1
2016-08-09T07:31:08Z
38,847,214
<p>maybe this will help you:</p> <p>Step 1: Create js that runs reqiest to <code>/example_link</code></p> <p>Step 2: Create controller who listens that link <code>@http.route('/example_link', type="json")</code></p> <p>Step 3: return from that function json <code>return json.dumps(res)</code> where res is python dictionary and also dont forget to import json.</p> <p>Thats all, it's not very hard, hope I helped you, good luck.</p>
0
2016-08-09T09:40:31Z
[ "python", "json", "odoo-8" ]
How to update user password in Django Rest Framework?
38,845,051
<p>I want to ask that following code provides updating password but I want to update password after current password confirmation process. So what should I add for it? Thank you.</p> <pre><code>class UserPasswordSerializer(ModelSerializer): class Meta: model = User fields = [ 'password' ] extra_kwargs = {"password": {"write_only": True} } def update(self, instance, validated_data): for attr, value in validated_data.items(): if attr == 'password': instance.set_password(value) else: setattr(instance, attr, value) instance.save() return instance </code></pre>
1
2016-08-09T07:52:05Z
38,846,554
<p>I believe that using a modelserializer might be an overkill. This simple serializer &amp; view should work.</p> <pre><code>class ChangePasswordSerializer(serializers.Serializer): """ Serializer for password change endpoint. """ old_password = serializers.CharField(required=True) new_password = serializers.CharField(required=True) class ChangePasswordView(UpdateAPIView): """ An endpoint for changing password. """ serializer_class = ChangePasswordSerializer model = UserProfile permission_classes = (IsAuthenticated,) def get_object(self, queryset=None): obj = self.request.user return obj def update(self, request, *args, **kwargs): self.object = self.get_object() serializer = self.get_serializer(data=request.data) if serializer.is_valid(): # Check old password if not self.object.check_password(serializer.data.get("old_password")): return Response({"old_password": ["Wrong password."]}, status=status.HTTP_400_BAD_REQUEST) # set_password also hashes the password that the user will get self.object.set_password(serializer.data.get("new_password")) self.object.save() return Response("Success.", status=status.HTTP_200_OK) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) </code></pre>
1
2016-08-09T09:11:27Z
[ "python", "django", "django-rest-framework" ]
np_utils.to_categorical Reverse
38,845,097
<pre><code>from keras.utils import np_utils uniques, ids = np.unique(arr, return_inverse=True) coded_array = np_utils.to_categorical(ids, len(uniques)) encode_dict ={} for i,j in zip(arr,coded_array): encode_dict[i] = j if len(encode_dict)==len(np.unique(arr)): break return coded_array,encode_dict </code></pre> <p>Example</p> <p>The Mapping Dictionary</p> <pre><code>{{'HOME': array([ 0., 0., 1.]), 'DRAW': array([ 0., 1., 0.]), 'AWAY': array([ 1., 0., 0.])} </code></pre> <p>Input</p> <pre><code> ['DRAW' 'HOME' 'HOME' ..., 'HOME' 'HOME' 'AWAY'] </code></pre> <p>Coded Output</p> <pre><code>[[ 0. 1. 0.] [ 0. 0. 1.] [ 0. 0. 1.] ..., [ 0. 0. 1.] [ 0. 0. 1.] [ 1. 0. 0.]] </code></pre> <p>How to reverse this function and get a decode function? </p>
1
2016-08-09T07:55:30Z
38,845,674
<p>You can use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.argmax.html" rel="nofollow"><code>np.argmax</code></a> to retrieve back those <code>ids</code> and then simply indexing into <code>uniques</code> should give you the original array. Thus, we would have an implementation, like so -</p> <pre><code>uniques[y_code.argmax(1)] </code></pre> <p>Sample run -</p> <pre><code>In [44]: arr Out[44]: array([5, 7, 3, 2, 4, 3, 7]) In [45]: uniques, ids = np.unique(arr, return_inverse=True) In [46]: y_code = np_utils.to_categorical(ids, len(uniques)) In [47]: uniques[y_code.argmax(1)] Out[47]: array([5, 7, 3, 2, 4, 3, 7]) </code></pre>
0
2016-08-09T08:29:22Z
[ "python", "numpy", "keras" ]
Saving and searching data with Tkinter entry boxes
38,845,134
<p>This might be a strange question because I am new to Python.</p> <p>I am trying to create form in Python which data can be entered into boxes and saved, then opened again. I'm currently using Tkinter to create a Gui which has entry boxes and buttons:</p> <pre><code>import sys from tkinter import * def mstore(): pass return def msearch(): file_path = filedialog.askopenfilename() return mGui=Tk() mGui.geometry('450x450+200+200') mGui.title('Form Test') #Top mTitle = Label (mGui,text='Heading Text',bg='white').grid(row=1,column=1) mDetail = Label (mGui,text='Flavour you can see',bg='white').grid(row=2,column=1) #Entry Boxes mFName = Label (mGui,text='Barcode',bg='white').grid(row=3,column=1) mEntryname = Entry().grid(row=3,column=2) #Buttons mSave = Button (mGui,text='Save',bg='white', command = mstore).grid(row=4,column=1) mSearch = Button (mGui,text='Search',bg='white', command = msearch).grid(row=5,column=1) mGui.mainloop() </code></pre> <p>The search was going to be used to open up a file which has been saved before and fill in the boxes with that data, however before that I need help saving the data in a way it will be retrievable - All the information I find is about web-forms. I have also tried saving information with SQLite3 but I found that to not be quite what I was looking for. Any help/guidance will be appreciated. Thanks,</p>
0
2016-08-09T07:57:55Z
38,846,532
<p><strong>Hello Gregulimy!</strong></p> <p>I have simplified your code and made it do what you want it to do. I have left comments explaining what the code does. If you have any questions about what I have done feel free to ask!</p> <pre><code>from tkinter import * def mstore(text): file = open("file.txt", "w") # Create file.txt file.write(text) # Write contents of mEntryname to file file.close() # Closes text file def msearch(): file = filedialog.askopenfilename() # Stores file directory that user chose open_file = open(file, 'r') # Opens file user chose print(open_file.read()) # Displays contents in console open_file.close() # Closes text file # Window Creation and Settings window = Tk() window.geometry('450x500') window.title('Form Test') # Create Widgets mTitle = Label (window,text='Heading Text',bg='white') mDetail = Label (window,text='Flavour you can see',bg='white') mFName = Label (window,text='Barcode',bg='white') mEntryname = Entry(window) # Runs mstore function when pressed (passing the contents of the entry box) mSave = Button (window,text='Save',bg='white', command = lambda: mstore(mEntryname.get())) # Runs msearch function when pressed mSearch = Button (window,text='Search',bg='white', command = lambda: msearch()) # Render Widgets mTitle.pack() mDetail.pack() mFName.pack() mEntryname.pack() mSave.pack() mSearch.pack() window.mainloop() </code></pre>
0
2016-08-09T09:10:30Z
[ "python", "tkinter" ]
Error Reading CSV file using Python, Flask
38,845,176
<p>I'm very new to python and flask. I simply wanted to read a CSV file but it's giving me an error of "FileNotFoundError: [Errno 2] No such file or directory: 'Dog-Data.csv'" everytime I try to run run.py</p> <p>Here are my file order</p> <pre><code>DD\ static\ (bunch of image files) templates\ (bunch of template files) __init__.py views.py Dog-Data.csv </code></pre> <p>views.py</p> <pre><code>from flask import render_template from app import app import csv @app.route('/') @app.route('/Home') def home(): return render_template("Home.html",title='Home') @app.route('/MakeaMatch') def makeamatch(): return render_template("MakeaMatch.html",title='Make a Match!') @app.route('/Game') def game(): return render_template("Game.html",title='Game') @app.route('/ListofDogs') def listofdogs(): return render_template("ListofDogs.html",title='List of Dogs') @app.route('/About') def about(): return render_template("About.html", title='About') @app.route('/Contact') def contact(): return render_template("Contact.html", title='Contact') @app.route('/MatchResult') def matchresult(): class DogBreed: def __init__(self, br, per, si, lif, hou, cli): self.breed = br self.personality = per self.size = si self.lifestyle = lif self.housing = hou self.climate = cli self.match = 0 #List that will contain class DogBreed ListOfBreeds = [] data_file = open('Dog-Data.csv') csv_file = csv.reader(data_file) for row in csv_file: #print (row) #will print the csv file #print (row[2]) #will print element of that row dog_breed = DogBreed(row[0],row[1].lower().split(", "),row[2].lower(),row[3].lower(),row[4].lower(),row[5].lower()) ListOfBreeds.append(dog_breed) data_file.close() #MORE CODES HERE. OMITTED BECAUSE I DON'T THINK IT'S RELEVANT return render_template("MatchResult.html",title='Match Result',posts=ListOfBreeds) </code></pre> <p>The webpage loads and templates shows up fine if I comment out the lines involving CSV. However, it doesn't of course show the result I want it too.</p> <p>I've also tried putting the Dog-Data.csv into the static folder and used</p> <pre><code>data_file = open('static/Dog-Data.csv') </code></pre> <p>but this didn't work either.</p> <p>Thanks so much for help.</p>
0
2016-08-09T08:00:27Z
38,845,332
<p>Have you tried to give the full path instead of just a relative path?</p> <p>Python sometimes takes the working directory as a "home" path, which might or might not be the same as your <code>view.py</code> is situated in.</p>
0
2016-08-09T08:08:20Z
[ "python", "csv", "parsing", "flask" ]
Error Reading CSV file using Python, Flask
38,845,176
<p>I'm very new to python and flask. I simply wanted to read a CSV file but it's giving me an error of "FileNotFoundError: [Errno 2] No such file or directory: 'Dog-Data.csv'" everytime I try to run run.py</p> <p>Here are my file order</p> <pre><code>DD\ static\ (bunch of image files) templates\ (bunch of template files) __init__.py views.py Dog-Data.csv </code></pre> <p>views.py</p> <pre><code>from flask import render_template from app import app import csv @app.route('/') @app.route('/Home') def home(): return render_template("Home.html",title='Home') @app.route('/MakeaMatch') def makeamatch(): return render_template("MakeaMatch.html",title='Make a Match!') @app.route('/Game') def game(): return render_template("Game.html",title='Game') @app.route('/ListofDogs') def listofdogs(): return render_template("ListofDogs.html",title='List of Dogs') @app.route('/About') def about(): return render_template("About.html", title='About') @app.route('/Contact') def contact(): return render_template("Contact.html", title='Contact') @app.route('/MatchResult') def matchresult(): class DogBreed: def __init__(self, br, per, si, lif, hou, cli): self.breed = br self.personality = per self.size = si self.lifestyle = lif self.housing = hou self.climate = cli self.match = 0 #List that will contain class DogBreed ListOfBreeds = [] data_file = open('Dog-Data.csv') csv_file = csv.reader(data_file) for row in csv_file: #print (row) #will print the csv file #print (row[2]) #will print element of that row dog_breed = DogBreed(row[0],row[1].lower().split(", "),row[2].lower(),row[3].lower(),row[4].lower(),row[5].lower()) ListOfBreeds.append(dog_breed) data_file.close() #MORE CODES HERE. OMITTED BECAUSE I DON'T THINK IT'S RELEVANT return render_template("MatchResult.html",title='Match Result',posts=ListOfBreeds) </code></pre> <p>The webpage loads and templates shows up fine if I comment out the lines involving CSV. However, it doesn't of course show the result I want it too.</p> <p>I've also tried putting the Dog-Data.csv into the static folder and used</p> <pre><code>data_file = open('static/Dog-Data.csv') </code></pre> <p>but this didn't work either.</p> <p>Thanks so much for help.</p>
0
2016-08-09T08:00:27Z
38,845,483
<p>ok so really simple mistake that took hours for me to solve. I should be passing it from the root folder which means I should've put</p> <pre><code>data_file = open('app/Dog-Data.csv') </code></pre> <p>and now it works. T__T</p>
0
2016-08-09T08:17:33Z
[ "python", "csv", "parsing", "flask" ]
Get string inside brackets
38,845,217
<p>I want to fetch the string inside the square bracket, which is given as array</p> <pre><code>u16 arrayName_1[8][7] </code></pre> <p>I have python code which can find the 1-Dimensional array and get the character inside squre brackets.</p> <pre><code>var = 'u16 arrayName_1[8]' index = re.split('\[(.*?)\]', str(var)) </code></pre> <p>index[0] will give 'u16 arrayName_1'.</p> <p>index[1] will give '8'.</p> <p>Problem: I want to get string inside brackets of 2D array. i tried below code but it is not desired result.</p> <pre><code>var = u16 arrayName_1[8][7] index= re.split('(\[.*\])$', str(var)) </code></pre> <p>index[0] will give 'u16 arrayName_1'.</p> <p>index[1] will give '[8][7]'. This is wrong result.</p> <p>I want output like:</p> <p>index[1] = '8'</p> <p>index[2] = '7'</p>
1
2016-08-09T08:02:35Z
38,845,325
<p>You may use your own pattern in <a href="https://docs.python.org/2/library/re.html#re.findall" rel="nofollow"><strong><code>re.findall</code></strong></a> to grab all the contents inside <code>[...]</code>:</p> <pre><code>import re var = 'u16 arrayName_1[8][7]' index = re.findall(r'\[(.*?)\]', var) print(index) # =&gt; ['8', '7'] </code></pre> <p>See <a href="https://ideone.com/JFfHYD" rel="nofollow">Python demo</a></p> <p>To only match digits inside, use <code>\[([0-9]+)]</code> regex. Also, you do not have to escape the <code>]</code> symbol outside the character class, and you should consider using raw string literals to define your regex patterns to avoid confusion with unescaped backslashes.</p>
3
2016-08-09T08:08:06Z
[ "python", "regex", "string" ]
How to sum up a column in numpy
38,845,265
<p>i got a dataframe which i convert in an array (that is a testscenario because i have problems with the results in pandas). Now i want to sum up one column.</p> <p>I have the following code:</p> <pre><code>import sys import pandas as pd import numpy as np import os from tkinter import * #data_rbu = np.genfromtxt('tmp_fakt_daten.csv', delimiter=',', dtype=None) data_rbu = pd.read_excel('tmp_fakt_daten.xlsx') array_rbu = data_rbu.as_matrix() print(array_rbu) summe1 = np.sum(array_rbu, axis=9, dtype=float) print(summe1) </code></pre> <p>This is the Array! I want to sum up KW_WERT and NETTO_EURO.</p> <pre><code>FAK_ART,FAK_DAT,LEIST_DAT,KD_CRM,MW_BW,EQ_NR,MATERIAL,KW_WERT,NETTO_EURO,TA ZPAF,2015-12-10,2015-12-31,T-HOME ICP,B,1001380363.0,B60ETS,0.15,18.9,SDH ZPAF,2015-12-10,2015-12-31,T-HOME ICP,B,1001380363.0,B60ETS,0.145,18.27,SDH ZPAF,2015-12-10,2015-12-31,T-HOME ICP,B,1001380363.0,B60ETS,0.145,18.27,SDH ZPAF,2015-12-10,2015-12-31,T-HOME ICP,B,1001380363.0,B60ETS,0.15,18.9,SDH ZPAF,2015-12-10,2015-12-31,T-HOME ICP,B,1001380363.0,B60ETS,0.15,18.9,SDH ZPAF,2015-12-10,2015-12-31,T-HOME ICP,B,1001380363.0,B60ETS,0.145,18.27,SDH ZPAF,2015-12-10,2015-12-31,T-HOME ICP,B,1001380363.0,B60ETS,0.15,18.9,SDH ZPAF,2015-12-10,2015-12-31,T-HOME ICP,E,1001380594.0,B60ETS,3.011,252.92,DSLAM/MSAN </code></pre> <p>After executing the code i get this error:</p> <pre><code>Traceback (most recent call last): File "C:\Users\A52113242\Desktop\PROJEKTE\[INPROGRESS] Faktura_sylvia\csv_einlesen bzgl. float\test2.py", line 12, in &lt;module&gt; summe1 = np.sum(array_rbu, axis=9, dtype=float) File "C:\Users\A52113242\AppData\Local\Downloaded Apps\Winpython\python-3.4.3\lib\site-packages\numpy\core\fromnumeric.py", line 1724, in sum out=out, keepdims=keepdims) File "C:\Users\A52113242\AppData\Local\Downloaded Apps\Winpython\python-3.4.3\lib\site-packages\numpy\core\_methods.py", line 32, in _sum return umr_sum(a, axis, dtype, out, keepdims) ValueError: 'axis' entry is out of bounds </code></pre> <p>I understand that the problem is the axis number.. but i dont know what im exactly doing wrong. I checked the documentation for numpy.sum...</p> <p>Hope you can help me!</p> <p>Damian</p>
1
2016-08-09T08:04:30Z
38,845,303
<p>do it directly in pandas:</p> <pre><code>data_rbu = pd.read_excel('tmp_fakt_daten.xlsx') summe1 = data_rbu['KW_WERT'] + data_rbu['NETTO_EURO'] # gets you a series summe1.sum() # gets you the total sum (if that's what you are after) </code></pre>
1
2016-08-09T08:06:51Z
[ "python", "pandas", "numpy" ]
How to sum up a column in numpy
38,845,265
<p>i got a dataframe which i convert in an array (that is a testscenario because i have problems with the results in pandas). Now i want to sum up one column.</p> <p>I have the following code:</p> <pre><code>import sys import pandas as pd import numpy as np import os from tkinter import * #data_rbu = np.genfromtxt('tmp_fakt_daten.csv', delimiter=',', dtype=None) data_rbu = pd.read_excel('tmp_fakt_daten.xlsx') array_rbu = data_rbu.as_matrix() print(array_rbu) summe1 = np.sum(array_rbu, axis=9, dtype=float) print(summe1) </code></pre> <p>This is the Array! I want to sum up KW_WERT and NETTO_EURO.</p> <pre><code>FAK_ART,FAK_DAT,LEIST_DAT,KD_CRM,MW_BW,EQ_NR,MATERIAL,KW_WERT,NETTO_EURO,TA ZPAF,2015-12-10,2015-12-31,T-HOME ICP,B,1001380363.0,B60ETS,0.15,18.9,SDH ZPAF,2015-12-10,2015-12-31,T-HOME ICP,B,1001380363.0,B60ETS,0.145,18.27,SDH ZPAF,2015-12-10,2015-12-31,T-HOME ICP,B,1001380363.0,B60ETS,0.145,18.27,SDH ZPAF,2015-12-10,2015-12-31,T-HOME ICP,B,1001380363.0,B60ETS,0.15,18.9,SDH ZPAF,2015-12-10,2015-12-31,T-HOME ICP,B,1001380363.0,B60ETS,0.15,18.9,SDH ZPAF,2015-12-10,2015-12-31,T-HOME ICP,B,1001380363.0,B60ETS,0.145,18.27,SDH ZPAF,2015-12-10,2015-12-31,T-HOME ICP,B,1001380363.0,B60ETS,0.15,18.9,SDH ZPAF,2015-12-10,2015-12-31,T-HOME ICP,E,1001380594.0,B60ETS,3.011,252.92,DSLAM/MSAN </code></pre> <p>After executing the code i get this error:</p> <pre><code>Traceback (most recent call last): File "C:\Users\A52113242\Desktop\PROJEKTE\[INPROGRESS] Faktura_sylvia\csv_einlesen bzgl. float\test2.py", line 12, in &lt;module&gt; summe1 = np.sum(array_rbu, axis=9, dtype=float) File "C:\Users\A52113242\AppData\Local\Downloaded Apps\Winpython\python-3.4.3\lib\site-packages\numpy\core\fromnumeric.py", line 1724, in sum out=out, keepdims=keepdims) File "C:\Users\A52113242\AppData\Local\Downloaded Apps\Winpython\python-3.4.3\lib\site-packages\numpy\core\_methods.py", line 32, in _sum return umr_sum(a, axis, dtype, out, keepdims) ValueError: 'axis' entry is out of bounds </code></pre> <p>I understand that the problem is the axis number.. but i dont know what im exactly doing wrong. I checked the documentation for numpy.sum...</p> <p>Hope you can help me!</p> <p>Damian</p>
1
2016-08-09T08:04:30Z
38,845,691
<p>As you said the values are in array:</p> <pre><code>In[10]:arr Out[10]: array([['ZPAF', '2015-12-10', '2015-12-31', 'T-HOME ICP', 'B', 1001380363.0, 'B60ETS', 0.15, 18.9, 'SDH'], ['ZPAF', '2015-12-10', '2015-12-31', 'T-HOME ICP', 'B', 1001380363.0, 'B60ETS', 0.145, 18.27, 'SDH'], ['ZPAF', '2015-12-10', '2015-12-31', 'T-HOME ICP', 'B', 1001380363.0, 'B60ETS', 0.145, 18.27, 'SDH'], ['ZPAF', '2015-12-10', '2015-12-31', 'T-HOME ICP', 'B', 1001380363.0, 'B60ETS', 0.15, 18.9, 'SDH'], ['ZPAF', '2015-12-10', '2015-12-31', 'T-HOME ICP', 'B', 1001380363.0, 'B60ETS', 0.15, 18.9, 'SDH'], ['ZPAF', '2015-12-10', '2015-12-31', 'T-HOME ICP', 'B', 1001380363.0, 'B60ETS', 0.145, 18.27, 'SDH'], ['ZPAF', '2015-12-10', '2015-12-31', 'T-HOME ICP', 'B', 1001380363.0, 'B60ETS', 0.15, 18.9, 'SDH'], ['ZPAF', '2015-12-10', '2015-12-31', 'T-HOME ICP', 'E', 1001380594.0, 'B60ETS', 3.011, 252.92, 'DSLAM/MSAN']], dtype=object) </code></pre> <p>you can do using <code>arr.sum</code>:</p> <pre><code>sum_arr=arr.sum(axis=0) </code></pre> <p><code>axis=0</code> it will sum column wise,then you can access the column based on its index.In your case for columns <code>KW_WERT</code> and <code>NETTO_EURO</code> you can get the sum as:</p> <pre><code>In[25]:sum_arr[7] Out[25]: 4.046 In[26]:sum_rr[8] In[23]: 383.33 </code></pre>
1
2016-08-09T08:30:13Z
[ "python", "pandas", "numpy" ]
Can you permanently change python code by input?
38,845,273
<p>I'm still learning python and am currently developing an API (artificial personal assistant e.g. Siri or Cortana). I was wondering if there was a way to update code by input. For example, if I had a list- would it be possible to PERMANENTLY add a new item even after the program has finished running.</p> <p>I read that you would have to use SQLite, is that true? And are there any other ways? </p>
-3
2016-08-09T08:04:49Z
38,845,353
<p>There are planty of methods how you can make your data persistent. It depends on the task, on the environment etc. Just a couple examples:</p> <ul> <li>Files (JSON, DBM, Pickle)</li> <li>NoSQL Databases (Redis, MongoDB, etc.)</li> <li>SQL Databases (both serverless and client server: sqlite, MySQL, PostgreSQL etc.)</li> </ul> <p>The most simple/basic approach is to use files. There are even modules that allow to do it transparently. You just work with your data as always.</p> <p>See <code>shelve</code> for example.</p> <p>From the documentation:</p> <blockquote> <p>A “shelf” is a persistent, dictionary-like object. The difference with “dbm” databases is that the values (not the keys!) in a shelf can be essentially arbitrary Python objects — anything that the pickle module can handle. This includes most class instances, recursive data types, and objects containing lots of shared sub-objects. The keys are ordinary strings.</p> </blockquote> <p>Example of usage:</p> <pre><code>import shelve s = shelve.open('test_shelf.db') try: s['key1'] = { 'int': 10, 'float':9.5, 'string':'Sample data' } finally: s.close() </code></pre> <p>You work with <code>s</code> just normally, as it were just a normal dictionary. And it is automatically saved on disk (in file <code>test_shelf.db</code> in this case).</p> <p>In this case your dictionary is persistent and will not lose its values after the program restart.</p> <p>More on it:</p> <ul> <li><a href="https://docs.python.org/2/library/shelve.html" rel="nofollow">https://docs.python.org/2/library/shelve.html</a></li> <li><a href="https://pymotw.com/2/shelve/" rel="nofollow">https://pymotw.com/2/shelve/</a></li> </ul> <p>Another option is to use pickle, which gives you persistence also, but not magically: you will need read and write data on your own.</p> <p>Comparison between <code>shelve</code> and <code>pickle</code>:</p> <ul> <li><a href="http://stackoverflow.com/questions/4103430/what-is-the-difference-between-pickle-and-shelve">What is the difference between pickle and shelve?</a></li> </ul>
0
2016-08-09T08:10:02Z
[ "python" ]
Can you permanently change python code by input?
38,845,273
<p>I'm still learning python and am currently developing an API (artificial personal assistant e.g. Siri or Cortana). I was wondering if there was a way to update code by input. For example, if I had a list- would it be possible to PERMANENTLY add a new item even after the program has finished running.</p> <p>I read that you would have to use SQLite, is that true? And are there any other ways? </p>
-3
2016-08-09T08:04:49Z
38,845,480
<p><strong>Hello J Nowak</strong></p> <p>I think what you want to do is save the input data to a file (Eg. txt file). You can view the link below which will show you how to read and write to a text file.</p> <p><a href="http://www.pythonforbeginners.com/files/reading-and-writing-files-in-python" rel="nofollow">How to read and write to text file in Python</a></p>
1
2016-08-09T08:17:22Z
[ "python" ]
How do I check the version of wxPython installed on my server?
38,845,293
<p>I have Python and WxPython installed. I want to check what is the version of WxPython installed.</p> <p>Didn't find the answer on <a href="https://wxpython.org/" rel="nofollow">https://wxpython.org/</a></p>
-1
2016-08-09T08:06:13Z
38,845,342
<p>Just like you would with every other Python library:</p> <p><code>pip show WxPython</code></p> <p>As I don't have this library installed, I can only suggest that some libraries also provide a <code>__version__</code> or <code>version()</code> attribute.</p> <p><strong>EDIT</strong>: <a href="http://stackoverflow.com/a/38845635/1453822">@nepix32's answer</a> provides the way it was implemented in <code>WxPython</code>.</p>
1
2016-08-09T08:09:21Z
[ "python", "wxpython" ]
How do I check the version of wxPython installed on my server?
38,845,293
<p>I have Python and WxPython installed. I want to check what is the version of WxPython installed.</p> <p>Didn't find the answer on <a href="https://wxpython.org/" rel="nofollow">https://wxpython.org/</a></p>
-1
2016-08-09T08:06:13Z
38,845,635
<p>Do as follows:</p> <pre><code>&gt;&gt;&gt; import wx &gt;&gt;&gt; wx.version() '3.0.2.0 msw (classic)' &gt;&gt;&gt; wx.__version__ '3.0.2.0' </code></pre> <p>If you want a one-liner on the command-line without using pip:</p> <pre><code>python -c "import wx;print wx.__version__" </code></pre>
0
2016-08-09T08:27:34Z
[ "python", "wxpython" ]
(Python Newbie) Following e-book "A Byte of Python" - Issue with first program
38,845,378
<p>Hoping some one can help me out with an issue I have with my first program from the e-book "A byte of Python". </p> <p>The e-book is based on Python 2.7. </p> <p>Program: zip a source directory and format it with a particular "Name" and place it in the destination directory. </p> <p>The E-Books code to do this task is: </p> <pre><code>import os import time # source directory of files to backup source = ["/root/Documents/test"] # target location for files to be backed up to target_dir = "/root/Documents/Backup" target = target_dir + os.sep time.strftime("%Y%m%d%H%M") + ".zip" # if target path does not exist, create it if not os.path.exists(target_dir): os.mkdir(target_dir) # Command to zip files zip_command = "zip -r {0}".format(target).join(source) #run the backup print "Zip command is:" print (zip_command) print "Running" # Check to see if backup was successful if os.system(zip_command) == 0: print "Successfull backup to", target else: print "Backup Failed" </code></pre> <p>The error I am receiving is: </p> <pre><code>Zip command is: /root/Documents/test Running Backup Failed sh: 1: /root/Documents/test: Permission denied Process finished with exit code 0 </code></pre> <p>I have checked the permissions on the folders, attempted to run the code as super user etc.. but I am having no luck, I am extremely new to Python and don't really want to continue on with this e-book until I have found a resolution to this problem as it re-uses and refines this code as I go on. </p> <p>I have a feeling the problem could be related to the zip_command? </p> <p>Any help would be greatly appreciated.</p>
0
2016-08-09T08:11:30Z
38,845,424
<p>You are constructing the command wrongly!</p> <pre><code>zip_command = "zip -r {0}".format(target) + " " + " ".join(source) # Result: zip -r /root/Documents/Backup &lt;space&gt; /root/Documents/test </code></pre>
1
2016-08-09T08:14:28Z
[ "python", "python-2.7" ]
install python-kerberos on windows
38,845,389
<p>I'm trying to install kerberos on windows, I download Zip package and in Kerberos folder I run this command : python setup.py install but I got this error :</p> <pre><code>error: command 'C:\\Users\\aicha\\AppData\\Local\\Programs\\Common\\Microsoft\ \Visual C++ for Python\\9.0\\VC\\Bin\\cl.exe' failed with exit status 2 </code></pre> <p>Thks for your help.</p>
0
2016-08-09T08:12:13Z
38,885,020
<p>A possible solution may be found here: <a href="http://stackoverflow.com/questions/21345000/python-kerberos-1-1-1-tar-gz-install-failure-on-windows">Python Kerberos-1.1.1.tar.gz Install Failure on Windows</a></p> <p>Basically, python kerberos is not supported on Windows, so you will have to use kerberos-sspi instead.</p>
1
2016-08-10T23:17:06Z
[ "python", "windows", "kerberos" ]
Can I create a loop to update SQL database?
38,845,435
<p>I have 6 tables in my <code>sql.db</code> file. And I was wondering if it would be possible to create a loop to go through each column within this 6 tables, and convert the values to <code>NULL</code> if the cell value is <code>-</code></p> <p><strong>Code I currently have</strong></p> <pre><code>for each_item in df.index: # Note: The name of the tables in the database is the variable 'each_item' pd.Dataframe.to_sql(df, con=engine, name=each_item, if_exists='append', index=False) # The below code does not work. And I have no idea why for each_columns in df.columns: connection.execute('UPDATE each_item SET each_columns = NULL WHERE each_columns = '-') </code></pre> <p>This seems to produce an error. </p> <p>How should I be coding it such that I am able to go through all the <code>tables</code> in the <code>sql.db</code>, and update each and every <code>column</code> in the <code>tables</code>, if the cell value = <code>-</code>?</p> <p>To be more specific, The error I got says that it cant locate the table. <code>no such table: each_item</code></p>
0
2016-08-09T08:15:02Z
38,846,889
<p>Ok, there are quite a few problems in your code. Let's address each at a time:</p> <ol> <li><code>pd.DataFrame.to_sql</code> stands for <code>your_dataframe.to_sql</code> in this case, <code>df.to_sql</code>. It is a method on a <code>DataFrame</code> object, and that object is the <code>DataFrame</code> you created. If this confuses you, please read about classes and methods in Python.</li> <li><code>to_sql</code> takes its first argument as table name, then connection, then schema name, and finally the if_exists and the index kwag</li> <li>It would be better if you did all conversions before you tried to write to SQL. That just makes things cleaner. Further, if you DataFrame is properly dtyped, NaN values will automatically get converted to the appropriate NULL value representation for the database engine in question.</li> </ol> <p>If you consider all the points above, this is how it should be done:</p> <pre><code>for each_item in df.index: # I would avoid a syntax like this. Better to have the DataFrames in a list, than iterate through a DataFrame df.loc[each_item].to_sql(name=each_item, con=engine, if_exists='append', index=False) # Here again, I would avoid using the name engine for a connection to a database engine </code></pre> <p>However, the success of the above code depends on your DataFrame being properly data typed, which I conclude it is not because you asked this question. If you edit your question with a sample of your DataFrame, I would be able to help you get your dtypes correct.</p> <hr> <p>Ps. If your DataFrame is created as a result of your previous question about DataFrame merging, then let me know and I will provide you with a comprehensive solution to both questions here. But do edit this question with data from that question so that people reading this question will not be stumped.</p>
1
2016-08-09T09:26:43Z
[ "python", "sql", "pandas", "sqlalchemy" ]
How to convert JSON into dataframe
38,845,474
<p>Any ideas on how to transform this JSON file into a usable dataframe format:</p> <pre><code>pd.read_json("http://api.census.gov/data/2014/acsse/variables.json") </code></pre> <p>Here's how the table should look: <a href="http://api.census.gov/data/2014/acsse/variables.html" rel="nofollow">http://api.census.gov/data/2014/acsse/variables.html</a></p>
1
2016-08-09T08:17:00Z
38,845,756
<p>Say you start with</p> <pre><code>df = pd.read_json("http://api.census.gov/data/2014/acsse/variables.json") </code></pre> <p>The problem is that the column is of dicts:</p> <pre><code>In [28]: df.variables.head() Out[28]: AIANHH {u'concept': u'Selectable Geographies', u'pred... ANRC {u'concept': u'Selectable Geographies', u'pred... BST {u'concept': u'Selectable Geographies', u'pred... CBSA {u'concept': u'Selectable Geographies', u'pred... CD {u'concept': u'Selectable Geographies', u'pred... Name: variables, dtype: object </code></pre> <p>But you can solve this by applying a <code>Series</code>:</p> <pre><code>In [27]: df.variables.apply(pd.Series) Out[27]: concept \ AIANHH Selectable Geographies ANRC Selectable Geographies BST Selectable Geographies CBSA Selectable Geographies CD Selectable Geographies CNECTA Selectable Geographies ... </code></pre> <p>This is the DataFrame you want, probably, as can be shown by:</p> <pre><code>In [32]: df.variables.apply(pd.Series).columns Out[32]: Index([u'concept', u'label', u'predicateOnly', u'predicateType'], dtype='object') </code></pre>
3
2016-08-09T08:33:13Z
[ "python", "json", "pandas", "census" ]
AttributeError: 'module' object has no attribute 'doc
38,845,494
<p>i am a beginner and i trying to model system dynamic model using python programming.the problem is when i trying to print the components of the sd model, the error message comes out like this: </p> <pre><code>"AttributeError: 'module' object has no attribute 'doc'" </code></pre> <p>my code:</p> <pre><code>import pysd educationmodel = pysd.read_vensim('Education.mdl') print educationmodel.components.doc() </code></pre>
-1
2016-08-09T08:18:18Z
38,845,875
<p>As far as understand from the git repo, the <code>doc()</code> method is inside <code>Class PySD</code>. Also, <code>read_vensim</code> returns an instance of this class. </p> <p>So your problem should get solved if you directly use <code>educationmodel.doc()</code>.</p>
0
2016-08-09T08:38:54Z
[ "python", "python-2.7", "ipython" ]
AttributeError: 'module' object has no attribute 'doc
38,845,494
<p>i am a beginner and i trying to model system dynamic model using python programming.the problem is when i trying to print the components of the sd model, the error message comes out like this: </p> <pre><code>"AttributeError: 'module' object has no attribute 'doc'" </code></pre> <p>my code:</p> <pre><code>import pysd educationmodel = pysd.read_vensim('Education.mdl') print educationmodel.components.doc() </code></pre>
-1
2016-08-09T08:18:18Z
40,115,667
<p>That may be my fault - I had to move the <code>.doc()</code> function to the model object instead of the components object as a way to work towards including Vensim macros properly. If it's still an issue, may want to update to the latest release (0.7.4). If that doesn't help either, then we may have to fix something. =)</p>
0
2016-10-18T18:39:15Z
[ "python", "python-2.7", "ipython" ]
PyXB: Cannot instantiate abstract type
38,845,528
<p>I try to do my first steps with PyXB but have the problem, that I cannot create the element paket. I have gone through the samples but can't find any more information on how to handle this. If the abstract element is one level deeper there seems a solution, but here it is on top level.</p> <p>Can somebody help me with this?</p> <p>Creating classes</p> <pre><code>pyxbgen -u arelda_v4.xsd -m all WARNING:pyxb.binding.generate:Complex type {http://bar.admin.ch/arelda/v4}paket renamed to paket_ Python for http://bar.admin.ch/arelda/v4 requires 1 modules </code></pre> <p>Try to create paket element:</p> <pre><code>Python 2.7.5 (default, Oct 11 2015, 17:47:16) [GCC 4.8.3 20140911 (Red Hat 4.8.3-9)] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import all &gt;&gt;&gt; paket = all.paket() Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/usr/lib/python2.7/site-packages/pyxb/binding/basis.py", line 1600, in __call__ rv = self.typeDefinition().Factory(*args, **kw) File "/usr/lib/python2.7/site-packages/pyxb/binding/basis.py", line 305, in Factory rv = cls._DynamicCreate(*args, **kw) File "/usr/lib/python2.7/site-packages/pyxb/binding/basis.py", line 677, in _DynamicCreate return ctor(*args, **kw) File "/usr/lib/python2.7/site-packages/pyxb/binding/basis.py", line 2075, in __init__ raise pyxb.AbstractInstantiationError(type(self), location, dom_node) pyxb.exceptions_.AbstractInstantiationError: Cannot instantiate abstract type {http://bar.admin.ch/arelda/v4}paket directly </code></pre> <p>XSD</p> <pre><code>&lt;xs:element name="paket" type="paket"&gt; &lt;xs:key name="ordnungssystempositionIdKey"&gt; &lt;xs:annotation&gt; &lt;xs:documentation&gt;Das Element id in der Entität Ordnungssystemposition muss eindeutig sein.&lt;/xs:documentation&gt; &lt;/xs:annotation&gt; &lt;xs:selector xpath=".//arelda:ordnungssystemposition"/&gt; &lt;xs:field xpath="@id"/&gt; &lt;/xs:key&gt; &lt;xs:key name="dossierIdKey"&gt; &lt;xs:annotation&gt; &lt;xs:documentation&gt;Das Element id in der Entität Dossier muss eindeutig sein.&lt;/xs:documentation&gt; &lt;/xs:annotation&gt; &lt;xs:selector xpath=".//arelda:dossier"/&gt; &lt;xs:field xpath="@id"/&gt; &lt;/xs:key&gt; &lt;xs:key name="dokumentIdKey"&gt; &lt;xs:annotation&gt; &lt;xs:documentation&gt;Das Element id in der Entität Dokument muss eindeutig sein.&lt;/xs:documentation&gt; &lt;/xs:annotation&gt; &lt;xs:selector xpath=".//arelda:dokument"/&gt; &lt;xs:field xpath="@id"/&gt; &lt;/xs:key&gt; &lt;xs:key name="archivischeNotizIdKey"&gt; &lt;xs:annotation&gt; &lt;xs:documentation&gt;Das Element id in der Entität ArchivischeNotiz muss eindeutig sein.&lt;/xs:documentation&gt; &lt;/xs:annotation&gt; &lt;xs:selector xpath=".//arelda:archivischeNotiz"/&gt; &lt;xs:field xpath="@id"/&gt; &lt;/xs:key&gt; &lt;/xs:element&gt; &lt;xs:complexType name="paket" abstract="true"&gt; </code></pre> <p>XML</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;v4:paket schemaVersion="4.0" xsi:type="v4:paketSIP" xmlns:v4="http://bar.admin.ch/arelda/v4" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"&gt; &lt;v4:paketTyp&gt;SIP&lt;/v4:paketTyp&gt; &lt;/v4:paket&gt; </code></pre> <p>Thanks Manuel</p>
0
2016-08-09T08:20:53Z
38,850,396
<p>The type <strong>paket</strong> is abstract, but this type is used in an element declaration against which the <strong>v4:paket</strong> element is validated. This is not allowed for abstract types. Abstract types can only be derived, and their concrete derived type used for validation.</p> <p>If you have control over the XSD document, setting <strong>abstract</strong> to <strong>false</strong>, or omitting this attribute, should make the error go away.</p> <pre><code>&lt;xs:complexType name="paket" abstract="false"&gt; ... &lt;/xs:complexType&gt; </code></pre>
1
2016-08-09T12:12:41Z
[ "python", "xml", "xsd", "abstract", "pyxb" ]
Error communicating with the remote browser It may have died
38,845,545
<p>I know this question has been asked many times and i have checked those but could not find solution .Above error is not frequent only sometimes i get it , so i am not able figure out why it is occurring .After executing below lines of code</p> <pre><code> driver.get(first_url) #here i open forst url the perform some operation main_window =driver.current_window_handle driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL + "t") #above line opens a new tab # Put focus on current window which will, in fact, put focus on the current visible tab main_window_new =driver.current_window_handle driver.switch_to_window(main_window_new ) time.sleep(1) driver.get(second_url) #opening new tab in the existing browser time.sleep(2) json_str=driver.find_element_by_tag_name('body').text time.sleep(1) print json # Close current tab driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL + 'w') # Put focus on current window which will be the window opener driver.switch_to_window(main_window) </code></pre> <p>i get this error</p> <blockquote> <p>Message: Error communicating with the remote browser. It may have died. Build info: version: '2.53.0', revision: '35ae25b', time: '2016-03-15 17:00:58' System info: host: 'BLR-CSM-1', ip: '172.17.1.34', os.name: 'Windows 7', os.arch: 'x86', os.version: '6.1', java.version: '1.8.0_101' Driver info: driver.version: RemoteWebDriver Capabilities [{applicationCacheEnabled=true, rotatable=false, handlesAlerts=true, databaseEnabled=true, version=35.0, platform=WINDOWS, nativeEvents=false, acceptSslCerts=true, webStorageEnabled=true, locationContextEnabled=true, browserName=firefox, takesScreenshot=true, javascriptEnabled=true, cssSelectorsEnabled=true}] Session ID: d7ac8e9e-2c20-48c6-82fd-ce8eaec93b46 Stacktrace: ('Unexpected error:', )</p> </blockquote> <p>Selenium Server log for above execuion </p> <pre><code>13:21:08.048 INFO - Executing: [get current window handle]) 13:21:08.058 INFO - Done: [get current window handle] 13:21:08.060 INFO - Executing: [find element: By.tagName: body]) 13:21:08.068 INFO - Done: [find element: By.tagName: body] 13:21:08.071 INFO - Executing: [send keys: 603 [[FirefoxDriver: firefox on WINDO WS (d52fe7cd-ee42-41f7-b065-ec1e853e1011)] -&gt; tag name: body], [?, t]]) 13:21:08.097 INFO - Done: [send keys: 603 [[FirefoxDriver: firefox on WINDOWS (d 52fe7cd-ee42-41f7-b065-ec1e853e1011)] -&gt; tag name: body], [?, t]] 13:21:10.107 INFO - Executing: [get current window handle]) 13:21:10.118 INFO - Done: [get current window handle] 13:21:10.122 INFO - Executing: [switch to window: {1d2e0152-8716-466e-bb62-d0a96 073fb3b}]) 13:21:10.130 INFO - Done: [switch to window: {1d2e0152-8716-466e-bb62-d0a96073fb 3b}] 13:21:11.133 INFO - Executing: [get:https://myar.axyza.com/monitor/getStatsData? graphTypeId=0]) 13:21:12.173 INFO - Done: [get: https://myar.axyza.com/monitor/getStatsData? graphTypeId=0])] 13:21:14.176 INFO - Executing: [find element: By.tagName: body]) 13:21:14.185 INFO - Done: [find element: By.tagName: body] 13:21:14.188 INFO - Executing: [get text: 853 [[FirefoxDriver: firefox on WINDOW S (d52fe7cd-ee42-41f7-b065-ec1e853e1011)] -&gt; tag name: body]]) 13:21:14.215 INFO - Done: [get text: 853 [[FirefoxDriver: firefox on WINDOWS (d5 2fe7cd-ee42-41f7-b065-ec1e853e1011)] -&gt; tag name: body]] 13:21:15.221 INFO - Executing: [find element: By.tagName: body]) 13:21:15.233 INFO - Done: [find element: By.tagName: body] 13:21:15.237 INFO - Executing: [send keys: 853 [[FirefoxDriver: firefox on WINDO WS (d52fe7cd-ee42-41f7-b065-ec1e853e1011)] -&gt; tag name: body], [?, w]]) 13:21:15.367 INFO - Done: [send keys: 853 [[FirefoxDriver: firefox on WINDOWS (d 52fe7cd-ee42-41f7-b065-ec1e853e1011)] -&gt; tag name: body], [?, w]] 13:21:17.371 INFO - Executing: [switch to window: {1d2e0152-8716-466e-bb62-d0a96 073fb3b}]) 13:21:18.417 INFO - Executing: [close window]) </code></pre> <p>Any help is appreciated.</p>
0
2016-08-09T08:22:13Z
38,846,799
<p>Because the below line will close your browser if it has only one tab open.</p> <pre><code># remove that line and run your code. You will not see this error again. driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL + 'w') </code></pre>
1
2016-08-09T09:21:45Z
[ "python", "selenium", "selenium-webdriver" ]
Is there a decorator equivalent to PyXll `@xl_func(macro=True)` with xlwings?
38,845,707
<p>Is there a decorator equivalent to PyXll <code>@xl_func(macro=True)</code> with xlwings? </p> <p>This would allow to interact with the entire workbook in Excel? </p> <p>A dummy example: <code>=test()</code> in cell 'E5' returns an error: </p> <pre><code>@xw.func def test(): wb = xw.Book.caller() wb.sheets[0].range('A1').formula = wb.name return 'done' </code></pre> <blockquote> <p>Unexpected Python Error: TypeError: Objects for SAFEARRAYS must be sequences (of sequences), or a buffer object.</p> </blockquote> <p>For the sake of clarification: I would like to be able to write Excel functions, without arrays formulas or buttons or macros.</p>
0
2016-08-09T08:31:10Z
38,848,719
<p>Yes, <code>xw.sub</code>, from the <a href="http://docs.xlwings.org/en/stable/udfs.html#macros" rel="nofollow">docs</a>:</p> <pre><code>import xlwings as xw @xw.sub def my_macro(): """Writes the name of the Workbook into Range("A1") of Sheet 1""" wb = xw.Book.caller() wb.sheets[0].range('A1').value = wb.name </code></pre>
0
2016-08-09T10:50:10Z
[ "python", "xlwings" ]
Django: "request" does not contain the 'method' (POST/GET)
38,845,737
<p>I've created a [seemingly] straightforward form for customers, however, after the user submits the form, when i try to check the returning request m- I'm getting :</p> <p><strong>Exception Type: AttributeError Exception Value: 'QueryDict' object has no attribute 'method'</strong></p> <p>when i checked I saw that the request objects contains only the data submitted in the form, and doesn't include the "method" attribute</p> <p>this is the function that is used by the form:</p> <pre><code>def institutionapply(request): print(request) print("request: ",request) a=get_ip(request) print (a) country=get_country(request) # if this is a POST request we need to process the form data if request.method == 'POST': # create a form instance and populate it with data from the request: form = institutionapply(request.POST) print ("form in post clause:",form) #print ("duration output:",form.duration) # check whether it's valid: if form.is_valid(): print ("print form is valid") print (form.cleaned_data['title']) print (form.cleaned_data['country']) # process the data in form.cleaned_data as required # ... # redirect to a new URL: #return HttpResponseRedirect('/thanks/') #return redirect(name='home') # if a GET (or any other method) we'll create a blank form else: # create a form instance and populate it with data from the request: data = {'title': '', 'first': '', 'last':'', 'country':'','internationalprefix':'','phone':'','email':'','institutionname':'','institutionurl':'',} form = institutionform(data) return render(request,'app/intitutionapply.html', {'form': form}) </code></pre> <p>any ideas why the "method" object is nowhere to be found?</p> <p>EDIT : url configuration:</p> <pre><code>urlpatterns = [ url(r'^$', views.home, name='home'), url(r'^InstitutionApply$', views.institutionapply, name='institutionapply'), url(r'^contact$', views.contact, name='contact'), url(r'^about', views.about, name='about'), url(r'^admin/', admin.site.urls), </code></pre> <p>from the html template , the form declaration is:</p> <p></p> <p><strong>the functions from views.py</strong></p> <pre><code>def get_country(request): a=get_ip(request) country='United States' g = GeoIP2(path='D:/newTelumis/newTelumis/GeoLite2-Country.mmdb') return country def get_ip(request): try: x_forward= request.META.get("HTTP_X_FORWARD_FOR") if x_forward: ip=x_forward.split(",")[0] else: ip=request.META.get("REMOTE_ADDR") except: ip="" return ip </code></pre>
0
2016-08-09T08:32:35Z
38,847,604
<pre><code>def institutionapply(request): ... if request.method == 'POST': ... form = institutionapply(request.POST) </code></pre> <p>Replace <code>institutionapply</code> with <code>institutionform</code>.</p>
3
2016-08-09T09:57:51Z
[ "python", "django", "django-forms", "django-views" ]
Ascending read from csv and update csv using python
38,845,789
<p>I want to know whether it is possible to read the <code>.csv</code> file with specific <code>row</code>, after reading the row. I want to delete that specific row and update the <code>.csv</code> file with next row gets ascended. Assuming the <code>.csv</code> file has headers. If it is possible than how? Ex. below is my <code>sample.csv</code> </p> <pre><code>Time A B 12:25 5.6 4.5 12:30 1.2 -3.4 12:35 4.7 -4.0 </code></pre> <p>Below is the code I have tried:</p> <pre><code>import csv with open('sample.csv', 'rb') as inp, open('sample.csv', "a") as out: writer = csv.writer(out) for row in csv.reader(inp): writer.writerow(row) </code></pre> <p>But it gets, appended at the end of file. I have also tried to write it on the temporary file for intermediate stage. But, it still not serve my purpose cause I have to work on the same file. Here is the output <code>sample.csv</code>, which I want after one iteration of read:</p> <pre><code>Time A B 12:30 1.2 -3.4 12:35 4.7 -4.0 </code></pre>
0
2016-08-09T08:34:42Z
38,850,877
<p>You could use <code>StringIO</code> to keep the contents in memory and then write them to the desired file at the end.</p> <pre><code>from io import StringIO import csv filename = 'sample.csv' out_data = StringIO() # Read CSV data to memory with open(filename, 'r', newline='') as in_file: writer = csv.writer(out_data) for row in csv.reader(in_file): writer.writerow(row) # Write intermediate data to file with open(filename, 'w', newline='') as out_file: out_file.write(out_data.getvalue()) out_data.close() </code></pre>
0
2016-08-09T12:32:30Z
[ "python", "csv" ]
How to divide python datetime-span into equally spaced time-intervals?
38,845,802
<p>I am having two dates, just like:</p> <pre><code>date_a = datetime.datetime(2016, 8, 9, 8, 24, 30, 993352) date_b = datetime.datetime(2016, 8, 9, 7, 24, 30, 993352) </code></pre> <p>What I want is getting a list of timestamps with a five minute interval that lies between those two dates. With the above two dates the result would be:</p> <pre><code>five_min_timestamps = [ datetime.datetime(2016, 8, 9, 7, 25, 0, 0) datetime.datetime(2016, 8, 9, 7, 30, 0, 0) datetime.datetime(2016, 8, 9, 7, 35, 0, 0) datetime.datetime(2016, 8, 9, 7, 45, 0, 0) datetime.datetime(2016, 8, 9, 7, 55, 0, 0) datetime.datetime(2016, 8, 9, 8, 00, 0, 0) datetime.datetime(2016, 8, 9, 8, 05, 0, 0) datetime.datetime(2016, 8, 9, 8, 10, 0, 0) datetime.datetime(2016, 8, 9, 8, 15, 0, 0) datetime.datetime(2016, 8, 9, 8, 20, 0, 0) ] </code></pre> <p>I am still trying to figure out how to implement a function (very pythonic) that puts out timestamps just like in the description above.</p> <p>Requirement is that the range between those two dates (date_a and date_b) will be greater or less than in that example. So getting an interval between a whole day or even a week should be covered by that function.</p>
-1
2016-08-09T08:35:05Z
38,845,911
<p>Not extremely pythonic, but clean and concise:</p> <pre><code>from datetime import timedelta delta = timedelta(minutes=5) five_min_timestamps = [] date_x = date_a while date_x &lt; date_b: date_x += timedelta(minutes=5) five_min_timestamps.append(date_x) </code></pre> <p>Another option is to use list comprehension:</p> <pre><code> intervals = divmod((date_b - date_a).total_seconds(), 300) five_min_timestamps = [date_a + i * datetime.timedelta(minutes=5) for i in range(intervals)] </code></pre> <p>The <code>intervals</code> variable shows you, how many intervals in this timespan do you need (difference between the dates divided through 300).</p> <p>Or with one statement:</p> <pre><code>five_min_timestamps = [ date_a + i * datetime.timedelta(minutes=5) for i in range( divmod((date_b - date_a).total_seconds(), 300))] </code></pre>
2
2016-08-09T08:40:44Z
[ "python", "datetime" ]
How to divide python datetime-span into equally spaced time-intervals?
38,845,802
<p>I am having two dates, just like:</p> <pre><code>date_a = datetime.datetime(2016, 8, 9, 8, 24, 30, 993352) date_b = datetime.datetime(2016, 8, 9, 7, 24, 30, 993352) </code></pre> <p>What I want is getting a list of timestamps with a five minute interval that lies between those two dates. With the above two dates the result would be:</p> <pre><code>five_min_timestamps = [ datetime.datetime(2016, 8, 9, 7, 25, 0, 0) datetime.datetime(2016, 8, 9, 7, 30, 0, 0) datetime.datetime(2016, 8, 9, 7, 35, 0, 0) datetime.datetime(2016, 8, 9, 7, 45, 0, 0) datetime.datetime(2016, 8, 9, 7, 55, 0, 0) datetime.datetime(2016, 8, 9, 8, 00, 0, 0) datetime.datetime(2016, 8, 9, 8, 05, 0, 0) datetime.datetime(2016, 8, 9, 8, 10, 0, 0) datetime.datetime(2016, 8, 9, 8, 15, 0, 0) datetime.datetime(2016, 8, 9, 8, 20, 0, 0) ] </code></pre> <p>I am still trying to figure out how to implement a function (very pythonic) that puts out timestamps just like in the description above.</p> <p>Requirement is that the range between those two dates (date_a and date_b) will be greater or less than in that example. So getting an interval between a whole day or even a week should be covered by that function.</p>
-1
2016-08-09T08:35:05Z
38,845,954
<p>Defining a function that returns a list of intervals between low time <code>a</code> and top time <code>b</code>. </p> <pre><code>def print_time(a, b, inter): tmp = a + datetime.timedelta(0,interval) # sum an interval of inter secs list = [] while tmp &lt; b: list.add(tmp) tmp = tmp + datetime.timedelta(0,interval) # sum the interval again return list </code></pre> <p>The result list will have datetimes separated by inter seconds.</p> <p>Yield version suggested by <a href="http://stackoverflow.com/users/4850040/toby-speight">Toby Speight</a>:</p> <pre><code>def print_time(a, b, inter): tmp = a + datetime.timedelta(0,interval) # sum an interval of inter secs while tmp &lt; b: yield tmp tmp = tmp + datetime.timedelta(0,interval) # sum the interval again </code></pre>
0
2016-08-09T08:42:30Z
[ "python", "datetime" ]
How to divide python datetime-span into equally spaced time-intervals?
38,845,802
<p>I am having two dates, just like:</p> <pre><code>date_a = datetime.datetime(2016, 8, 9, 8, 24, 30, 993352) date_b = datetime.datetime(2016, 8, 9, 7, 24, 30, 993352) </code></pre> <p>What I want is getting a list of timestamps with a five minute interval that lies between those two dates. With the above two dates the result would be:</p> <pre><code>five_min_timestamps = [ datetime.datetime(2016, 8, 9, 7, 25, 0, 0) datetime.datetime(2016, 8, 9, 7, 30, 0, 0) datetime.datetime(2016, 8, 9, 7, 35, 0, 0) datetime.datetime(2016, 8, 9, 7, 45, 0, 0) datetime.datetime(2016, 8, 9, 7, 55, 0, 0) datetime.datetime(2016, 8, 9, 8, 00, 0, 0) datetime.datetime(2016, 8, 9, 8, 05, 0, 0) datetime.datetime(2016, 8, 9, 8, 10, 0, 0) datetime.datetime(2016, 8, 9, 8, 15, 0, 0) datetime.datetime(2016, 8, 9, 8, 20, 0, 0) ] </code></pre> <p>I am still trying to figure out how to implement a function (very pythonic) that puts out timestamps just like in the description above.</p> <p>Requirement is that the range between those two dates (date_a and date_b) will be greater or less than in that example. So getting an interval between a whole day or even a week should be covered by that function.</p>
-1
2016-08-09T08:35:05Z
38,846,755
<p>You can also look into using <a href="https://labix.org/python-dateutil#head-cf004ee9a75592797e076752b2a889c10f445418" rel="nofollow"><code>rrule</code> module from <code>dateutil</code></a>:</p> <blockquote> <p>The rrule module offers a small, complete, and very fast, implementation of the recurrence rules documented in the iCalendar RFC, including support for caching of results.</p> </blockquote> <p>Sample:</p> <pre><code>&gt;&gt;&gt; import datetime &gt;&gt;&gt; &gt;&gt;&gt; date_a = datetime.datetime(2016, 8, 9, 8, 24, 30, 993352) &gt;&gt;&gt; date_b = datetime.datetime(2016, 8, 9, 7, 24, 30, 993352) &gt;&gt;&gt; &gt;&gt;&gt; from dateutil import rrule &gt;&gt;&gt; &gt;&gt;&gt; list(rrule.rrule(rrule.MINUTELY, interval=5, dtstart=date_b + datetime.timedelta(minutes=1), until=date_a)) [ datetime.datetime(2016, 8, 9, 7, 25, 30), datetime.datetime(2016, 8, 9, 7, 30, 30), datetime.datetime(2016, 8, 9, 7, 35, 30), datetime.datetime(2016, 8, 9, 7, 40, 30), datetime.datetime(2016, 8, 9, 7, 45, 30), datetime.datetime(2016, 8, 9, 7, 50, 30), datetime.datetime(2016, 8, 9, 7, 55, 30), datetime.datetime(2016, 8, 9, 8, 0, 30), datetime.datetime(2016, 8, 9, 8, 5, 30), datetime.datetime(2016, 8, 9, 8, 10, 30), datetime.datetime(2016, 8, 9, 8, 15, 30), datetime.datetime(2016, 8, 9, 8, 20, 30) ] </code></pre> <p>There is also the often-overlooked <a href="http://delorean.readthedocs.io/en/latest" rel="nofollow"><code>Delorean</code> library</a> which <a href="http://delorean.readthedocs.io/en/latest/quickstart.html#making-a-few-stops" rel="nofollow">can make "a few stops"</a>.</p>
1
2016-08-09T09:19:59Z
[ "python", "datetime" ]
Can't update ballot date in UpdateView in django
38,845,806
<p>I designed a model:</p> <pre><code>class Sitting(models.Model): sit_date = models.DateField(blank=False) cut_off_date = models.DateField(null=True, blank=True) ballot_date = models.DateField(null=True, blank=True) sess_no = models.ForeignKey(Session, on_delete=models.CASCADE) genre = TreeForeignKey('Genre', null=True, blank=True, db_index=True) def get_cut_off_date(self): return self.sit_date - timedelta(days=16) def save(self, *args, **kwargs): self.cut_off_date = self.get_cut_off_date() self.ballot_date = self.get_ballot_date() super(Sitting, self).save(*args, **kwargs) </code></pre> <p>It correctly set ballot_date and cut_off_date. When I try to update the ballot date in UpdateView it was saved but no changes made in the database. I also tried it in django admin panel result was same. </p> <p><a href="http://i.stack.imgur.com/t7z0j.png" rel="nofollow"><img src="http://i.stack.imgur.com/t7z0j.png" alt="enter image description here"></a></p> <p>Suppose I want to change ballot date from 20 august to 22 august, I can made it in the form and also save it but when call the sitting no changes are found.</p> <p>I believe it was the reason of </p> <pre><code>def get_ballot_date(self): return self.sit_date - timedelta(days=12) </code></pre> <p>Can anybody suggest the ways how could I overwrite above function so that it accepted later changes.</p>
0
2016-08-09T08:35:13Z
38,845,904
<p>You explicitly override the ballot_date and cut_off_date fields every time you save. If you don't want that, maybe you need to put a check there?</p> <pre><code>def save(self, *args, **kwargs): if not self.cut_off_date: self.cut_off_date = self.get_cut_off_date() if not self.ballot_date: self.ballot_date = self.get_ballot_date() </code></pre>
1
2016-08-09T08:40:31Z
[ "python", "django" ]
What is the most Pythonic way to shorten this proportioning method?
38,846,132
<p>I'm looking for a way for shorten <code>find_equivalent()</code> proportioning method in most Pythonic way.</p> <p>if <code>y</code> number is not in range <code>0 - 2000</code> method should return <code>0</code>. Otherwise, method should find the range of the <code>y</code> and return the equal number to the range.</p> <pre><code>def find_equivalent(y): if y &lt;= 0 or y &gt; 2000: return 0 elif 0 &lt; y &lt;= 100: if y in range(1, 34): return 18 if y in range(34, 67): return 17 if y in range(67, 101): return 16 elif 100 &lt; y &lt;= 200: if y in range(101, 134): return 15 if y in range(134, 167): return 14 if y in range(167, 201): return 13 elif 200 &lt; y &lt;= 500: if y in range(201, 301): return 12 if y in range(301, 401): return 11 if y in range(401, 501): return 10 elif 500 &lt; y &lt;= 1000: if y in range(501, 667): return 9 if y in range(667, 834): return 8 if y in range(834, 1001): return 7 elif 1000 &lt; y &lt;= 2000: if y in range(1001, 1334): return 6 if y in range(1334, 1667): return 5 if y in range(1667, 2001): return 4 . . . </code></pre>
-3
2016-08-09T08:50:59Z
38,846,320
<p>You should calculate the return value.</p> <p>But still if you want to know how it should be done, then here is the way that I think is most appropriate, will update if I find something better.</p> <pre><code>range_value = [ {'min':100,'max':200,'val_return':1} , {'min':200,'max':300,'val_return':2} ,..... ] for _range in range_value: if y in range(_range['min'],_range['max']): return _range['val_return'] </code></pre> <p>You can use nested dictionary also, to minimize the iteration.</p>
-1
2016-08-09T09:00:18Z
[ "python" ]
What is the most Pythonic way to shorten this proportioning method?
38,846,132
<p>I'm looking for a way for shorten <code>find_equivalent()</code> proportioning method in most Pythonic way.</p> <p>if <code>y</code> number is not in range <code>0 - 2000</code> method should return <code>0</code>. Otherwise, method should find the range of the <code>y</code> and return the equal number to the range.</p> <pre><code>def find_equivalent(y): if y &lt;= 0 or y &gt; 2000: return 0 elif 0 &lt; y &lt;= 100: if y in range(1, 34): return 18 if y in range(34, 67): return 17 if y in range(67, 101): return 16 elif 100 &lt; y &lt;= 200: if y in range(101, 134): return 15 if y in range(134, 167): return 14 if y in range(167, 201): return 13 elif 200 &lt; y &lt;= 500: if y in range(201, 301): return 12 if y in range(301, 401): return 11 if y in range(401, 501): return 10 elif 500 &lt; y &lt;= 1000: if y in range(501, 667): return 9 if y in range(667, 834): return 8 if y in range(834, 1001): return 7 elif 1000 &lt; y &lt;= 2000: if y in range(1001, 1334): return 6 if y in range(1334, 1667): return 5 if y in range(1667, 2001): return 4 . . . </code></pre>
-3
2016-08-09T08:50:59Z
38,846,356
<p>I would suggest to use two lists, one containing the values for the range and the other containing the return values, i.e.</p> <pre><code>rangelist = [0, 1, 34, 67, 100 (etc)] returnlist = [18, 17, 16 (etc)] </code></pre> <p>Then, you can find the entry of <code>rangelist</code> closest to your <code>y</code> and pick the matching item from <code>returnlist</code>.</p>
0
2016-08-09T09:02:14Z
[ "python" ]
What is the most Pythonic way to shorten this proportioning method?
38,846,132
<p>I'm looking for a way for shorten <code>find_equivalent()</code> proportioning method in most Pythonic way.</p> <p>if <code>y</code> number is not in range <code>0 - 2000</code> method should return <code>0</code>. Otherwise, method should find the range of the <code>y</code> and return the equal number to the range.</p> <pre><code>def find_equivalent(y): if y &lt;= 0 or y &gt; 2000: return 0 elif 0 &lt; y &lt;= 100: if y in range(1, 34): return 18 if y in range(34, 67): return 17 if y in range(67, 101): return 16 elif 100 &lt; y &lt;= 200: if y in range(101, 134): return 15 if y in range(134, 167): return 14 if y in range(167, 201): return 13 elif 200 &lt; y &lt;= 500: if y in range(201, 301): return 12 if y in range(301, 401): return 11 if y in range(401, 501): return 10 elif 500 &lt; y &lt;= 1000: if y in range(501, 667): return 9 if y in range(667, 834): return 8 if y in range(834, 1001): return 7 elif 1000 &lt; y &lt;= 2000: if y in range(1001, 1334): return 6 if y in range(1334, 1667): return 5 if y in range(1667, 2001): return 4 . . . </code></pre>
-3
2016-08-09T08:50:59Z
38,846,358
<p>You can just <em>calculate</em> your numbers:</p> <pre><code>if 0 &lt; y &lt;= 200: return 18 - ((y - 1) // 33) elif 200 &lt; y &lt;= 500: return 12 - ((y - 201) // 100) elif 500 &lt; y &lt;= 1000: return 9 - ((y - 501) // 667)) elif 1000 &lt; y &lt;= 2000: return 6 - ((y - 501) // 1333) return 0 </code></pre> <p>and even those boundary values can be calculated; they are based on the range divided by 3.</p> <p>You could put most of this into a list and use bisection to find the right boundaries:</p> <pre><code>from bisect import bisect_left boundaries = [0, 100, 200, 500, 1000, 2000] def find_equivalent(y): if not 0 &lt; y &lt;= 2000: return 0 index = bisect_left(boundaries, y) stepsize = (boundaries[index] - boundaries[index - 1]) // 3 return 21 - (index * 3) - ((y - boundaries[index - 1] - 1) // stepsize) </code></pre> <p>or pre-calculate the smaller range boundaries, but still use bisection:</p> <pre><code>boundaries = [0, 100, 200, 500, 1000, 2000] precise_boundaries = [ upper - ((upper - boundaries[i]) // 3 * step) for i, upper in enumerate(boundaries[1:]) for step in range(2, -1, -1)] def find_equivalent(y): if not 0 &lt; y &lt;= 2000: return 0 return 18 - bisect_left(precise_boundaries, y) </code></pre>
6
2016-08-09T09:02:18Z
[ "python" ]
Python Eventlet spawn not executing concurrently
38,846,147
<p>I have following two versions of code using eventlet. The expectation is that the 2 spawn_n calls will execute concurrently, but thats not the case. The execution happens serially.</p> <pre><code>import eventlet import threading import datetime from eventlet.green import urllib2 def hello(name): print eventlet.greenthread.getcurrent(), threading.current_thread() print datetime.datetime.now() print " %s hello !!" % name urllib2.urlopen("http://www.google.com/intl/en_ALL/images/logo.gif").read() eventlet.spawn(hello, 'abc') eventlet.spawn(hello, 'xyz') eventlet.sleep(0) </code></pre> <p>O/P: &lt;_MainThread(MainThread, started 140365670881088)><br> 2016-08-09 14:04:57.782866<br> abc hello !!<br> &lt;_MainThread(MainThread, started 140365670881088)><br> 2016-08-09 14:05:02.929903<br> xyz hello !! </p> <pre><code>import eventlet import threading import datetime from eventlet.green import urllib2 def hello(name): print eventlet.greenthread.getcurrent(), threading.current_thread() print datetime.datetime.now() print " %s hello !!" % name urllib2.urlopen("http://www.google.com/intl/en_ALL/images/logo.gif").read() pool = eventlet.GreenPool(size=4) pool.spawn_n(hello, 'pqr') pool.spawn_n(hello, 'lmn') pool.waitall() </code></pre> <p>O/P: &lt;_MainThread(MainThread, started 139897149990720)><br> 2016-08-09 14:05:25.613546<br> pqr hello !!<br> &lt;_MainThread(MainThread, started 139897149990720)><br> 2016-08-09 14:05:30.699473<br> lmn hello !! </p> <p>In both the versions of the code, the call happens sequentially. </p>
1
2016-08-09T08:51:28Z
38,870,068
<pre><code>def fun(tag): print('{0} begin'.format(tag)) eventlet.sleep(0.1) # pretty much the same as running HTTP request and throwing results away print('{0} end'.format(tag)) t1 = time.time() pool.spawn(fun, 'Turtle') pool.spawn(fun, 'Achilles') pool.waitall() tt = time.time() - t1 print('Total time: {0:.2f}'.format(tt)) </code></pre> <p>And you would see output similar to this:</p> <pre><code>Turtle begin Achilles begin Turtle end Achilles end Total time: 0.10 </code></pre> <p>Which shows that execution of functions was interleaved at IO waiting points (sleep), which is close to definition of cooperative concurrency. Also notice that total time is not sum of two sleeps, but maximum + infrastructure overhead (should be close to nothing in this synthetic test).</p> <p>Code in question could not show this because you only had prints (which don't create IO wait in Eventlet) before IO and none after. So what you actually had executing is this:</p> <pre><code>main: pool.waitall() begin, switch to Eventlet loop loop: oh, there are greenthreads scheduled to run now, switch to 1 1: print this 1: print that 1: urllib... start network IO, switch to loop loop: there is another green thread scheduled, switch to 2 2: print this 2: print that 2: urllib... start network IO, switch to Eventlet loop loop: wait for any event that should wake greenthread, suppose that would be thread 1 urllib that is finished first 1: HTTP request finished, thread 1 finished, but no code to prove it loop: wait for any event... 2: HTTP request finished, thread 2 finished main: pool.waitall() finished </code></pre>
0
2016-08-10T09:58:25Z
[ "python", "eventlet" ]
python stream handler for multiple servers
38,846,262
<p>There are servers running in multiple locations,I need to stream the application log data from these servers to a <strong>ZMQ</strong>(Zero Message Queue) using <strong>python stream handler</strong>.How do i use the stream handler to get this done? I have already referred the Python Handlers documentation <a href="https://docs.python.org/3/library/logging.handlers.html#logging.StreamHandler" rel="nofollow">https://docs.python.org/3/library/logging.handlers.html#logging.StreamHandler</a></p>
0
2016-08-09T08:57:41Z
38,847,231
<p>You can post your logs from different servers as <code>json</code> to the ZMQ iteratively. For the ZMQ make a PyZMQ application which will have a message handler, listening to your incoming json from these servers. Then as per requirement the incoming json data can be processed and stored in a file (or wherever you want to store). This file can be read for the incoming logs ( eg: tail -f fileName.txt or fileName.log)</p> <p>Here is link which will help you setup a PyZMQ application:</p> <p><a href="https://stefan.sofa-rockers.org/2012/02/01/designing-and-testing-pyzmq-applications-part-1/" rel="nofollow">Designing and Testing PyZMQ Applications – Part 1</a></p> <p>For logging specifically you can use these example:</p> <p><a href="http://www.mglerner.com/blog/?p=8" rel="nofollow">A simple Python logging example</a></p> <p><a href="http://stackoverflow.com/questions/1383254/logging-streamhandler-and-standard-streams?rq=1">Logging, StreamHandler and standard streams</a></p>
0
2016-08-09T09:41:12Z
[ "python", "logging" ]
Python3 - wifi library does not run with Cell.all("wlan0")
38,846,295
<p>I'm trying to use wifi library for python3 (<a href="https://wifi.readthedocs.io/en/latest/index.html" rel="nofollow">https://wifi.readthedocs.io/en/latest/index.html</a>) but when I use Cell.all("wlan0") I get this error:</p> <pre><code>Microsoft Windows [Versione 10.0.10586] (c) 2015 Microsoft Corporation. Tutti i diritti sono riservati. C:\WINDOWS\system32&gt;python Python 3.5.1 (v3.5.1:37a07cee5969, Dec 6 2015, 01:54:25) [MSC v.1900 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; from wifi import Cell, scheme &gt;&gt;&gt; list(Cell.all("wlan0")) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "c:\users\-----\appdata\local\programs\python\python35\lib\site-packages\wifi\scan.py", line 39, in all stderr=subprocess.STDOUT) File "c:\users\-----\appdata\local\programs\python\python35\lib\subprocess.py", line 629, in check_output **kwargs).stdout File "c:\users\-----o\appdata\local\programs\python\python35\lib\subprocess.py", line 696, in run with Popen(*popenargs, **kwargs) as process: File "c:\users\-----\appdata\local\programs\python\python35\lib\subprocess.py", line 950, in __init__ restore_signals, start_new_session) File "c:\users\-----\appdata\local\programs\python\python35\lib\subprocess.py", line 1220, in _execute_child startupinfo) FileNotFoundError: [WinError 2] Impossibile trovare il file specificato &gt;&gt;&gt; </code></pre> <p>p.s. Sorry for my bad English (I'm italian)</p>
0
2016-08-09T08:59:04Z
38,846,996
<p>You get this error because you are running Windows. The wifi library is only designed for Linux systems as described in the documentation.</p>
0
2016-08-09T09:31:17Z
[ "python", "python-3.x", "wifi" ]
How to club dictionaries?
38,846,335
<p>I've two dictionaries as below.</p> <pre><code>d1 = { "user1":{"key1":"val1","key2":"val2"}, "user2":{"key3":"val3","key4":"val4"} } d2 = { "admin":{ "user1":{"key5":"val5","key6":"val6"}, "user3":{"key7":"val7","key8":"val8"} } } </code></pre> <p>Final dictionary should look like this:</p> <pre><code>d3 = { "user1":{"key1":"val1","key2":"val2","key5":"val5","key6":"val6"}, "user2":{"key3":"val3","key4":"val4"}, "user3":{"key7":"val7","key8":"val8"} } </code></pre> <p>Merging concept doesn't apply here. Could you please help me here ?</p> <p>I've tried the solution of <a href="http://stackoverflow.com/questions/38987/how-can-i-merge-two-python-dictionaries-in-a-single-expression">How can I merge two Python dictionaries in a single expression?</a> . Below solution is different from what i needed. </p> <pre><code>{'admin': {'user3': {'key8': 'val8', 'key7': 'val7'}, 'user1': {'key6': 'val6', 'key5': 'val5'}}, 'user2': {'key3': 'val3', 'key4': 'val4'}, 'user1': {'key2': ' val2', 'key1': 'val1'}} </code></pre>
-3
2016-08-09T09:01:09Z
38,847,100
<p>You can take a copy of the first dictionary, then iterate over the other - creating a default empty dictionary, then updating it with the contents of d2, eg:</p> <pre><code>d3 = d1.copy() for k, v in d2['admin'].iteritems(): d3.setdefault(k, {}).update(v) </code></pre> <p>Gives you output of:</p> <pre><code>{'user1': {'key1': 'val1', 'key2': 'val2', 'key5': 'val5', 'key6': 'val6'}, 'user2': {'key3': 'val3', 'key4': 'val4'}, 'user3': {'key7': 'val7', 'key8': 'val8'}} </code></pre>
1
2016-08-09T09:36:03Z
[ "python", "python-2.7", "dictionary" ]
How much time should the mouse left button be held?
38,846,373
<p>If you want to detect a Bot that is clicking on a button when he has to, could you look how long the left button stays down before being up again? I mean a script like this one (python):</p> <pre><code>import win32api, win32con win32api.SetCursorPos((x,y)) win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,x,y,0,0) win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,x,y,0,0) </code></pre> <p>Will click really fast. Probably faster than a human. And always at (really closely) the same speed. Could an anti-bot system detect that?</p> <p>So you can add a <code>time.sleep(float)</code> instruction between the two mouse_event's. But should it be randomised? We probably have a slight difference of time between two clicks, less precise than a computed click.</p> <p>So how much time should we make the sleep last (min and max of the randrange)?</p> <p>It's probably too much effort for being undetected but is that possible?</p> <p>So quick recap:</p> <ul> <li><p>Can we detect a bot on the click speed and click time never changing even a bit?</p></li> <li><p>How long does an average person press the button down before letting it go up? If I want to stay undetected should I randomise this time, and with which min and max?</p></li> </ul> <p>(I'm not talking about other existing security like checking if you press the same pixel over and over.)</p>
1
2016-08-09T09:02:52Z
38,913,260
<p>Yes, bots can and are detected this way.</p> <p>Yes, adding a random offset to the click speed, delay, mouse path, movement speed, and many more things is the standard solution to circumvent this kind of detection. There are many other ways to detect bots though.</p> <p>To get an average click speed, write a short program that logs the timestamps for mouseDown and mouseUp events and click in it. </p>
0
2016-08-12T08:23:35Z
[ "python", "security", "artificial-intelligence" ]
Where to place example data in python package?
38,846,395
<p>I'm setting up my first Python package, and I want to install it with some example data so that users can run the code straight off. In case it's relevant my package is on github and I'm using pip.</p> <p>At the moment my example data is being installed with the rest of the package into site_packages/, by setting <code>include_package_data=True</code> in setup.py, and referencing the files I want to include in MANIFEST.in. However, while this makes sense to me for files used by the code as part of its processing, it doesn't seem especially appropriate for example data. </p> <p>What is best/standard practice for deploying example data with a python package?</p>
0
2016-08-09T09:03:42Z
38,846,673
<p>You can put your example data in the repository in <code>examples</code> folder next to your project sources and exclude it from package with <code>prune examples</code> in your manifest file.</p> <p>There is actually no universal and standard advice for that. Do whatever suits your needs.</p>
1
2016-08-09T09:16:19Z
[ "python", "install" ]
nose2.main() verbose output
38,846,535
<p>I'm writing a separate nose2 tests.py for my program and because I want it to run on both Windows and Linux fairly seamlessly I've decided to forgo using the normal commandline nose2 and instead import it in the file and run it from there.</p> <pre><code>if __name__ == '__main__': import nose2 nose2.main() </code></pre> <p>This works fine, no problems. But I'd like the verbose output and I can't see how to get it to do this. I've tried:</p> <pre><code>nose2.main("-v") nose2.main(kwargs="-v") nose2.main(args="-v") </code></pre> <p>Anyone know how to get the imported version of nose2 to run in verbose mode?</p>
0
2016-08-09T09:10:41Z
38,848,397
<p>Since the <code>PluggableTestProgram</code> class <a href="http://nose2.readthedocs.io/en/latest/dev/main.html?highlight=verbosity" rel="nofollow">accepts the same parameters</a> of <code>unittest.TestProgram</code>, you can pass <code>verbosity</code> to the <code>main</code> function as such:</p> <pre><code>nose2.main(verbosity=2) # default is 1 </code></pre> <p>See: <code>Unittest.main</code> <a href="https://docs.python.org/2/library/unittest.html?highlight=verbosity#unittest.main" rel="nofollow">documentation about verbosity</a></p>
1
2016-08-09T10:35:55Z
[ "python", "nose2" ]
Python pandas producing error when trying to access 'DATE' column on large data set
38,846,590
<p>I have a file with 3'502'379 rows and 3 columns. The following script is supposed to be executed but raises and error in the date handling line:</p> <pre><code>import matplotlib.pyplot as plt import numpy as np import csv import pandas path = 'data_prices.csv' data = pandas.read_csv(path, sep=';') data['DATE'] = pandas.to_datetime(data['DATE'], format='%Y%m%d') </code></pre> <p>This is the error that occurs:</p> <pre><code>Traceback (most recent call last): File "C:\Program Files\Python35\lib\site-packages\pandas\indexes\base.py", line 1945, in get_loc return self._engine.get_loc(key) File "pandas\index.pyx", line 137, in pandas.index.IndexEngine.get_loc (pandas\index.c:4066) File "pandas\index.pyx", line 159, in pandas.index.IndexEngine.get_loc (pandas\index.c:3930) File "pandas\hashtable.pyx", line 675, in pandas.hashtable.PyObjectHashTable.get_item (pandas\hashtable.c:12408) File "pandas\hashtable.pyx", line 683, in pandas.hashtable.PyObjectHashTable.get_item (pandas\hashtable.c:12359) KeyError: 'DATE' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\data\script.py", line 15, in &lt;module&gt; data['DATE'] = pandas.to_datetime(data['DATE'], format='%Y%m%d') File "C:\Program Files\Python35\lib\site-packages\pandas\core\frame.py", line 1997, in __getitem__ return self._getitem_column(key) File "C:\Program Files\Python35\lib\site-packages\pandas\core\frame.py", line 2004, in _getitem_column return self._get_item_cache(key) File "C:\Program Files\Python35\lib\site-packages\pandas\core\generic.py", line 1350, in _get_item_cache values = self._data.get(item) File "C:\Program Files\Python35\lib\site-packages\pandas\core\internals.py", line 3290, in get loc = self.items.get_loc(item) File "C:\Program Files\Python35\lib\site-packages\pandas\indexes\base.py", line 1947, in get_loc return self._engine.get_loc(self._maybe_cast_indexer(key)) File "pandas\index.pyx", line 137, in pandas.index.IndexEngine.get_loc (pandas\index.c:4066) File "pandas\index.pyx", line 159, in pandas.index.IndexEngine.get_loc (pandas\index.c:3930) File "pandas\hashtable.pyx", line 675, in pandas.hashtable.PyObjectHashTable.get_item (pandas\hashtable.c:12408) File "pandas\hashtable.pyx", line 683, in pandas.hashtable.PyObjectHashTable.get_item (pandas\hashtable.c:12359) KeyError: 'DATE' </code></pre>
1
2016-08-09T09:12:51Z
38,846,829
<p>the <code>'\ufeffDATE'</code> in the first column name shows that your CSV file has a <a href="https://en.wikipedia.org/wiki/Byte_order_mark#Representations_of_byte_order_marks_by_encoding" rel="nofollow">UTF-16 Byte Order Mark (BOM) signature</a> so it must be read accordingly.</p> <p>so try this when reading your CSV:</p> <pre><code>df = pd.read_csv(path, sep=';', encoding='utf-8-sig') </code></pre> <p>or as <a href="http://stackoverflow.com/questions/38846590/python-pandas-producing-error-when-trying-to-access-date-column-on-large-data/38846829#comment65058304_38846590">@EdChum suggested</a>:</p> <pre><code>df = pd.read_csv(path, sep=';', encoding='utf-16') </code></pre> <p>both variants should work properly</p> <p>PS <a href="http://stackoverflow.com/a/17912811/5741205">this answer</a> shows how to deal with BOMs</p>
4
2016-08-09T09:23:29Z
[ "python", "date", "datetime", "pandas", "dataframe" ]
pandas update dataframe values if cell contains '-'
38,846,642
<p>I have a pandas Dataframe which has 46 columns, and 6 rows. </p> <pre><code>Index Column1 Column2 Column3 Column4 ... # Cant type all 46 columns. 2012 5626 fooo - barrr 2013 5655h booo - barr 2014 5626d zooo - - LTM 56 gooo greed - </code></pre> <p>Is there a way for me to go through this Dataframe and update all the <code>-</code> values to be <code>0</code> or <code>null</code> values?</p> <p>I have tried:</p> <pre><code>for zzz in df.columns: # since df.columns will return me the names of the columns if df_final[zzz].any() == '-': df_final[zzz] = 0 print(df_final) </code></pre> <p>However, this just prints everything out as it is. it does not convert <code>-</code> into <code>0 / null</code></p>
2
2016-08-09T09:15:05Z
38,846,678
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.replace.html" rel="nofollow"><code>replace</code></a>:</p> <pre><code>print (df.replace({'-': 0})) Index Column1 Column2 Column3 Column4 0 2012 5626 fooo 0 barrr 1 2013 5655h booo 0 barr 2 2014 5626d zooo 0 0 3 LTM 56 gooo greed 0 </code></pre>
3
2016-08-09T09:16:37Z
[ "python", "pandas" ]
pandas update dataframe values if cell contains '-'
38,846,642
<p>I have a pandas Dataframe which has 46 columns, and 6 rows. </p> <pre><code>Index Column1 Column2 Column3 Column4 ... # Cant type all 46 columns. 2012 5626 fooo - barrr 2013 5655h booo - barr 2014 5626d zooo - - LTM 56 gooo greed - </code></pre> <p>Is there a way for me to go through this Dataframe and update all the <code>-</code> values to be <code>0</code> or <code>null</code> values?</p> <p>I have tried:</p> <pre><code>for zzz in df.columns: # since df.columns will return me the names of the columns if df_final[zzz].any() == '-': df_final[zzz] = 0 print(df_final) </code></pre> <p>However, this just prints everything out as it is. it does not convert <code>-</code> into <code>0 / null</code></p>
2
2016-08-09T09:15:05Z
38,846,680
<p>use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.replace.html" rel="nofollow"><code>replace</code></a> to replace that specific value with another one:</p> <pre><code>In [71]: df.replace('-',0, inplace=True) df Out[71]: Index Column1 Column2 Column3 Column4 0 2012 5626 fooo 0 barrr 1 2013 5655h booo 0 barr 2 2014 5626d zooo 0 0 3 LTM 56 gooo greed 0 </code></pre> <p>Your code even if it would've worked is the wrong semantics:</p> <pre><code>for zzz in df.columns: if df_final[zzz].any() == '-': df_final[zzz] = 0 print(df_final) </code></pre> <p>this: <code>df_final[zzz] = 0</code> would've updated the entire column</p> <p>if your code was:</p> <pre><code>for zzz in df.columns: if df_final[zzz].any() == '-': df_final[zzz] = df_final[zzz].replace('-',0) print(df_final) </code></pre> <p>then this would've only replace the rows that met the condition, you could've also done:</p> <pre><code>df.apply(lambda x: x.replace('-',0)) </code></pre> <p>for a more compact method</p> <p><strong>EDIT</strong> if you want to replace with <code>NaN</code> then pass <code>np.NaN</code> instead of <code>0</code> above.</p>
3
2016-08-09T09:16:39Z
[ "python", "pandas" ]
Login with python module requests
38,846,846
<p>I need to log me in a website with requests, but all I have try don't work :</p> <pre><code>from bs4 import BeautifulSoup as bs import requests s = requests.session() url = 'https://www.ent-place.fr/CookieAuth.dll?GetLogon?curl=Z2F&amp;reason=0&amp;formdir=5' def authenticate(): headers = {'username': 'myuser', 'password': 'mypasss', '_Id': 'submit'} page = s.get(url) soup = bs(page.content) value = soup.form.find_all('input')[2]['value'] headers.update({'value_name':value}) auth = s.post(url, params=headers, cookies=page.cookies) authenticate() </code></pre> <p>or :</p> <pre><code>import requests payload = { 'inUserName': 'user', 'inUserPass': 'pass' } with requests.Session() as s: p = s.post('https://www.ent-place.fr/CookieAuth.dll?GetLogon?curl=Z2F&amp;reason=0&amp;formdir=5', data=payload) print(p.text) print(p.status_code) r = s.get('A protected web page url') print(r.text) </code></pre> <p>When I try this with the .status_code, it return 200 but I want 401 or 403 for do a script like 'if login'...</p> <p>Somebody know how to do ?</p>
0
2016-08-09T09:24:43Z
38,847,208
<p>You can just try this.</p> <p>Your login url is not correct, you can check the network requests in browser's developer tools.</p> <pre><code>import requests payload = { 'username': 'user', 'password': 'pass' } with requests.Session() as s: p = s.post('https://www.ent-place.fr/CookieAuth.dll?Logon', data=payload) print(p.text) print(p.status_code) </code></pre>
0
2016-08-09T09:40:22Z
[ "python", "python-requests" ]
Login with python module requests
38,846,846
<p>I need to log me in a website with requests, but all I have try don't work :</p> <pre><code>from bs4 import BeautifulSoup as bs import requests s = requests.session() url = 'https://www.ent-place.fr/CookieAuth.dll?GetLogon?curl=Z2F&amp;reason=0&amp;formdir=5' def authenticate(): headers = {'username': 'myuser', 'password': 'mypasss', '_Id': 'submit'} page = s.get(url) soup = bs(page.content) value = soup.form.find_all('input')[2]['value'] headers.update({'value_name':value}) auth = s.post(url, params=headers, cookies=page.cookies) authenticate() </code></pre> <p>or :</p> <pre><code>import requests payload = { 'inUserName': 'user', 'inUserPass': 'pass' } with requests.Session() as s: p = s.post('https://www.ent-place.fr/CookieAuth.dll?GetLogon?curl=Z2F&amp;reason=0&amp;formdir=5', data=payload) print(p.text) print(p.status_code) r = s.get('A protected web page url') print(r.text) </code></pre> <p>When I try this with the .status_code, it return 200 but I want 401 or 403 for do a script like 'if login'...</p> <p>Somebody know how to do ?</p>
0
2016-08-09T09:24:43Z
38,847,342
<p>These are the parameters your should be supplying.</p> <pre><code>curl:Z2F flags:0 forcedownlevel:0 formdir:5 username:yourusername password:yourpassword SubmitCreds.x:57 SubmitCreds.y:23 SubmitCreds:Ouvrir une session </code></pre>
0
2016-08-09T09:45:37Z
[ "python", "python-requests" ]
How to install Python3 to custom path using Chocolatey?
38,846,874
<p>I'm installing Python 3 with <a href="https://chocolatey.org/" rel="nofollow">Chocolatey</a>, which installs into <code>C:\ProgramData\chocolatey\lib\python3</code>:</p> <pre><code>&gt; choco install python3 </code></pre> <p>Is there any way I can get Python3 to install into <code>C:\Python35</code> instead?</p> <p>I´m aware of <a href="http://stackoverflow.com/questions/34581991/how-to-make-chocolatey-install-python2-into-custom-path">this question</a> which is related to Python 2 ... but here a different package is used thus the answer there does not help in this case.</p>
3
2016-08-09T09:26:06Z
38,847,127
<p>There is a possibility to override <code>--installargs</code> like this:</p> <pre><code>&gt; choco install python3 -y --override --installarguments "'/quiet InstallAllUsers=1 TargetDir=c:\Python35'" </code></pre> <p>You might see some (access denied) errors (guess Python 3.5.1 Package is broken) but overall it seems to work.</p> <p>I recommend to create your own Package as there is a newer Python version 3.5.2 which is not in the public package feed on <a href="https://chocolatey.org/packages/" rel="nofollow">chocolatey.org</a> yet</p>
2
2016-08-09T09:37:15Z
[ "python", "python-3.x", "chocolatey" ]
asyncio scheduling callback at specific time
38,846,962
<p>In the following code, the callback() is not called at the repsective time(now+0.2and now+0.1) and also stopper() ,what is wrong here</p> <pre><code> def callback(n,loop): print('Callback {} invoked at {}'.format(n,loop.time())) def stopper(loop): print("Stopper invoked at {}".format(loop.time())) loop.stop() event_loop = asyncio.get_event_loop() try: now =event_loop.time() print('clock time: {}'.format(time.time())) print('loop time: {}'.format(now)) print('Registering callbacks') event_loop.call_later(now + 0.2,callback,1,event_loop) event_loop.call_later(now + 0.1,callback,2,event_loop) event_loop.call_later(now + 0.3,stopper,event_loop) event_loop.call_soon(callback,3,event_loop) print('Entering event loop') event_loop.run_forever() finally: print('Closing event loop') event_loop.close(); </code></pre>
0
2016-08-09T09:29:33Z
38,848,943
<p><code>.call_later(delay, cb, *args)</code> requires <code>delay</code> parameters, time delta in seconds (<code>float</code>).</p> <p>But you pass <code>now + delay</code> to these calls.</p> <p>Either drop <code>now</code> or replace <code>.call_later()</code> with <code>.call_at()</code>.</p>
2
2016-08-09T11:00:43Z
[ "python", "python-asyncio" ]
How to create selective patches from an image based on the objects identified
38,847,116
<p>I have created a numpy matrix with all elements initialized to zeros as shown:</p> <pre><code>[[[0 0 0 0] [0 0 0 0] [0 0 0 0] ... </code></pre> <p>This is to resemble an image of the screenshot of a webpage which is of the size 1200 X 1000.</p> <p>I have identified a few rectangular region of interest for different HTML objects such as Radiobutton, Textbox and dropdown within the screenshot image and assigned them fixed values like 1,2 and 3 for the respective object-regions in the numpy matrix created.</p> <p>So the resultant matrix almost looks like :</p> <pre><code>[[[0 0 0 0] [0 0 0 0] [0 0 0 0] ..., [[1 1 1 1] [1 1 1 1] [1 1 1 1] ..., [0 0 0 0] [2 2 2 2] [0 0 0 0] ..., </code></pre> <p>I wish to now prepare data set for Convolutional neural network with the patches from the screenshot image. For the purpose of improving the quality of the data supplied to the CNN, I wish to filter the patches and provide only the patches to the CNN which has presence of the objects i.e. Textbox, Radiobutton etc which were detected earlier (Radiobutton and dropdown selections should be there fully and button atleast 50% of the region should be included in the patch). Any ideas how it can be realized in python?</p>
-4
2016-08-09T09:36:49Z
38,847,417
<p>a very naive approach</p> <pre><code>maxY, maxX = np.shape(theMatrix) for curY in range(0,maxY): for curX in range(0,maxX): print theMatrix[curY,curX], print " " </code></pre>
0
2016-08-09T09:49:02Z
[ "python", "numpy", "image-processing", "conv-neural-network" ]
How to create selective patches from an image based on the objects identified
38,847,116
<p>I have created a numpy matrix with all elements initialized to zeros as shown:</p> <pre><code>[[[0 0 0 0] [0 0 0 0] [0 0 0 0] ... </code></pre> <p>This is to resemble an image of the screenshot of a webpage which is of the size 1200 X 1000.</p> <p>I have identified a few rectangular region of interest for different HTML objects such as Radiobutton, Textbox and dropdown within the screenshot image and assigned them fixed values like 1,2 and 3 for the respective object-regions in the numpy matrix created.</p> <p>So the resultant matrix almost looks like :</p> <pre><code>[[[0 0 0 0] [0 0 0 0] [0 0 0 0] ..., [[1 1 1 1] [1 1 1 1] [1 1 1 1] ..., [0 0 0 0] [2 2 2 2] [0 0 0 0] ..., </code></pre> <p>I wish to now prepare data set for Convolutional neural network with the patches from the screenshot image. For the purpose of improving the quality of the data supplied to the CNN, I wish to filter the patches and provide only the patches to the CNN which has presence of the objects i.e. Textbox, Radiobutton etc which were detected earlier (Radiobutton and dropdown selections should be there fully and button atleast 50% of the region should be included in the patch). Any ideas how it can be realized in python?</p>
-4
2016-08-09T09:36:49Z
38,847,826
<p>You can just use the plot function to plot a 2D-array. Take for example:</p> <pre><code>import numpy as np import matplotlib.pyplot as pyplot x = np.random.rand(3, 2) </code></pre> <p>which will yield us </p> <pre><code>array([[ 0.53255518, 0.04687357], [ 0.4600085 , 0.73059902], [ 0.7153942 , 0.68812506]]) </code></pre> <p>If you use the <code>pyplot.plot(x, 'ro')</code>, it will plot you the figure given below.</p> <p><a href="http://i.stack.imgur.com/RMeNS.png" rel="nofollow"><img src="http://i.stack.imgur.com/RMeNS.png" alt="2d array plot"></a></p> <p>The row numbers are put in x-axis and the values are plotted in the y-axis. But from the nature of your problem , I suspect you need the columns numbers to be put in x-axis and the values in y-axis. To do so, you can simply transpose your matrix.</p> <pre><code>pyplot.plot(x.T,'ro') pyplot.show() </code></pre> <p>which now yields (for the same array) the figure given below.</p> <p><a href="http://i.stack.imgur.com/X0mIi.png" rel="nofollow"><img src="http://i.stack.imgur.com/X0mIi.png" alt="2d array transpose plot"></a></p>
0
2016-08-09T10:07:24Z
[ "python", "numpy", "image-processing", "conv-neural-network" ]
OpenCV error on spyder
38,847,201
<p>I want to use OpenCV with python on spyder. <br>But error occured when I run a simple code.<br></p> <pre><code>import cv2 img = cv2.imread('pi.png',0) cv2.imshow('image', img) cv2.waitKey(0) dcv2.destroyAllwindows() </code></pre> <p><strong>Error</strong></p> <blockquote> <p>This application failed to start because it could not find or load the Qt platform plugin "xcb".</p> <p>Reinstalling the application may fix this problem.</p> </blockquote> <p>The error is occured at this line.</p> <pre><code>cv2.imshow('image', img) </code></pre> <p><strong>Details: Ubuntu 14.04(LTS), OpenCV 2.4.13, Spyder 2.3.9(Python 2.7)</strong></p> <p>Please Tell me in detail what should I do.</p>
0
2016-08-09T09:40:13Z
38,865,986
<p>I didn't understand the answer.( <a href="http://stackoverflow.com/questions/30483753/python-app-xcb-plugin-fail">stackoverflow.com/questions/30483753/python-app-xcb-plugin-fail</a> )</p> <p>But, the problem is solved from changing condition when I reinstall OpenCV</p> <p>Installation is referred to <a href="https://help.ubuntu.com/community/OpenCV" rel="nofollow">this page</a>.</p> <p>The key of the solution in this method is simple!</p> <p>Change the condition from '<strong>WITH_QT=ON</strong>' to '<strong>WITH_QT=OFF</strong>' in the script. (<em>opencv.sh</em>)</p> <p>I don't have any solution without reinstalling because I'm inexperienced.</p> <p>If you know about solution that change the condition without reintalling or reason why the problem is occured, give me a feedback please.</p> <p>Thank you.</p>
0
2016-08-10T06:39:48Z
[ "python", "opencv", "ubuntu", "anaconda", "spyder" ]
Sending payload for GET request in python
38,847,317
<p>To filter the output, I can send a JSON to the API, like :</p> <pre><code>curl -X GET https://api.mysite.com/user \ -H "Authorization: XXXXX" \ -H "Content-Type: application/json" -d '{ "q": { "name": { "eq": "0aslam0" } } }' </code></pre> <p>The above works just fine. I am trying to send the same via python code using <code>requests</code> library.I tried the following code: </p> <pre><code>r = requests.get(url, headers=my_headers, params=payload) </code></pre> <p>where</p> <pre><code>url = "https://api.mysite.com/user" my_headers = { 'Authorization': 'XXXXX', 'Content-Type': 'application/json', 'Accept': 'application/json', } data = { "q": { "name": { "eq": "0aslam0" } } } payload = json.dumps(data) </code></pre> <p>but <code>r.text</code> contains the output of a normal GET without applying filter. I logged the request, and saw that I was getting a redirect <code>301</code>. I don't understand my mistake.</p> <p><strong>EDIT 1</strong></p> <p>I changed the code to : </p> <pre><code>r = requests.get(url, headers=my_headers, json=payload) </code></pre> <p>@Martijn was right. Using <code>params</code> was wrong. But the above also didn't succeed. I also added a header <code>'User-Agent': 'curl/7.40.0'</code>, to see if that could work. No luck there as well.</p> <p><strong>EDIT 2</strong></p> <p>The API documentation says, filtering can be done by another method. Changing the url into: </p> <pre><code>GET /user?q%5Bname%5D%5Beq%5D=0aslam0 HTTP/1.1 </code></pre> <p>It is HTML encoded. So I tried, to format my url into such a format and avoid sending the payload, like:</p> <pre><code>r = requests.get(url, headers=my_headers) </code></pre> <p>And it works! So at least now I have a solution to my problem. But the question on how to send the payload (the method discussed above) for a GET request, still remains.</p>
0
2016-08-09T09:44:45Z
38,847,431
<p>When you use <code>-d</code>, the data is sent as a request <em>body</em>. <code>params</code> sends a URL query string, so that's the wrong argument to use.</p> <p>Note that packaging along a request body with a <code>GET</code> method is technically a violation of the HTTP RFCs.</p> <p>You'd have to send your request the <code>data</code> argument set instead, or pass in your dictionary to the <code>json</code> keyword argument and <code>requests</code> will encode that and set the right <code>Content-Type</code> header for you:</p> <pre><code>my_headers = { 'Authorization': 'XXXXX', } data = { "q": { "name": { "eq": "0aslam0" } } } r = requests.get(url, headers=my_headers, json=data) </code></pre>
0
2016-08-09T09:49:35Z
[ "python", "python-2.7", "get", "python-requests" ]
Commit multiple SVN repositories using a Python script?
38,847,353
<p>I've been doing a lot of script-powered mass-updates to dozens of project folders at once, lately. Unfortunately, my pointy-haired boss insists that each folder be committed to TortoiseSVN separately after one of these bulk edits - he wants every folder to have a different revision number. Me being the automation fiend that I am, turned to scripting to try to solve this problem for me. This is what I'm trying:</p> <pre><code>import subprocess import glob for filepath in glob.glob("C:\eForms\*"): if ".svn" not in filepath: subprocess.call(['svn commit',filepath, '--message "&lt;commit message here&gt;"'], shell=True) </code></pre> <p>When I try to run it, I get <code>The filename, directory name, or volume label syntax is incorrect.</code> Any ideas?</p> <p>EDIT: Think I solved that issue. I tweaked the syntax, so now the call line reads <code>subprocess.call(["svn", "commit",('"',filepath,'"'), '-m "&lt;commit message&gt;"'], shell=True)</code></p> <p>Now I'm getting the error <code>svn: E020024: Error resolving case of '"&lt;filepath&gt;"'</code></p> <p>EDIT2: And pulling the quotes off the filepath solved that. All working now!</p>
0
2016-08-09T09:46:25Z
38,848,059
<p>Correct syntax of the call function turned out to be </p> <pre><code>subprocess.call(["svn", "commit", filepath, '-m "&lt;commit message here&gt;"'], shell = True) </code></pre>
0
2016-08-09T10:17:46Z
[ "python", "svn", "command-line", "tortoisesvn" ]
Django - exception handling best practice and sending customized error message
38,847,441
<p>I am starting to think about appropriate exception handling in my Django app, and my goal is to make it as user-friendly, as possible. By user-friendliness, I imply that the user must always get a detailed clarification as to what exactly went wrong. Following on <a href="http://stackoverflow.com/questions/9797253/django-ajax-error-response-best-practice">this post</a>, the best practice is to</p> <blockquote> <p>use a JSON response with status 200 for your normal responses and return an (appropriate!) 4xx/5xx response for errors. These can carry JSON payload, too, so your server side can add additional details about the error.</p> </blockquote> <p>I tried to google by the key words in this answer, by still have more questions than answers in my head.</p> <ol> <li>How do I decide upon which error code - 400 or 500 - to return? I mean, Django has many predefined error types, and how can I implement this mapping between Django exception types and 400-500 error code to make the exception handling blocks as DRY and reusable as possible?</li> <li>Can the approach with middleware suggested by @Reorx in <a href="http://stackoverflow.com/questions/9797253/django-ajax-error-response-best-practice">the post</a> be considered viable ? ( The answer got only one upvote, thus making me reluctant to delve into details and implement it in my project</li> <li>Most importantly, sometimes I may wish to raise an error related to business logic, rather than incorrect syntax or something standard like null value. For example, if there's no CEO in my legal entity, I might want to prohibit the user from adding a contract. What should be the error status in this case, and how do I throw an error with my detailed explanation of the error for the user?</li> </ol> <p>Let us consider it on a simple view</p> <pre><code>def test_view (request): try: # Some code .... if my_business_logic_is_violated(): # How do I raise the error error_msg = "You violated bussiness logic because..." # How do I pass error_msg my_response = {'my_field' : value} except ExpectedError as e: # what is the most appropriate way to pass both error status and custom message # How do I list all possible error types here (instead of ExpectedError to make the exception handling block as DRY and reusable as possible return JsonResponse({'status':'false','message':message}, status=500) </code></pre>
2
2016-08-09T09:50:11Z
38,847,585
<p>The status codes are very well defined in the HTTP standard. You can find a <a href="https://en.wikipedia.org/wiki/List_of_HTTP_status_codes" rel="nofollow">very readable list on Wikipedia</a>. Basically the errors in the 4XX range are errors made by the client, i.e. if they request a resource that doesn't exist, etc. The errors in the 5XX range should be returned if an error is encountered server side.</p> <p>With regards to point number 3, you should pick a 4XX error for the case where a precondition has not been met, for example <code>428 Precondition Required</code>, but return a 5XX error when a server raises a syntax error.</p> <p>One of the problems with your example is that no response is returned unless the server raises a specific exception, i.e. when the code executes normally and no exception is raised, neither the message nor the status code is explicitly sent to the client. This can be taken care of via a finally block, to make that part of the code as generic as possible.</p> <p>As per your example:</p> <pre><code>def test_view (request): try: # Some code .... status = 200 msg = 'Everything is ok.' if my_business_logic_is_violated(): # Here we're handling client side errors, and hence we return # status codes in the 4XX range status = 428 msg = 'You violated bussiness logic because a precondition was not met'. except SomeException as e: # Here, we assume that exceptions raised are because of server # errors and hence we return status codes in the 5XX range status = 500 msg = 'Server error, yo' finally: # Here we return the response to the client, regardless of whether # it was created in the try or the except block return JsonResponse({'message': msg}, status=status) </code></pre> <p>However, as stated in the comments it would make more sense to do both validations the same way, i.e. via exceptions, like so:</p> <pre><code>def test_view (request): try: # Some code .... status = 200 msg = 'Everything is ok.' if my_business_logic_is_violated(): raise MyPreconditionException() except MyPreconditionException as e: # Here we're handling client side errors, and hence we return # status codes in the 4XX range status = 428 msg = 'Precondition not met.' except MyServerException as e: # Here, we assume that exceptions raised are because of server # errors and hence we return status codes in the 5XX range status = 500 msg = 'Server error, yo.' finally: # Here we return the response to the client, regardless of whether # it was created in the try or the except block return JsonResponse({'message': msg}, status=status) </code></pre>
1
2016-08-09T09:57:16Z
[ "python", "json", "ajax", "django" ]
Django - exception handling best practice and sending customized error message
38,847,441
<p>I am starting to think about appropriate exception handling in my Django app, and my goal is to make it as user-friendly, as possible. By user-friendliness, I imply that the user must always get a detailed clarification as to what exactly went wrong. Following on <a href="http://stackoverflow.com/questions/9797253/django-ajax-error-response-best-practice">this post</a>, the best practice is to</p> <blockquote> <p>use a JSON response with status 200 for your normal responses and return an (appropriate!) 4xx/5xx response for errors. These can carry JSON payload, too, so your server side can add additional details about the error.</p> </blockquote> <p>I tried to google by the key words in this answer, by still have more questions than answers in my head.</p> <ol> <li>How do I decide upon which error code - 400 or 500 - to return? I mean, Django has many predefined error types, and how can I implement this mapping between Django exception types and 400-500 error code to make the exception handling blocks as DRY and reusable as possible?</li> <li>Can the approach with middleware suggested by @Reorx in <a href="http://stackoverflow.com/questions/9797253/django-ajax-error-response-best-practice">the post</a> be considered viable ? ( The answer got only one upvote, thus making me reluctant to delve into details and implement it in my project</li> <li>Most importantly, sometimes I may wish to raise an error related to business logic, rather than incorrect syntax or something standard like null value. For example, if there's no CEO in my legal entity, I might want to prohibit the user from adding a contract. What should be the error status in this case, and how do I throw an error with my detailed explanation of the error for the user?</li> </ol> <p>Let us consider it on a simple view</p> <pre><code>def test_view (request): try: # Some code .... if my_business_logic_is_violated(): # How do I raise the error error_msg = "You violated bussiness logic because..." # How do I pass error_msg my_response = {'my_field' : value} except ExpectedError as e: # what is the most appropriate way to pass both error status and custom message # How do I list all possible error types here (instead of ExpectedError to make the exception handling block as DRY and reusable as possible return JsonResponse({'status':'false','message':message}, status=500) </code></pre>
2
2016-08-09T09:50:11Z
38,849,047
<p>First of all you should think on what errors you want to expose:</p> <ul> <li><p>Usually 4xx errors (Errors that are attributed to the client-side) are disclosed so the user may correct the request.</p></li> <li><p>On the other side, 5xx errors (Errors that are attributed to the server-side) are usually only presented without information. In my opinion for those you should use tools like <a href="https://getsentry.com/welcome/" rel="nofollow">Sentry</a> do monitor and resolve this errors, that may have security issues embedded in them.</p></li> </ul> <p>Having this is mind in my opinion for a correct Ajax request you should return a a status code and then some json to help understand what happened like a message and an explanation (when applicable). </p> <p>If your objective is to use ajax to submit information I suggest setting a <a href="https://docs.djangoproject.com/en/1.10/topics/forms/" rel="nofollow">form</a> for what you want. This way you get past some of the validation process with ease. I will assume the case is this in the example.</p> <p><strong>First</strong> - Is the request correct?</p> <pre><code>def test_view(request): message = None explanation = None status_code = 500 # First, is the request correct? if request.is_ajax() and request.method == "POST": .... else: status_code = 400 message = "The request is not valid." # You should log this error because this usually means your front end has a bug. # do you whant to explain anything? explanation = "The server could not accept your request because it was not valid. Please try again and if the error keeps happening get in contact with us." return JsonResponse({'message':message,'explanation':explanation}, status=status_code) </code></pre> <p><strong>Second</strong> - Are there errors in the form?</p> <pre><code>form = TestForm(request.POST) if form.is_valid(): ... else: message = "The form has errors" explanation = form.errors.as_data() # Also incorrect request but this time the only flag for you should be that maybe JavaScript validation can be used. status_code = 400 </code></pre> <p>You may even get error field by field so you may presented in a better way in the form itself.</p> <p><strong>Third</strong> - Let's process the request</p> <pre><code> try: test_method(form.cleaned_data) except `PermissionError` as e: status_code= 403 message= "Your account doesn't have permissions to go so far!" except `Conflict` as e: status_code= 409 message= "Other user is working in the same information, he got there first" .... else: status_code= 201 message= "Object created with success!" </code></pre> <p>Depending on the exceptions you define, different codes may be required. Go to <a href="https://en.wikipedia.org/wiki/List_of_HTTP_status_codes" rel="nofollow">Wikipedia</a> and check the list. Don't forget that response also vary in code. If you add something to the database you should return a <code>201</code>. If you just got information then you were looking for a GET request.</p> <p><strong>Responding to the questions</strong></p> <ol> <li><p>Django exceptions will return 500 errors if not dealt with, because if you don't know that an exception is going to happen then it is an error in the server. With exception to 404 and login requirements I would do <code>try catch</code> blocks for everything. (For 404 you may raise it and if you do <code>@login_required</code>or a permission required django will respond with the appropriate code without you doing anything).</p></li> <li><p>I don't agree completely to the approach. As you said errors should be explicit so you should know allways what is suppose to happen and how to explain it, and make it dependable on the operation performed.</p></li> <li><p>I would say a 400 error is ok for that. It is a bad request you just need to explain why, the error code is for you and for your js code so just be consistent.</p></li> <li><p>(example provided) - In the <code>text_view</code> you should have the <code>test_method</code> as in the third example. </p></li> </ol> <p>Test method should have the following structure:</p> <pre><code>def test_method(validated_data): try: my_business_logic_is_violated(): catch BusinessLogicViolation: raise else: ... #your code </code></pre> <p>The in my example:</p> <pre><code> try: test_method(form.cleaned_data) except `BusinessLogicViolation` as e: status_code= 400 message= "You violated the business logic" explanation = e.explanation ... </code></pre> <p>I considered the business logic violation to be a Client Error because if something is needed before that request the client should be aware of that and ask the user to do it first. (From the <a href="https://tools.ietf.org/html/rfc7231#section-6.5.1" rel="nofollow">Error Definition</a>):</p> <blockquote> <p>The 400 (Bad Request) status code indicates that the server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request<br> message framing, or deceptive request routing).</p> </blockquote> <p>By the way, see the <a href="https://docs.python.org/3/tutorial/errors.html#tut-userexceptions" rel="nofollow">Python Docs on User-defined Exceptions</a> so you may give appropriate error messages. The idea behind this example is that you raise a <code>BusinessLogicViolation</code>exception with a different message in <code>my_business_logic_is_violated()</code>according to the place where it was generated.</p>
3
2016-08-09T11:06:19Z
[ "python", "json", "ajax", "django" ]
Python3 - use/wrap R function
38,847,573
<p>I'm using python 3.4.3 under ubuntu 14.04 and would like to use call R code to obtain some results. I know the existence of some packages such as pyper and rpy2 but they look compatible only with python2. By typing 'sudo pip3 install rpy2' I get the follow</p> <pre><code>Exception information: Traceback (most recent call last): File "/usr/lib/python3/dist-packages/pip/basecommand.py", line 122, in main status = self.run(options, args) File "/usr/lib/python3/dist-packages/pip/commands/install.py", line 283, in run requirement_set.install(install_options, global_options, root=options.root_path) File "/usr/lib/python3/dist-packages/pip/req.py", line 1436, in install requirement.install(install_options, global_options, *args, **kwargs) File "/usr/lib/python3/dist-packages/pip/req.py", line 707, in install cwd=self.source_dir, filter_stdout=self._filter_install, show_stdout=False) File "/usr/lib/python3/dist-packages/pip/util.py", line 715, in call_subprocess % (command_desc, proc.returncode, cwd)) pip.exceptions.InstallationError: Command /usr/bin/python3 -c "import setuptools, tokenize;__file__='/tmp/pip_build_user/rpy2/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-8hhbkgev-record/install-record.txt --single-version-externally-managed --compile failed with error code 1 in /tmp/pip_build_user/rpy2 </code></pre> <p>Is there any way to use R code inside python 3.4.3?</p>
0
2016-08-09T09:56:30Z
38,847,651
<p>rpy is in fact compatible with both Python 2 and Python 3. <a href="http://rpy2.readthedocs.io/en/version_2.8.x/overview.html#requirements" rel="nofollow">http://rpy2.readthedocs.io/en/version_2.8.x/overview.html#requirements</a></p> <blockquote> <p>Requirements</p> <p>Currently the development is done on UNIX-like operating systems with the following software versions. Those are the recommended versions to run rpy2 with.</p> <ul> <li>Python 3.5, with intended compatibility with 2.7 and > 3.3</li> </ul> </blockquote>
0
2016-08-09T10:00:01Z
[ "python", "python-3.x", "wrapper" ]
Django can't find static files
38,847,647
<p>I'm trying to deploy my Django project on <a href="https://www.digitalocean.com" rel="nofollow">Digital Ocean</a>. I've chosen Django App droplet to make it more simple. </p> <p>Then I've simply installed requirements, replace their <code>django_project</code> to my project. </p> <p>The problem is that static files (at least <code>css</code>) doesn't work at all. I can see the web but no <code>css</code>.</p> <p>Settings.py:</p> <pre><code>STATIC_ROOT = '/home/django/SolutionsForLanguages_2/SolutionsForLanguagesApp/static' STATIC_URL = '/static/' </code></pre> <p>I've followed this tutorial <a href="https://www.digitalocean.com/community/tutorials/how-to-use-the-django-one-click-install-image" rel="nofollow">One-Click Django - DigitalOcean</a></p> <p>Did <code>python manage.py collectstatic</code> I've already tried to restart <code>gunicorn</code>.</p> <p>nginx/sites-available/django:</p> <pre><code>upstream app_server { server 127.0.0.1:9000 fail_timeout=0; } server { listen 80 default_server; listen [::]:80 default_server ipv6only=on; root /usr/share/nginx/html; index index.html index.htm; client_max_body_size 4G; server_name _; keepalive_timeout 5; # Your Django project's media files - amend as required location /media { alias /home/django/SolutionsForLanguages_2/SolutionsForLanguagesApp/media; } # your Django project's static files - amend as required location /static { alias /home/django/SolutionsForLanguages_2/SolutionsForLanguagesApp/static; } # Proxy the static assests for the Django Admin panel location /static/admin { alias /usr/lib/python2.7/dist-packages/django/contrib/admin/static/admin/; } location / { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; proxy_pass http://app_server; } } </code></pre> <p>EDIT: </p> <p><code>CSS</code> works for <code>Django-Admin</code> pages</p> <p><strong>IMPORTANT EDIT</strong>;</p> <p>I've checked nginx log and it seems that it tries to find these files in wrong path. It is searching in their default project path. </p> <pre><code>2016/08/09 06:31:29 [error] 998#0: *140 open() "/home/django/django_project/django_project/static/css/bootstrap.min.css" failed (2: No such file or directory), client: 89.103.231.4, server: _, request: "GET /static/css/bootstrap.min.css HTTP/1.1", host: "37.139.20.125", referrer: "http://37.139.20.125/" 2016/08/09 06:31:29 [error] 998#0: *142 open() "/home/django/django_project/django_project/static/css/jumbotron.css" failed (2: No such file or directory), client: 89.103.231.4, server: _, request: "GET /static/css/jumbotron.css HTTP/1.1", host: "37.139.20.125", referrer: "http://37.139.20.125/" 2016/08/09 06:31:29 [error] 998#0: *140 open() "/home/django/django_project/django_project/static/css/dropdown.css" failed (2: No such file or directory), client: 89.103.231.4, server: _, request: "GET /static/css/dropdown.css HTTP/1.1", host: "37.139.20.125", referrer: "http://37.139.20.125/" 2016/08/09 06:31:29 [error] 998#0: *143 open() "/home/django/django_project/django_project/static/css/bootstrap-theme.min.css" failed (2: No such file or directory), client: 89.103.231.4, server: _, request: "GET /static/css/bootstrap-theme.min.css HTTP/1.1", host: "37.139.20.125", referrer: "http://37.139.20.125/" 2016/08/09 06:31:30 [error] 998#0: *140 open() "/home/django/django_project/django_project/static/img/hourglass.png" failed (2: No such file or directory), client: 89.103.231.4, server: _, request: "GET /static/img/hourglass.png HTTP/1.1", host: "37.139.20.125", referrer: "http://37.139.20.125/" 2016/08/09 06:31:30 [error] 998#0: *142 open() "/home/django/django_project/django_project/static/img/value.png" failed (2: No such file or directory), client: 89.103.231.4, server: _, request: "GET /static/img/value.png HTTP/1.1", host: "37.139.20.125", referrer: "http://37.139.20.125/" 2016/08/09 06:31:30 [error] 998#0: *143 open() "/home/django/django_project/django_project/static/img/people.png" failed (2: No such file or directory), client: 89.103.231.4, server: _, request: "GET /static/img/people.png HTTP/1.1", host: "37.139.20.125", referrer: "http://37.139.20.125/" 2016/08/09 06:31:30 [error] 998#0: *144 open() "/home/django/django_project/django_project/static/img/howitworks.png" failed (2: No such file or directory), client: 89.103.231.4, server: _, request: "GET /static/img/howitworks.png HTTP/1.1", host: "37.139.20.125", referrer: "http://37.139.20.125/" 2016/08/09 06:31:30 [error] 998#0: *140 open() "/home/django/django_project/django_project/static/img/languages.png" failed (2: No such file or directory), client: 89.103.231.4, server: _, request: "GET /static/img/languages.png HTTP/1.1", host: "37.139.20.125", referrer: "http://37.139.20.125/" 2016/08/09 06:31:30 [error] 998#0: *142 open() "/home/django/django_project/django_project/static/img/logos.png" failed (2: No such file or directory), client: 89.103.231.4, server: _, request: "GET /static/img/logos.png HTTP/1.1", host: "37.139.20.125", referrer: "http://37.139.20.125/" 2016/08/09 06:31:30 [error] 998#0: *143 open() "/home/django/django_project/django_project/static/img/pricing.png" failed (2: No such file or directory), client: 89.103.231.4, server: _, request: "GET /static/img/pricing.png HTTP/1.1", host: "37.139.20.125", referrer: "http://37.139.20.125/" 2016/08/09 06:31:30 [error] 998#0: *144 open() "/home/django/django_project/django_project/static/img/fcb.png" failed (2: No such file or directory), client: 89.103.231.4, server: _, request: "GET /static/img/fcb.png HTTP/1.1", host: "37.139.20.125", referrer: "http://37.139.20.125/" 2016/08/09 06:31:30 [error] 998#0: *140 open() "/home/django/django_project/django_project/static/img/twitter.png" failed (2: No such file or directory), client: 89.103.231.4, server: _, request: "GET /static/img/twitter.png HTTP/1.1", host: "37.139.20.125", referrer: "http://37.139.20.125/" 2016/08/09 06:31:30 [error] 998#0: *142 open() "/home/django/django_project/django_project/static/img/linkedin.png" failed (2: No such file or directory), client: 89.103.231.4, server: _, request: "GET /static/img/linkedin.png HTTP/1.1", host: "37.139.20.125", referrer: "http://37.139.20.125/" 2016/08/09 06:31:30 [error] 998#0: *145 open() "/home/django/django_project/django_project/static/img/helpful.png" failed (2: No such file or directory), client: 89.103.231.4, server: _, request: "GET /static/img/helpful.png HTTP/1.1", host: "37.139.20.125", referrer: "http://37.139.20.125/" </code></pre>
2
2016-08-09T09:59:46Z
38,848,485
<p>Try specifying STATIC_ROOT as following:</p> <pre><code>BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) # Note that number of times os.path.dirname is used depends on # to reach top of your project directory. here # Static Files STATIC_ROOT = join(os.path.dirname(BASE_DIR), 'staticfiles') STATICFILES_DIRS = [join(os.path.dirname(BASE_DIR), 'static'), ] STATIC_URL = '/static/' STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ) </code></pre>
0
2016-08-09T10:39:32Z
[ "python", "django", "nginx", "static", "gunicorn" ]
Django can't find static files
38,847,647
<p>I'm trying to deploy my Django project on <a href="https://www.digitalocean.com" rel="nofollow">Digital Ocean</a>. I've chosen Django App droplet to make it more simple. </p> <p>Then I've simply installed requirements, replace their <code>django_project</code> to my project. </p> <p>The problem is that static files (at least <code>css</code>) doesn't work at all. I can see the web but no <code>css</code>.</p> <p>Settings.py:</p> <pre><code>STATIC_ROOT = '/home/django/SolutionsForLanguages_2/SolutionsForLanguagesApp/static' STATIC_URL = '/static/' </code></pre> <p>I've followed this tutorial <a href="https://www.digitalocean.com/community/tutorials/how-to-use-the-django-one-click-install-image" rel="nofollow">One-Click Django - DigitalOcean</a></p> <p>Did <code>python manage.py collectstatic</code> I've already tried to restart <code>gunicorn</code>.</p> <p>nginx/sites-available/django:</p> <pre><code>upstream app_server { server 127.0.0.1:9000 fail_timeout=0; } server { listen 80 default_server; listen [::]:80 default_server ipv6only=on; root /usr/share/nginx/html; index index.html index.htm; client_max_body_size 4G; server_name _; keepalive_timeout 5; # Your Django project's media files - amend as required location /media { alias /home/django/SolutionsForLanguages_2/SolutionsForLanguagesApp/media; } # your Django project's static files - amend as required location /static { alias /home/django/SolutionsForLanguages_2/SolutionsForLanguagesApp/static; } # Proxy the static assests for the Django Admin panel location /static/admin { alias /usr/lib/python2.7/dist-packages/django/contrib/admin/static/admin/; } location / { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; proxy_pass http://app_server; } } </code></pre> <p>EDIT: </p> <p><code>CSS</code> works for <code>Django-Admin</code> pages</p> <p><strong>IMPORTANT EDIT</strong>;</p> <p>I've checked nginx log and it seems that it tries to find these files in wrong path. It is searching in their default project path. </p> <pre><code>2016/08/09 06:31:29 [error] 998#0: *140 open() "/home/django/django_project/django_project/static/css/bootstrap.min.css" failed (2: No such file or directory), client: 89.103.231.4, server: _, request: "GET /static/css/bootstrap.min.css HTTP/1.1", host: "37.139.20.125", referrer: "http://37.139.20.125/" 2016/08/09 06:31:29 [error] 998#0: *142 open() "/home/django/django_project/django_project/static/css/jumbotron.css" failed (2: No such file or directory), client: 89.103.231.4, server: _, request: "GET /static/css/jumbotron.css HTTP/1.1", host: "37.139.20.125", referrer: "http://37.139.20.125/" 2016/08/09 06:31:29 [error] 998#0: *140 open() "/home/django/django_project/django_project/static/css/dropdown.css" failed (2: No such file or directory), client: 89.103.231.4, server: _, request: "GET /static/css/dropdown.css HTTP/1.1", host: "37.139.20.125", referrer: "http://37.139.20.125/" 2016/08/09 06:31:29 [error] 998#0: *143 open() "/home/django/django_project/django_project/static/css/bootstrap-theme.min.css" failed (2: No such file or directory), client: 89.103.231.4, server: _, request: "GET /static/css/bootstrap-theme.min.css HTTP/1.1", host: "37.139.20.125", referrer: "http://37.139.20.125/" 2016/08/09 06:31:30 [error] 998#0: *140 open() "/home/django/django_project/django_project/static/img/hourglass.png" failed (2: No such file or directory), client: 89.103.231.4, server: _, request: "GET /static/img/hourglass.png HTTP/1.1", host: "37.139.20.125", referrer: "http://37.139.20.125/" 2016/08/09 06:31:30 [error] 998#0: *142 open() "/home/django/django_project/django_project/static/img/value.png" failed (2: No such file or directory), client: 89.103.231.4, server: _, request: "GET /static/img/value.png HTTP/1.1", host: "37.139.20.125", referrer: "http://37.139.20.125/" 2016/08/09 06:31:30 [error] 998#0: *143 open() "/home/django/django_project/django_project/static/img/people.png" failed (2: No such file or directory), client: 89.103.231.4, server: _, request: "GET /static/img/people.png HTTP/1.1", host: "37.139.20.125", referrer: "http://37.139.20.125/" 2016/08/09 06:31:30 [error] 998#0: *144 open() "/home/django/django_project/django_project/static/img/howitworks.png" failed (2: No such file or directory), client: 89.103.231.4, server: _, request: "GET /static/img/howitworks.png HTTP/1.1", host: "37.139.20.125", referrer: "http://37.139.20.125/" 2016/08/09 06:31:30 [error] 998#0: *140 open() "/home/django/django_project/django_project/static/img/languages.png" failed (2: No such file or directory), client: 89.103.231.4, server: _, request: "GET /static/img/languages.png HTTP/1.1", host: "37.139.20.125", referrer: "http://37.139.20.125/" 2016/08/09 06:31:30 [error] 998#0: *142 open() "/home/django/django_project/django_project/static/img/logos.png" failed (2: No such file or directory), client: 89.103.231.4, server: _, request: "GET /static/img/logos.png HTTP/1.1", host: "37.139.20.125", referrer: "http://37.139.20.125/" 2016/08/09 06:31:30 [error] 998#0: *143 open() "/home/django/django_project/django_project/static/img/pricing.png" failed (2: No such file or directory), client: 89.103.231.4, server: _, request: "GET /static/img/pricing.png HTTP/1.1", host: "37.139.20.125", referrer: "http://37.139.20.125/" 2016/08/09 06:31:30 [error] 998#0: *144 open() "/home/django/django_project/django_project/static/img/fcb.png" failed (2: No such file or directory), client: 89.103.231.4, server: _, request: "GET /static/img/fcb.png HTTP/1.1", host: "37.139.20.125", referrer: "http://37.139.20.125/" 2016/08/09 06:31:30 [error] 998#0: *140 open() "/home/django/django_project/django_project/static/img/twitter.png" failed (2: No such file or directory), client: 89.103.231.4, server: _, request: "GET /static/img/twitter.png HTTP/1.1", host: "37.139.20.125", referrer: "http://37.139.20.125/" 2016/08/09 06:31:30 [error] 998#0: *142 open() "/home/django/django_project/django_project/static/img/linkedin.png" failed (2: No such file or directory), client: 89.103.231.4, server: _, request: "GET /static/img/linkedin.png HTTP/1.1", host: "37.139.20.125", referrer: "http://37.139.20.125/" 2016/08/09 06:31:30 [error] 998#0: *145 open() "/home/django/django_project/django_project/static/img/helpful.png" failed (2: No such file or directory), client: 89.103.231.4, server: _, request: "GET /static/img/helpful.png HTTP/1.1", host: "37.139.20.125", referrer: "http://37.139.20.125/" </code></pre>
2
2016-08-09T09:59:46Z
38,849,152
<p>If your log file is showing nginx looking for files to server but from the wrong location then it because you nginx file has not be updated since your last change.</p> <p><a href="http://nginx.org/en/docs/beginners_guide.html#control" rel="nofollow">Reload your nginx configuration</a> and it should start serving files correctly.</p>
1
2016-08-09T11:11:21Z
[ "python", "django", "nginx", "static", "gunicorn" ]
Convert float to string without scientific notation and false precision
38,847,690
<p>I want to print some floating point numbers so that they're always written in decimal form (e.g. <code>12345000000000000000000.0</code> or <code>0.000000000000012345</code>, not in <a href="https://en.wikipedia.org/wiki/Scientific_notation" rel="nofollow">scientific notation</a>, yet I'd want to keep the 15.7 decimal digits of precision and no more.</p> <p>It is well-known that the <code>repr</code> of a <code>float</code> is written in scientific notation if the exponent is greater than 15, or less than -4:</p> <pre><code>&gt;&gt;&gt; n = 0.000000054321654321 &gt;&gt;&gt; n 5.4321654321e-08 # scientific notation </code></pre> <p>If <code>str</code> is used, the resulting string again is in scientific notation:</p> <pre><code>&gt;&gt;&gt; str(n) '5.4321654321e-08' </code></pre> <hr> <p>It has been suggested that I can use <code>format</code> with <code>f</code> flag and sufficient precision to get rid of the scientific notation:</p> <pre><code>&gt;&gt;&gt; format(0.00000005, '.20f') '0.00000005000000000000' </code></pre> <p>It works for that number, though it has some extra trailing zeroes. But then the same format fails for <code>.1</code>, which gives decimal digits beyond the actual machine precision of float:</p> <pre><code>&gt;&gt;&gt; format(0.1, '.20f') '0.10000000000000000555' </code></pre> <p>And if my number is <code>4.5678e-20</code>, using <code>.20f</code> would still lose relative precision:</p> <pre><code>&gt;&gt;&gt; format(4.5678e-20, '.20f') '0.00000000000000000005' </code></pre> <p>Thus <strong>these approaches do not match my requirements</strong>.</p> <hr> <p>This leads to the question: what is the easiest and also well-performing way to print arbitrary floating point number in decimal format, having the same digits as in <a href="http://stackoverflow.com/a/28493269/918959"><code>repr(n)</code> (or <code>str(n)</code> on Python 3)</a>, but always using the decimal format, not the scientific notation.</p> <p>That is, a function or operation that for example converts the float value <code>0.00000005</code> to string <code>'0.00000005'</code>; <code>0.1</code> to <code>'0.1'</code>; <code>420000000000000000.0</code> to <code>'420000000000000000.0'</code> or <code>420000000000000000</code> and formats the float value <code>-4.5678e-5</code> as <code>'-0.000045678'</code>.</p> <hr> <p>After the bounty period: It seems that there are at least 2 viable approaches, as Karin demonstrated that using string manipulation one can achieve significant speed boost compared to my initial algorithm on Python 2.</p> <p>Thus,</p> <ul> <li>If performance is important and Python 2 compatibility is required; or if the <code>decimal</code> module cannot be used for some reason, then <a href="http://stackoverflow.com/a/38983595/918959">Karin's approach using string manipulation</a> is the way to do it.</li> <li>On Python 3, <a href="http://stackoverflow.com/a/38847691/918959">my somewhat shorter code will also be faster</a>.</li> </ul> <p>Since I am primarily developing on Python 3, I will accept my own answer, and shall award Karin the bounty.</p>
27
2016-08-09T10:01:59Z
38,847,691
<p>Unfortunately it seems that not even the new-style formatting with <code>float.__format__</code> supports this. The default formatting of <code>float</code>s is the same as with <code>repr</code>; and with <code>f</code> flag there are 6 fractional digits by default:</p> <pre><code>&gt;&gt;&gt; format(0.0000000005, 'f') '0.000000' </code></pre> <hr> <p>However there is a hack to get the desired result - not the fastest one, but relatively simple:</p> <ul> <li>first the float is converted to a string using <code>str()</code> or <code>repr()</code></li> <li>then a new <a href="https://docs.python.org/3/library/decimal.html#decimal.Decimal" rel="nofollow"><code>Decimal</code></a> instance is created from that string.</li> <li><code>Decimal.__format__</code> supports <code>f</code> flag which gives the desired result, and, unlike <code>float</code>s it prints the actual precision instead of default precision.</li> </ul> <p>Thus we can make a simple utility function <code>float_to_str</code>:</p> <pre><code>import decimal # create a new context for this task ctx = decimal.Context() # 20 digits should be enough for everyone :D ctx.prec = 20 def float_to_str(f): """ Convert the given float to a string, without resorting to scientific notation """ d1 = ctx.create_decimal(repr(f)) return format(d1, 'f') </code></pre> <p>Care must be taken to not use the global decimal context, so a new context is constructed for this function. This is the fastest way; another way would be to use <code>decimal.local_context</code> but it would be slower, creating a new thread-local context and a context manager for each conversion.</p> <p>This function now returns the string with all possible digits from mantissa, rounded to the <a href="http://stackoverflow.com/a/28493269/918959">shortest equivalent representation</a>:</p> <pre><code>&gt;&gt;&gt; float_to_str(0.1) '0.1' &gt;&gt;&gt; float_to_str(0.00000005) '0.00000005' &gt;&gt;&gt; float_to_str(420000000000000000.0) '420000000000000000' &gt;&gt;&gt; float_to_str(0.000000000123123123123123123123) '0.00000000012312312312312313' </code></pre> <p>The last result is rounded at the last digit</p> <p>As @Karin noted, <code>float_to_str(420000000000000000.0)</code> does not strictly match the format expected; it returns <code>420000000000000000</code> without trailing <code>.0</code>.</p>
21
2016-08-09T10:01:59Z
[ "python", "python-3.x", "floating-point", "number-formatting", "python-2.x" ]
Convert float to string without scientific notation and false precision
38,847,690
<p>I want to print some floating point numbers so that they're always written in decimal form (e.g. <code>12345000000000000000000.0</code> or <code>0.000000000000012345</code>, not in <a href="https://en.wikipedia.org/wiki/Scientific_notation" rel="nofollow">scientific notation</a>, yet I'd want to keep the 15.7 decimal digits of precision and no more.</p> <p>It is well-known that the <code>repr</code> of a <code>float</code> is written in scientific notation if the exponent is greater than 15, or less than -4:</p> <pre><code>&gt;&gt;&gt; n = 0.000000054321654321 &gt;&gt;&gt; n 5.4321654321e-08 # scientific notation </code></pre> <p>If <code>str</code> is used, the resulting string again is in scientific notation:</p> <pre><code>&gt;&gt;&gt; str(n) '5.4321654321e-08' </code></pre> <hr> <p>It has been suggested that I can use <code>format</code> with <code>f</code> flag and sufficient precision to get rid of the scientific notation:</p> <pre><code>&gt;&gt;&gt; format(0.00000005, '.20f') '0.00000005000000000000' </code></pre> <p>It works for that number, though it has some extra trailing zeroes. But then the same format fails for <code>.1</code>, which gives decimal digits beyond the actual machine precision of float:</p> <pre><code>&gt;&gt;&gt; format(0.1, '.20f') '0.10000000000000000555' </code></pre> <p>And if my number is <code>4.5678e-20</code>, using <code>.20f</code> would still lose relative precision:</p> <pre><code>&gt;&gt;&gt; format(4.5678e-20, '.20f') '0.00000000000000000005' </code></pre> <p>Thus <strong>these approaches do not match my requirements</strong>.</p> <hr> <p>This leads to the question: what is the easiest and also well-performing way to print arbitrary floating point number in decimal format, having the same digits as in <a href="http://stackoverflow.com/a/28493269/918959"><code>repr(n)</code> (or <code>str(n)</code> on Python 3)</a>, but always using the decimal format, not the scientific notation.</p> <p>That is, a function or operation that for example converts the float value <code>0.00000005</code> to string <code>'0.00000005'</code>; <code>0.1</code> to <code>'0.1'</code>; <code>420000000000000000.0</code> to <code>'420000000000000000.0'</code> or <code>420000000000000000</code> and formats the float value <code>-4.5678e-5</code> as <code>'-0.000045678'</code>.</p> <hr> <p>After the bounty period: It seems that there are at least 2 viable approaches, as Karin demonstrated that using string manipulation one can achieve significant speed boost compared to my initial algorithm on Python 2.</p> <p>Thus,</p> <ul> <li>If performance is important and Python 2 compatibility is required; or if the <code>decimal</code> module cannot be used for some reason, then <a href="http://stackoverflow.com/a/38983595/918959">Karin's approach using string manipulation</a> is the way to do it.</li> <li>On Python 3, <a href="http://stackoverflow.com/a/38847691/918959">my somewhat shorter code will also be faster</a>.</li> </ul> <p>Since I am primarily developing on Python 3, I will accept my own answer, and shall award Karin the bounty.</p>
27
2016-08-09T10:01:59Z
38,950,952
<p>If you are ready to lose your precision arbitrary by calling <code>str()</code> on the float number, then it's the way to go:</p> <pre><code>import decimal def float_to_string(number, precision=20): return '{0:.{prec}f}'.format( decimal.Context(prec=100).create_decimal(str(number)), prec=precision, ).rstrip('0').rstrip('.') or '0' </code></pre> <p>It doesn't include global variables and allows you to choose the precision yourself. Decimal precision 100 is chosen as an upper bound for <code>str(float)</code> length. The actual supremum is much lower. The <code>or '0'</code> part is for the situation with small numbers and zero precision.</p> <p>Note that it still has its consequences:</p> <pre><code>&gt;&gt; float_to_string(0.10101010101010101010101010101) '0.10101010101' </code></pre> <p>Otherwise, if the precision is important, <code>format</code> is just fine:</p> <pre><code>import decimal def float_to_string(number, precision=20): return '{0:.{prec}f}'.format( number, prec=precision, ).rstrip('0').rstrip('.') or '0' </code></pre> <p>It doesn't miss the precision being lost while calling <code>str(f)</code>. The <code>or</code></p> <pre><code>&gt;&gt; float_to_string(0.1, precision=10) '0.1' &gt;&gt; float_to_string(0.1) '0.10000000000000000555' &gt;&gt;float_to_string(0.1, precision=40) '0.1000000000000000055511151231257827021182' &gt;&gt;float_to_string(4.5678e-5) '0.000045678' &gt;&gt;float_to_string(4.5678e-5, precision=1) '0' </code></pre> <p>Anyway, maximum decimal places are limited, since the <code>float</code> type itself has its limits and cannot express really long floats:</p> <pre><code>&gt;&gt; float_to_string(0.1, precision=10000) '0.1000000000000000055511151231257827021181583404541015625' </code></pre> <p>Also, whole numbers are being formatted as-is.</p> <pre><code>&gt;&gt; float_to_string(100) '100' </code></pre>
1
2016-08-15T07:29:26Z
[ "python", "python-3.x", "floating-point", "number-formatting", "python-2.x" ]
Convert float to string without scientific notation and false precision
38,847,690
<p>I want to print some floating point numbers so that they're always written in decimal form (e.g. <code>12345000000000000000000.0</code> or <code>0.000000000000012345</code>, not in <a href="https://en.wikipedia.org/wiki/Scientific_notation" rel="nofollow">scientific notation</a>, yet I'd want to keep the 15.7 decimal digits of precision and no more.</p> <p>It is well-known that the <code>repr</code> of a <code>float</code> is written in scientific notation if the exponent is greater than 15, or less than -4:</p> <pre><code>&gt;&gt;&gt; n = 0.000000054321654321 &gt;&gt;&gt; n 5.4321654321e-08 # scientific notation </code></pre> <p>If <code>str</code> is used, the resulting string again is in scientific notation:</p> <pre><code>&gt;&gt;&gt; str(n) '5.4321654321e-08' </code></pre> <hr> <p>It has been suggested that I can use <code>format</code> with <code>f</code> flag and sufficient precision to get rid of the scientific notation:</p> <pre><code>&gt;&gt;&gt; format(0.00000005, '.20f') '0.00000005000000000000' </code></pre> <p>It works for that number, though it has some extra trailing zeroes. But then the same format fails for <code>.1</code>, which gives decimal digits beyond the actual machine precision of float:</p> <pre><code>&gt;&gt;&gt; format(0.1, '.20f') '0.10000000000000000555' </code></pre> <p>And if my number is <code>4.5678e-20</code>, using <code>.20f</code> would still lose relative precision:</p> <pre><code>&gt;&gt;&gt; format(4.5678e-20, '.20f') '0.00000000000000000005' </code></pre> <p>Thus <strong>these approaches do not match my requirements</strong>.</p> <hr> <p>This leads to the question: what is the easiest and also well-performing way to print arbitrary floating point number in decimal format, having the same digits as in <a href="http://stackoverflow.com/a/28493269/918959"><code>repr(n)</code> (or <code>str(n)</code> on Python 3)</a>, but always using the decimal format, not the scientific notation.</p> <p>That is, a function or operation that for example converts the float value <code>0.00000005</code> to string <code>'0.00000005'</code>; <code>0.1</code> to <code>'0.1'</code>; <code>420000000000000000.0</code> to <code>'420000000000000000.0'</code> or <code>420000000000000000</code> and formats the float value <code>-4.5678e-5</code> as <code>'-0.000045678'</code>.</p> <hr> <p>After the bounty period: It seems that there are at least 2 viable approaches, as Karin demonstrated that using string manipulation one can achieve significant speed boost compared to my initial algorithm on Python 2.</p> <p>Thus,</p> <ul> <li>If performance is important and Python 2 compatibility is required; or if the <code>decimal</code> module cannot be used for some reason, then <a href="http://stackoverflow.com/a/38983595/918959">Karin's approach using string manipulation</a> is the way to do it.</li> <li>On Python 3, <a href="http://stackoverflow.com/a/38847691/918959">my somewhat shorter code will also be faster</a>.</li> </ul> <p>Since I am primarily developing on Python 3, I will accept my own answer, and shall award Karin the bounty.</p>
27
2016-08-09T10:01:59Z
38,983,595
<p>If you are satisfied with the precision in scientific notation, then could we just take a simple string manipulation approach? Maybe it's not terribly clever, but it seems to work (passes all of the use cases you've presented), and I think it's fairly understandable:</p> <pre><code>def float_to_str(f): float_string = repr(f) if 'e' in float_string: # detect scientific notation digits, exp = float_string.split('e') digits = digits.replace('.', '').replace('-', '') exp = int(exp) zero_padding = '0' * (abs(int(exp)) - 1) # minus 1 for decimal point in the sci notation sign = '-' if f &lt; 0 else '' if exp &gt; 0: float_string = '{}{}{}.0'.format(sign, digits, zero_padding) else: float_string = '{}0.{}{}'.format(sign, zero_padding, digits) return float_string n = 0.000000054321654321 assert(float_to_str(n) == '0.000000054321654321') n = 0.00000005 assert(float_to_str(n) == '0.00000005') n = 420000000000000000.0 assert(float_to_str(n) == '420000000000000000.0') n = 4.5678e-5 assert(float_to_str(n) == '0.000045678') n = 1.1 assert(float_to_str(n) == '1.1') n = -4.5678e-5 assert(float_to_str(n) == '-0.000045678') </code></pre> <p><strong>Performance</strong>:</p> <p>I was worried this approach may be too slow, so I ran <code>timeit</code> and compared with the OP's solution of decimal contexts. It appears the string manipulation is actually quite a bit faster. <strong>Edit</strong>: It appears to only be much faster in Python 2. In Python 3, the results were similar, but with the decimal approach slightly faster.</p> <p><strong>Result</strong>:</p> <ul> <li><p>Python 2: using <code>ctx.create_decimal()</code>: <code>2.43655490875</code></p></li> <li><p>Python 2: using string manipulation: <code>0.305557966232</code></p></li> <li><p>Python 3: using <code>ctx.create_decimal()</code>: <code>0.19519368198234588</code></p></li> <li><p>Python 3: using string manipulation: <code>0.2661344590014778</code></p></li> </ul> <p>Here is the timing code:</p> <pre><code>from timeit import timeit CODE_TO_TIME = ''' float_to_str(0.000000054321654321) float_to_str(0.00000005) float_to_str(420000000000000000.0) float_to_str(4.5678e-5) float_to_str(1.1) float_to_str(-0.000045678) ''' SETUP_1 = ''' import decimal # create a new context for this task ctx = decimal.Context() # 20 digits should be enough for everyone :D ctx.prec = 20 def float_to_str(f): """ Convert the given float to a string, without resorting to scientific notation """ d1 = ctx.create_decimal(repr(f)) return format(d1, 'f') ''' SETUP_2 = ''' def float_to_str(f): float_string = repr(f) if 'e' in float_string: # detect scientific notation digits, exp = float_string.split('e') digits = digits.replace('.', '').replace('-', '') exp = int(exp) zero_padding = '0' * (abs(int(exp)) - 1) # minus 1 for decimal point in the sci notation sign = '-' if f &lt; 0 else '' if exp &gt; 0: float_string = '{}{}{}.0'.format(sign, digits, zero_padding) else: float_string = '{}0.{}{}'.format(sign, zero_padding, digits) return float_string ''' print(timeit(CODE_TO_TIME, setup=SETUP_1, number=10000)) print(timeit(CODE_TO_TIME, setup=SETUP_2, number=10000)) </code></pre>
13
2016-08-16T20:09:16Z
[ "python", "python-3.x", "floating-point", "number-formatting", "python-2.x" ]
Convert float to string without scientific notation and false precision
38,847,690
<p>I want to print some floating point numbers so that they're always written in decimal form (e.g. <code>12345000000000000000000.0</code> or <code>0.000000000000012345</code>, not in <a href="https://en.wikipedia.org/wiki/Scientific_notation" rel="nofollow">scientific notation</a>, yet I'd want to keep the 15.7 decimal digits of precision and no more.</p> <p>It is well-known that the <code>repr</code> of a <code>float</code> is written in scientific notation if the exponent is greater than 15, or less than -4:</p> <pre><code>&gt;&gt;&gt; n = 0.000000054321654321 &gt;&gt;&gt; n 5.4321654321e-08 # scientific notation </code></pre> <p>If <code>str</code> is used, the resulting string again is in scientific notation:</p> <pre><code>&gt;&gt;&gt; str(n) '5.4321654321e-08' </code></pre> <hr> <p>It has been suggested that I can use <code>format</code> with <code>f</code> flag and sufficient precision to get rid of the scientific notation:</p> <pre><code>&gt;&gt;&gt; format(0.00000005, '.20f') '0.00000005000000000000' </code></pre> <p>It works for that number, though it has some extra trailing zeroes. But then the same format fails for <code>.1</code>, which gives decimal digits beyond the actual machine precision of float:</p> <pre><code>&gt;&gt;&gt; format(0.1, '.20f') '0.10000000000000000555' </code></pre> <p>And if my number is <code>4.5678e-20</code>, using <code>.20f</code> would still lose relative precision:</p> <pre><code>&gt;&gt;&gt; format(4.5678e-20, '.20f') '0.00000000000000000005' </code></pre> <p>Thus <strong>these approaches do not match my requirements</strong>.</p> <hr> <p>This leads to the question: what is the easiest and also well-performing way to print arbitrary floating point number in decimal format, having the same digits as in <a href="http://stackoverflow.com/a/28493269/918959"><code>repr(n)</code> (or <code>str(n)</code> on Python 3)</a>, but always using the decimal format, not the scientific notation.</p> <p>That is, a function or operation that for example converts the float value <code>0.00000005</code> to string <code>'0.00000005'</code>; <code>0.1</code> to <code>'0.1'</code>; <code>420000000000000000.0</code> to <code>'420000000000000000.0'</code> or <code>420000000000000000</code> and formats the float value <code>-4.5678e-5</code> as <code>'-0.000045678'</code>.</p> <hr> <p>After the bounty period: It seems that there are at least 2 viable approaches, as Karin demonstrated that using string manipulation one can achieve significant speed boost compared to my initial algorithm on Python 2.</p> <p>Thus,</p> <ul> <li>If performance is important and Python 2 compatibility is required; or if the <code>decimal</code> module cannot be used for some reason, then <a href="http://stackoverflow.com/a/38983595/918959">Karin's approach using string manipulation</a> is the way to do it.</li> <li>On Python 3, <a href="http://stackoverflow.com/a/38847691/918959">my somewhat shorter code will also be faster</a>.</li> </ul> <p>Since I am primarily developing on Python 3, I will accept my own answer, and shall award Karin the bounty.</p>
27
2016-08-09T10:01:59Z
39,000,705
<p>Interesting question, to add a little bit more of content to the question, here's a litte test comparing @Antti Haapala and @Harold solutions outputs:</p> <pre><code>import decimal import math ctx = decimal.Context() def f1(number, prec=20): ctx.prec = prec return format(ctx.create_decimal(str(number)), 'f') def f2(number, prec=20): return '{0:.{prec}f}'.format( number, prec=prec, ).rstrip('0').rstrip('.') k = 2*8 for i in range(-2**8,2**8): if i&lt;0: value = -k*math.sqrt(math.sqrt(-i)) else: value = k*math.sqrt(math.sqrt(i)) value_s = '{0:.{prec}E}'.format(value, prec=10) n = 10 print ' | '.join([str(value), value_s]) for f in [f1, f2]: test = [f(value, prec=p) for p in range(n)] print '\t{0}'.format(test) </code></pre> <p>Neither of them gives "consistent" results for all cases.</p> <ul> <li>With Anti's you'll see strings like '-000' or '000'</li> <li>With Harolds's you'll see strings like ''</li> </ul> <p>I'd prefer consistency even if I'm sacrificing a little bit of speed. Depends which tradeoffs you want to assume for your use-case.</p>
0
2016-08-17T15:27:39Z
[ "python", "python-3.x", "floating-point", "number-formatting", "python-2.x" ]
Convert float to string without scientific notation and false precision
38,847,690
<p>I want to print some floating point numbers so that they're always written in decimal form (e.g. <code>12345000000000000000000.0</code> or <code>0.000000000000012345</code>, not in <a href="https://en.wikipedia.org/wiki/Scientific_notation" rel="nofollow">scientific notation</a>, yet I'd want to keep the 15.7 decimal digits of precision and no more.</p> <p>It is well-known that the <code>repr</code> of a <code>float</code> is written in scientific notation if the exponent is greater than 15, or less than -4:</p> <pre><code>&gt;&gt;&gt; n = 0.000000054321654321 &gt;&gt;&gt; n 5.4321654321e-08 # scientific notation </code></pre> <p>If <code>str</code> is used, the resulting string again is in scientific notation:</p> <pre><code>&gt;&gt;&gt; str(n) '5.4321654321e-08' </code></pre> <hr> <p>It has been suggested that I can use <code>format</code> with <code>f</code> flag and sufficient precision to get rid of the scientific notation:</p> <pre><code>&gt;&gt;&gt; format(0.00000005, '.20f') '0.00000005000000000000' </code></pre> <p>It works for that number, though it has some extra trailing zeroes. But then the same format fails for <code>.1</code>, which gives decimal digits beyond the actual machine precision of float:</p> <pre><code>&gt;&gt;&gt; format(0.1, '.20f') '0.10000000000000000555' </code></pre> <p>And if my number is <code>4.5678e-20</code>, using <code>.20f</code> would still lose relative precision:</p> <pre><code>&gt;&gt;&gt; format(4.5678e-20, '.20f') '0.00000000000000000005' </code></pre> <p>Thus <strong>these approaches do not match my requirements</strong>.</p> <hr> <p>This leads to the question: what is the easiest and also well-performing way to print arbitrary floating point number in decimal format, having the same digits as in <a href="http://stackoverflow.com/a/28493269/918959"><code>repr(n)</code> (or <code>str(n)</code> on Python 3)</a>, but always using the decimal format, not the scientific notation.</p> <p>That is, a function or operation that for example converts the float value <code>0.00000005</code> to string <code>'0.00000005'</code>; <code>0.1</code> to <code>'0.1'</code>; <code>420000000000000000.0</code> to <code>'420000000000000000.0'</code> or <code>420000000000000000</code> and formats the float value <code>-4.5678e-5</code> as <code>'-0.000045678'</code>.</p> <hr> <p>After the bounty period: It seems that there are at least 2 viable approaches, as Karin demonstrated that using string manipulation one can achieve significant speed boost compared to my initial algorithm on Python 2.</p> <p>Thus,</p> <ul> <li>If performance is important and Python 2 compatibility is required; or if the <code>decimal</code> module cannot be used for some reason, then <a href="http://stackoverflow.com/a/38983595/918959">Karin's approach using string manipulation</a> is the way to do it.</li> <li>On Python 3, <a href="http://stackoverflow.com/a/38847691/918959">my somewhat shorter code will also be faster</a>.</li> </ul> <p>Since I am primarily developing on Python 3, I will accept my own answer, and shall award Karin the bounty.</p>
27
2016-08-09T10:01:59Z
39,002,207
<p>I think <code>rstrip</code> can get the job done.</p> <pre><code>a=5.4321654321e-08 '{0:.40f}'.format(a).rstrip("0") # float number and delete the zeros on the right # '0.0000000543216543210000004442039220863003' # there's roundoff error though </code></pre> <p>Let me know if that works for you.</p>
0
2016-08-17T16:48:00Z
[ "python", "python-3.x", "floating-point", "number-formatting", "python-2.x" ]
Exporting R data.frame/tbl to Google BigQuery table
38,847,743
<p>I know it's possible to import Google BigQuery tables to R through <code>bigrquery</code> library. But is it possible to export tables/data frames created in R to Google BigQuery as new tables? </p> <p>Basically, is there an R equivalent of Python's <code>temptable.insert_data(df)</code> or <code>df.to_sql()</code> ? </p> <p>thanks for your help, Kasia</p>
0
2016-08-09T10:03:48Z
39,119,230
<p>It looks like <code>bigrquery</code> package does the job through <code>insert_upload_job()</code>. In package documentation it says this function </p> <p><em>> is only suitable for relatively small datasets</em></p> <p>but it doesn't specify any size limits. For me, it's been working for tens of thousands of rows, so far.</p>
0
2016-08-24T09:19:18Z
[ "python", "dataframe", "google-bigquery" ]
Variable amount of Corners for a Polygon in Tkinter
38,847,857
<p>Busy fooling around with Tkinter, and was wondering if there was a way to create a polygon with a variable amount of corners? I'm trying to write a program that involves the user inputting a certain number of coordinates, and then a polygon with edges at those points is drawn on a canvas. Since I am unaware of the amount of values the user will input, it will be impossible to write code for every possibility, so is this actually possible?</p> <pre><code>canvas.create_polygon(x1,y1,x2,y2...xn,yn,fill="black") </code></pre>
0
2016-08-09T10:08:36Z
38,849,370
<p>You can pass an array of coordinates as long as they are pairs. eg:</p> <pre><code># triangle canvas.create_polygon([150,100, 100,150, 150,150], fill="red") # square canvas.create_polygon([0,0, 50,0, 50,50, 0,50], fill="black") </code></pre>
3
2016-08-09T11:23:40Z
[ "python", "tkinter", "tkinter-canvas" ]
Importing pyplot in a Jupyter Notebook
38,847,900
<p>Running Python 2.7 and trying to get plotting to work the tutorials recommend the below command.</p> <pre><code>from matplotlib import pyplot as plt </code></pre> <p>Works fine when run from the command line</p> <pre><code>python -c "from matplotlib import pyplot as plt" </code></pre> <p>but I get an error when trying to run it inside a Jupyter Notebook.</p> <pre><code>--------------------------------------------------------------------------- ImportError Traceback (most recent call last) &lt;ipython-input-21-1d1446f6fa64&gt; in &lt;module&gt;() ----&gt; 1 from matplotlib import pyplot as plt /usr/local/lib/python2.7/dist-packages/matplotlib/pyplot.py in &lt;module&gt;() 112 113 from matplotlib.backends import pylab_setup --&gt; 114 _backend_mod, new_figure_manager, draw_if_interactive, _show = pylab_setup() 115 116 _IP_REGISTERED = None /usr/local/lib/python2.7/dist-packages/matplotlib/backends/__init__.pyc in pylab_setup() 30 # imports. 0 means only perform absolute imports. 31 backend_mod = __import__(backend_name, ---&gt; 32 globals(),locals(),[backend_name],0) 33 34 # Things we pull in from all backends /usr/local/lib/python2.7/dist-packages/ipykernel/pylab/backend_inline.py in &lt;module&gt;() 154 configure_inline_support(ip, backend) 155 --&gt; 156 _enable_matplotlib_integration() /usr/local/lib/python2.7/dist-packages/ipykernel/pylab/backend_inline.py in _enable_matplotlib_integration() 152 backend = get_backend() 153 if ip and backend == 'module://%s' % __name__: --&gt; 154 configure_inline_support(ip, backend) 155 156 _enable_matplotlib_integration() /usr/local/lib/python2.7/dist-packages/IPython/core/pylabtools.pyc in configure_inline_support(shell, backend) 359 except ImportError: 360 return --&gt; 361 from matplotlib import pyplot 362 363 cfg = InlineBackend.instance(parent=shell) ImportError: cannot import name pyplot </code></pre> <p>The following command works</p> <pre><code>import matplotlib </code></pre> <p>But the following gives me a similar error</p> <pre><code>import matplotlib.pyplot </code></pre>
1
2016-08-09T10:10:08Z
38,851,858
<p>You can also use the <code>%matplotlib inline</code> magic, but it has to be preceded by the pure <code>%matplotlib</code> line:</p> <p><strong>Works (figures in new window)</strong></p> <pre><code>%matplotlib import matplotlib.pyplot as plt </code></pre> <p><strong>Works (inline figures)</strong></p> <pre><code>%matplotlib %matplotlib inline import matplotlib.pyplot as plt </code></pre> <p><strong>Does not work</strong></p> <pre><code>%matplotlib inline import matplotlib.pyplot as plt </code></pre> <p>Also: <a href="http://stackoverflow.com/questions/38838914/failure-to-import-matplotlib-pyplot-in-jupyter-but-not-ipython">Failure to import matplotlib.pyplot in jupyter (but not ipython)</a> seems to be the same issue. It looks like a recently introduced bug in the ipykernel. Maybe someone mark this or the other question as duplicate, thx.</p>
2
2016-08-09T13:16:09Z
[ "python", "matplotlib", "jupyter", "jupyter-notebook" ]
Implementing SJCL .frombits in python
38,847,927
<p>I'm trying to rewrite some JS (which uses the SJCL library) in Python using pycrypto. I'm having trouble figuring out how to implement the following code</p> <pre><code>aes = new sjcl.cipher.aes( this.key ); bits = sjcl.codec.utf8String.toBits( text ); cipher = sjcl.mode.ccm.encrypt( aes, bits, iv ); cipherIV = sjcl.bitArray.concat( iv, cipher ); return sjcl.codec.base64.fromBits( cipherIV ); </code></pre> <p>My issue isn't the crypto, but the way the library handles the fromBits conversions. According to the SJCL docs:</p> <blockquote> <p>Most of our crypto primitives operate on arrays of 4-byte words internally, but many of them can take arguments that are not a multiple of 4 bytes. This library encodes arrays of bits (whose size need not be a multiple of 8 bits) as arrays of 32-bit words. The bits are packed, big-endian, into an array of words, 32 bits at a time. Since the words are double-precision floating point numbers, they fit some extra data. We use this (in a private, possibly-changing manner) to encode the number of bits actually present in the last word of the array.</p> </blockquote> <p>To me this seems to imply that conversion to a bit array adds on some sort of additional information, which I am concerned will be prevalent during the <strong>concat</strong> operation. Additionally, after the concat, the result is returned as a base64 string. I am unsure of the proper 'struct' packing parameters to replicate this.</p>
0
2016-08-09T10:10:59Z
38,858,852
<p>If you look closely at this code you should see that it is self-contained. SJCL's "bits" (native binary data representation) are not needed after this code has run. This internal data is given into the encryption and concatenation functions, and the result is then converted back to a "normal" Base64-encoded string which is portable.</p> <p>The only problem that may exist with this code is the encoding of <code>this.key</code> and <code>ìv</code>.</p> <p>PyCrypto doesn't have a special internal binary data encoding, because the Python language already provides us with binary strings or <code>bytes</code> (depending on the Python version). But you still need to encode to / decode from string with a Base64 encoding.</p>
1
2016-08-09T19:23:12Z
[ "javascript", "python", "cryptography", "pycrypto", "sjcl" ]
choose n cluster for chemical fingerprint
38,847,940
<p>Hello I am trying to cluster chemical fingerprint</p> <p>I am using rdkit which provide a hierarchical method for cluster, the problem is that I know the number of cluster I want to have 13 clusters so I am using kmean method based on tanimoto similarity score with scikit</p> <p>here is my code :</p> <pre><code>smiles = [] molFin = [] fps = [] np_fps = [] #mol["idx"] contain the name of the molecules for x in mol["idx"]: res = cs.search(x) #get the smiles code of a molecule smi = res[0].smiles #get the fingerprint of the molecule fp = Chem.MolFromSmiles(str(smi)) fp = FingerprintMols.FingerprintMol(fp) fps.append(fp) #compute the similarity score (end up with a cross molecule matrix where each occurence correspond to the taminoto score) dists = [] nfps = len(fps) for i in range(0,nfps): sims = DataStructs.BulkTanimotoSimilarity(fps[i],fps) dists.append(sims) #store the value on a data frame and apply kmean mol_dist = pd.DataFrame(dists) k_means = cluster.KMeans(n_clusters=13) k1 = k_means.fit_predict(mol_dist) mol["cluster"] = k1 #get the result final = mol[["idx","cluster"]] </code></pre> <p>The clustering seems to work in a way but I have no idea how we do a the clustering for chemical fingerprint , shall we apply the clustering algorithm directly on the fingerprint themselve instead?</p>
1
2016-08-09T10:11:34Z
38,848,272
<p>I think the problem in clustering is how to choose appropriate k. Your problem may be resolve as follows:</p> <ol> <li><p>determine the appropriate k-clusters number. You can use some methods such as Elbow,... refer the link below -- <a href="https://datasciencelab.wordpress.com/2013/12/27/finding-the-k-in-k-means-clustering" rel="nofollow">https://datasciencelab.wordpress.com/2013/12/27/finding-the-k-in-k-means-clustering</a></p></li> <li><p>After having k-numbers, you choose the appropriate features along with obtained k-cluster then clustering your dataset and evaluation.</p></li> </ol> <p>Best regard ! </p>
0
2016-08-09T10:29:45Z
[ "python", "cluster-analysis", "rdkit" ]
Center align outputs in ipython notebook
38,848,219
<p>I want to center align the outputs (which includes text and plots) in my <code>ipython notebook</code>. Is there a way in which I can add styling in the same notebook for the same? Code or screenshot examples would greatly help.</p>
1
2016-08-09T10:26:23Z
38,859,920
<p>Try running this in a code-cell to override the default CSS for an output cell:</p> <pre><code>from IPython.display import display, HTML CSS = """ .output { align-items: center; } """ HTML('&lt;style&gt;{}&lt;/style&gt;'.format(CSS)) </code></pre> <p><strong>Example</strong> <a href="http://i.stack.imgur.com/8t4J8.png" rel="nofollow"><img src="http://i.stack.imgur.com/8t4J8.png" alt="Center align output Jupyter notebook"></a></p> <p>You can see here that the right side of the table is cut-off a bit and the string that is printed wraps to the next line. This can be fixed by playing around with the CSS a bit, but you'll have to customize it to your own output.</p> <p>In my case, I added the following lines to the CSS:</p> <pre><code>div.output_area { width: 30%; } </code></pre> <p>resulting in the following output:</p> <p><a href="http://i.stack.imgur.com/X4M3M.png" rel="nofollow"><img src="http://i.stack.imgur.com/X4M3M.png" alt="enter image description here"></a></p>
2
2016-08-09T20:33:42Z
[ "python", "css", "ipython", "ipython-notebook", "jupyter-notebook" ]
Python remove customized stop words from pandas dataframe
38,848,222
<p>I was following the next question: <a href="http://stackoverflow.com/questions/29523254/python-remove-stop-words-from-pandas-dataframe/38846564">Python remove stop words from pandas dataframe</a></p> <p>but it doesnt work for me for a customized stop words list, check out this code:</p> <pre><code> pos_tweets = [('I love this car', 'positive'), ('This view is amazing', 'positive'), ('I feel great this morning', 'positive'), ('I am so excited about the concert', 'positive'), ('He is my best friend', 'positive')] import pandas as pd test = pd.DataFrame(pos_tweets) test.columns = ["tweet","col2"] test["tweet"] = test["tweet"].str.lower().str.split() stop = ['love','car','amazing'] test['tweet'].apply(lambda x: [item for item in x if item not in stop) print test </code></pre> <p>the result is:</p> <pre><code> tweet col2 0 [i, love, this, car] positive 1 [this, view, is, amazing] positive 2 [i, feel, great, this, morning] positive 3 [i, am, so, excited, about, the, concert] positive 4 [he, is, my, best, friend] positive </code></pre> <p>the words love, car and amazing are still there, what Im missing?</p> <p>thanks!</p>
0
2016-08-09T10:26:50Z
38,848,260
<p>You need assign output back to column <code>tweet</code>:</p> <pre><code>test['tweet'] = test['tweet'].apply(lambda x: [item for item in x if item not in stop]) print (test) tweet col2 0 [i, this] positive 1 [this, view, is] positive 2 [i, feel, great, this, morning] positive 3 [i, am, so, excited, about, the, concert] positive 4 [he, is, my, best, friend] positive </code></pre>
0
2016-08-09T10:29:14Z
[ "python", "pandas", "dataframe" ]
How to use tornado coroutines in this case?
38,848,363
<p>I have created tornado server which accepts python and matlab code and executes it. Here is server code.</p> <pre><code>from zmq.eventloop.zmqstream import ZMQStream from zmq.eventloop import ioloop ioloop.install() from functools import partial from tornado import web, gen, escape from tornado import options, httpserver from tornado.concurrent import Future settings = dict() settings['autoreload'] = True settings['debug'] = True from jupyter_client import MultiKernelManager reply_futures = {} kids = [] class MainHandler(web.RequestHandler): def get(self): self.write("Hello") class ExecuteHandler(web.RequestHandler): def get(self): self.write("approaching execute") def post(self): data = escape.json_decode(self.request.body) print data self.application.execute_code(data) class Application(web.Application): def __init__(self): handlers = [] handlers.append((r"/", MainHandler)) handlers.append((r"/execute", ExecuteHandler)) web.Application.__init__(self, handlers, **settings) self.km = MultiKernelManager() self.setup_kernels() def setup_kernels(self): matlab_kernel_id = self.km.start_kernel(kernel_name="matlab") python_kernel_id = self.km.start_kernel(kernel_name="python") self.matlab_kernel_id = matlab_kernel_id self.python_kernel_id = python_kernel_id matkab_kernel_client = self.km.get_kernel(matlab_kernel_id).client() matkab_kernel_client.start_channels() python_kernel_client = self.km.get_kernel(python_kernel_id).client() python_kernel_client.start_channels() self.matkab_kernel_client = matkab_kernel_client self.python_kernel_client = python_kernel_client matlab_iopub_stream = ZMQStream(matkab_kernel_client.iopub_channel.socket) matlab_shell_stream = ZMQStream(matkab_kernel_client.shell_channel.socket) python_iopub_stream = ZMQStream(python_kernel_client.iopub_channel.socket) python_shell_stream = ZMQStream(python_kernel_client.shell_channel.socket) matlab_iopub_stream.on_recv_stream(partial(self.reply_callback, matkab_kernel_client.session)) matlab_shell_stream.on_recv_stream(partial(self.reply_callback, matkab_kernel_client.session)) python_iopub_stream.on_recv_stream(partial(self.reply_callback, python_kernel_client.session)) python_shell_stream.on_recv_stream(partial(self.reply_callback, python_kernel_client.session)) def reply_callback(self, session, stream, msg_list): idents, msg_parts = session.feed_identities(msg_list) reply = session.deserialize(msg_parts) if "stream" == reply["msg_type"]: print reply["content"]["text"] parent_id = reply['parent_header'].get('msg_id') reply_future = reply_futures.get(parent_id) if reply_future: reply_future.set_result(reply) def execute_code(self, data): matlab_code = data['matlab_code'] python_code = data['python_code'] self.execute_matlab_then_python(matlab_code, python_code) @gen.coroutine def execute_matlab_then_python(self, matlab_code, python_code): print "executing matlab code" parent_id1 = self.matkab_kernel_client.execute(matlab_code) f1 = reply_futures[parent_id1] = Future() yield f1 print "executing python code" parent_id2 = self.python_kernel_client.execute(python_code) f2 = reply_futures[parent_id2] = Future() yield f2 def shutdown_kernels(self): self.km.get_kernel(self.matlab_kernel_id).cleanup_connection_file() self.km.shutdown_kernel(self.matlab_kernel_id) self.km.get_kernel(self.python_kernel_id).cleanup_connection_file() self.km.shutdown_kernel(self.python_kernel_id) if __name__ == '__main__': options.parse_command_line() app = Application() server = httpserver.HTTPServer(app) server.listen(8888) try: ioloop.IOLoop.current().start() except KeyboardInterrupt: print 'going down' finally: app.shutdown_kernels() </code></pre> <p>The client code I use to access is, here</p> <pre><code>import json import requests matlab_code = "a=magic(3);disp(a)" python_code = "print 'Hello World!!'" data = {} data['matlab_code'] = matlab_code data['python_code'] = python_code r = requests.post('http://0.0.0.0:8888/execute', json.dumps(data)) </code></pre> <p>My concern is to maintain the order of execution, such that python code get executed only after matlab completes. I am using jupyter_client to execute the matlab/python code. I am using python27 here. The problem is that when I submit the code it throws <code>TypeError: 'NoneType' object is not iterable</code>. Here is a stack-trace out it.</p> <pre> [E 160809 15:17:51 ioloop:633] Exception in callback None Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/tornado/ioloop.py", line 887, in start handler_func(fd_obj, events) File "/usr/local/lib/python2.7/dist-packages/tornado/stack_context.py", line 275, in null_wrapper return fn(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/zmq/eventloop/zmqstream.py", line 440, in _handle_events self._handle_recv() File "/usr/local/lib/python2.7/dist-packages/zmq/eventloop/zmqstream.py", line 472, in _handle_recv self._run_callback(callback, msg) File "/usr/local/lib/python2.7/dist-packages/zmq/eventloop/zmqstream.py", line 414, in _run_callback callback(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/tornado/stack_context.py", line 275, in null_wrapper return fn(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/zmq/eventloop/zmqstream.py", line 191, in self.on_recv(lambda msg: callback(self, msg), copy=copy) File "tornado_test.py", line 86, in reply_callback reply_future.set_result(reply) File "/usr/local/lib/python2.7/dist-packages/tornado/concurrent.py", line 276, in set_result self._set_done() File "/usr/local/lib/python2.7/dist-packages/tornado/concurrent.py", line 320, in _set_done for cb in self._callbacks: TypeError: 'NoneType' object is not iterable </pre> <p>I don't understand what is problem here? </p>
2
2016-08-09T10:34:11Z
38,863,406
<p>The unfortunately cryptic error message "'NoneType' object is not iterable" means that you are calling <code>set_result</code> more than once on the same <code>Future</code> object. I don't know much about zmq or the jupyter kernel interfaces, but my guess is that either the IDs returned by the <code>execute</code> methods of the two different kernels are overlapping, or you're getting more than one response per execute call (from the two different streams?).</p>
0
2016-08-10T02:39:04Z
[ "python", "asynchronous", "tornado", "jupyter", "coroutine" ]
Apply function on each column in a pandas dataframe
38,848,411
<p>How I can write following function in more pandas way:</p> <pre><code> def calculate_df_columns_mean(self, df): means = {} for column in df.columns.columns.tolist(): cleaned_data = self.remove_outliers(df[column].tolist()) means[column] = np.mean(cleaned_data) return means </code></pre> <p>Thanks for help.</p>
-1
2016-08-09T10:36:21Z
38,848,528
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.apply.html" rel="nofollow"><code>dataFrame.apply(func, axis=0)</code></a>:</p> <pre><code># axis=0 means apply to columns; axis=1 to rows df.apply(numpy.sum, axis=0) # equiv to df.sum(0) </code></pre>
1
2016-08-09T10:41:15Z
[ "python", "pandas", "dataframe" ]
Apply function on each column in a pandas dataframe
38,848,411
<p>How I can write following function in more pandas way:</p> <pre><code> def calculate_df_columns_mean(self, df): means = {} for column in df.columns.columns.tolist(): cleaned_data = self.remove_outliers(df[column].tolist()) means[column] = np.mean(cleaned_data) return means </code></pre> <p>Thanks for help.</p>
-1
2016-08-09T10:36:21Z
38,848,624
<p>It seems to me that the iteration over the columns is unnecessary:</p> <pre><code>def calculate_df_columns_mean(self, df): cleaned_data = self.remove_outliers(df[column].tolist()) return cleaned_data.mean() </code></pre> <p>the above should be enough assuming that <code>remove_outliers</code> still returns a df</p> <p><strong>EDIT</strong></p> <p>I think the following should work:</p> <pre><code>def calculate_df_columns_mean(self, df): return df.apply(lambda x: remove_outliers(x.tolist()).mean() </code></pre>
2
2016-08-09T10:45:48Z
[ "python", "pandas", "dataframe" ]
except NameError not working
38,848,453
<p>I am trying to make a listool module.</p> <p>I am trying to make a checking function which checks the availability of an item in a list.</p> <p>Here is my non-working code:</p> <pre><code>def check(lst, item): try: if item in lst: return "Requested Item In List" else: return "Requested Item Not In List" except: pass </code></pre> <p><strong>I want to make it so if there is no list it just passes.</strong></p> <p>So when I do it with no list, here is the error:</p> <pre><code>&gt;&gt;&gt; import listools &gt;&gt;&gt; listools.check(example_list, 'example') Traceback (most recent call last): File "&lt;pyshell#1&gt;", line 1, in &lt;module&gt; listools.check(example_list, 'example') NameError: name 'example_list' is not defined &gt;&gt;&gt; </code></pre> <p>so what i want it to do is do nothing if there is no list but it comes out with a error (NameError)</p>
-1
2016-08-09T10:38:18Z
39,112,820
<p><code>NameError</code> typically indicates that the variable you are trying to reference does not exist. If you look at your error message, it says <code>name 'example_list' is not defined</code>. This should tell you, I tried to use <code>example_list</code> but the program couldn't find it. Most reasons for this are a) you defined a variable in a function/loop that is not accessible outside the function/loop (local variable), or b) you never defined the variable at all. In this case, given that the error message tells you that it was <strong>not</strong> a problem with the function but with your other code, you most likely forgot to define a variable. In this case, you should try defining <code>example_list</code> before using it.</p>
0
2016-08-24T00:53:07Z
[ "python", "list", "python-3.x", "module", "availability" ]
Sortin apache log with Python
38,848,537
<p>For example I have this simple apache log:</p> <pre><code>192.168.1.1 GET /index.php 192.168.1.1 GET /pilt.png 192.168.1.1 GET /index.php 192.168.1.5 GET /index.php 192.168.1.5 GET /pilt.png 192.168.1.7 GET /index.php 192.168.1.7 GET /index.php 192.168.1.7 GET /index.php 192.168.1.7 GET /kaust/index.php 192.168.1.7 GET /index.php </code></pre> <p>How would I write a Python code to sort it out that all the similar IP addresses are together and counted how much IP addresses are there</p> <pre><code>w = open("C:\\Users\\xxx\\Desktop\\test.txt","r") for i in w: log=i.split(' ') print log[0] w.close() </code></pre> <p>Have tried so much, but can't write the code further.</p> <p>Thank you!</p>
0
2016-08-09T10:41:48Z
38,848,878
<p>This is how it will be done : </p> <pre><code>x = open('PATH_TO_FILE').read() from itertools import groupby from operator import itemgetter x = x.split('\n') for i in range(len(x)): x[i] = x[i].split(' ') j = 0 for elt, items in groupby(x, itemgetter(0)): j += 1 k = 0 print elt, items for i in items: k += 1 print i print 'Total count for IP ',i[0],' is :',k print 'Total unique IP address are : ',j </code></pre>
0
2016-08-09T10:58:31Z
[ "python", "apache", "python-2.7" ]
Sortin apache log with Python
38,848,537
<p>For example I have this simple apache log:</p> <pre><code>192.168.1.1 GET /index.php 192.168.1.1 GET /pilt.png 192.168.1.1 GET /index.php 192.168.1.5 GET /index.php 192.168.1.5 GET /pilt.png 192.168.1.7 GET /index.php 192.168.1.7 GET /index.php 192.168.1.7 GET /index.php 192.168.1.7 GET /kaust/index.php 192.168.1.7 GET /index.php </code></pre> <p>How would I write a Python code to sort it out that all the similar IP addresses are together and counted how much IP addresses are there</p> <pre><code>w = open("C:\\Users\\xxx\\Desktop\\test.txt","r") for i in w: log=i.split(' ') print log[0] w.close() </code></pre> <p>Have tried so much, but can't write the code further.</p> <p>Thank you!</p>
0
2016-08-09T10:41:48Z
38,849,169
<p>You can use <code>defaultdict(int)</code> for your purpose :</p> <pre><code>from collections import defaultdict my_dict = defaultdict(int) w = open("C:\\Users\\xxx\\Desktop\\test.txt", "r") for line in w: ip = line.split(' ')[0] my_dict[ip]+=1 my_dict # defaultdict(&lt;class 'int'&gt;, {'192.168.1.7': 5, '192.168.1.1': 3, '192.168.1.5': 2}) </code></pre>
0
2016-08-09T11:11:55Z
[ "python", "apache", "python-2.7" ]
ValueError: all the input arrays must have same number of dimensions
38,848,759
<p>I'm having a problem with <code>np.append</code>.</p> <p>I'm trying to duplicate the last column of 20x361 matrix <code>n_list_converted</code> by using the code below:</p> <pre><code>n_last = [] n_last = n_list_converted[:, -1] n_lists = np.append(n_list_converted, n_last, axis=1) </code></pre> <p>But I get error: </p> <blockquote> <p>ValueError: all the input arrays must have same number of dimensions</p> </blockquote> <p>However, I've checked the matrix dimensions by doing</p> <pre><code> print(n_last.shape, type(n_last), n_list_converted.shape, type(n_list_converted)) </code></pre> <p>and I get </p> <blockquote> <p>(20L,) (20L, 361L) </p> </blockquote> <p>so the dimensions match? Where is the mistake?</p>
1
2016-08-09T10:52:32Z
38,850,126
<p>(n,) and (n,1) are not the same shape. Try casting the vector to an array by using the <code>[:, None]</code> notation:</p> <pre><code>n_lists = np.append(n_list_converted, n_last[:, None], axis=1) </code></pre> <p>Alternatively, when extracting <code>n_last</code> you can use</p> <pre><code>n_last = n_list_converted[:, -1:] </code></pre> <p>to get a <code>(20, 1)</code> array.</p>
1
2016-08-09T12:00:13Z
[ "python", "arrays", "numpy", "append" ]
ValueError: all the input arrays must have same number of dimensions
38,848,759
<p>I'm having a problem with <code>np.append</code>.</p> <p>I'm trying to duplicate the last column of 20x361 matrix <code>n_list_converted</code> by using the code below:</p> <pre><code>n_last = [] n_last = n_list_converted[:, -1] n_lists = np.append(n_list_converted, n_last, axis=1) </code></pre> <p>But I get error: </p> <blockquote> <p>ValueError: all the input arrays must have same number of dimensions</p> </blockquote> <p>However, I've checked the matrix dimensions by doing</p> <pre><code> print(n_last.shape, type(n_last), n_list_converted.shape, type(n_list_converted)) </code></pre> <p>and I get </p> <blockquote> <p>(20L,) (20L, 361L) </p> </blockquote> <p>so the dimensions match? Where is the mistake?</p>
1
2016-08-09T10:52:32Z
38,850,254
<p>The reason why you get your error is because a "1 by n" matrix is different from an array of length n.</p> <p>I recommend using <code>hstack()</code> and <code>vstack()</code> instead. Like this:</p> <pre><code>import numpy as np a = np.arange(32).reshape(4,8) # 4 rows 8 columns matrix. b = a[:,-1:] # last column of that matrix. result = np.hstack((a,b)) # stack them horizontally like this: #array([[ 0, 1, 2, 3, 4, 5, 6, 7, 7], # [ 8, 9, 10, 11, 12, 13, 14, 15, 15], # [16, 17, 18, 19, 20, 21, 22, 23, 23], # [24, 25, 26, 27, 28, 29, 30, 31, 31]]) </code></pre> <p>Notice the repeated "7, 15, 23, 31" column. Also, notice that I used <code>a[:,-1:]</code> instead of <code>a[:,-1]</code>. My version generates a column:</p> <pre><code>array([[7], [15], [23], [31]]) </code></pre> <p>Instead of a row <code>array([7,15,23,31])</code></p> <hr> <p>Edit: <code>append()</code> is <em>much</em> slower. Read <a href="http://stackoverflow.com/a/5744459/4317303">this answer</a>.</p>
1
2016-08-09T12:06:37Z
[ "python", "arrays", "numpy", "append" ]
ValueError: all the input arrays must have same number of dimensions
38,848,759
<p>I'm having a problem with <code>np.append</code>.</p> <p>I'm trying to duplicate the last column of 20x361 matrix <code>n_list_converted</code> by using the code below:</p> <pre><code>n_last = [] n_last = n_list_converted[:, -1] n_lists = np.append(n_list_converted, n_last, axis=1) </code></pre> <p>But I get error: </p> <blockquote> <p>ValueError: all the input arrays must have same number of dimensions</p> </blockquote> <p>However, I've checked the matrix dimensions by doing</p> <pre><code> print(n_last.shape, type(n_last), n_list_converted.shape, type(n_list_converted)) </code></pre> <p>and I get </p> <blockquote> <p>(20L,) (20L, 361L) </p> </blockquote> <p>so the dimensions match? Where is the mistake?</p>
1
2016-08-09T10:52:32Z
38,855,679
<p>If I start with a 3x4 array, and concatenate a 3x1 array, with axis 1, I get a 3x5 array:</p> <pre><code>In [911]: x = np.arange(12).reshape(3,4) In [912]: np.concatenate([x,x[:,-1:]], axis=1) Out[912]: array([[ 0, 1, 2, 3, 3], [ 4, 5, 6, 7, 7], [ 8, 9, 10, 11, 11]]) In [913]: x.shape,x[:,-1:].shape Out[913]: ((3, 4), (3, 1)) </code></pre> <p>Note that both inputs to concatenate have 2 dimensions.</p> <p>Omit the <code>:</code>, and <code>x[:,-1]</code> is (3,) shape - it is 1d, and hence the error:</p> <pre><code>In [914]: np.concatenate([x,x[:,-1]], axis=1) ... ValueError: all the input arrays must have same number of dimensions </code></pre> <p>The code for <code>np.append</code> is (in this case where axis is specified)</p> <pre><code>return concatenate((arr, values), axis=axis) </code></pre> <p>So with a slight change of syntax <code>append</code> works. Instead of a list it takes 2 arguments. It imitates the list <code>append</code> is syntax, but should not be confused with that list method.</p> <pre><code>In [916]: np.append(x, x[:,-1:], axis=1) Out[916]: array([[ 0, 1, 2, 3, 3], [ 4, 5, 6, 7, 7], [ 8, 9, 10, 11, 11]]) </code></pre> <p><code>np.hstack</code> first makes sure all inputs are <code>atleast_1d</code>, and then does concatenate:</p> <pre><code>return np.concatenate([np.atleast_1d(a) for a in arrs], 1) </code></pre> <p>So it requires the same <code>x[:,-1:]</code> input. Essentially the same action.</p> <p><code>np.column_stack</code> also does a concatenate on axis 1. But first it passes 1d inputs through</p> <pre><code>array(arr, copy=False, subok=True, ndmin=2).T </code></pre> <p>This is a general way of turning that (3,) array into a (3,1) array.</p> <pre><code>In [922]: np.array(x[:,-1], copy=False, subok=True, ndmin=2).T Out[922]: array([[ 3], [ 7], [11]]) In [923]: np.column_stack([x,x[:,-1]]) Out[923]: array([[ 0, 1, 2, 3, 3], [ 4, 5, 6, 7, 7], [ 8, 9, 10, 11, 11]]) </code></pre> <p>All these 'stacks' can be convenient, but in the long run, it's important to understand dimensions and the base <code>np.concatenate</code>. Also know how to look up the code for functions like this. I use the <code>ipython</code> <code>??</code> magic a lot.</p> <p>And in time tests, the <code>np.concatenate</code> is noticeably faster - with a small array like this the extra layers of function calls makes a big time difference.</p>
1
2016-08-09T16:09:05Z
[ "python", "arrays", "numpy", "append" ]