title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
Calling methods from C/C++ DLL with Python
38,997,898
<p>I do have a tutorial here about calling functions from a c/c++ dll, the example is written here from the <a href="https://docs.python.org/3.3/library/ctypes.html#function-prototypes" rel="nofollow">official tutorial</a>.</p> <pre><code>WINUSERAPI int WINAPI MessageBoxA( HWND hWnd, LPCSTR lpText, LPCSTR lpCaption, UINT uType); Here is the wrapping with ctypes: &gt;&gt;&gt; &gt;&gt;&gt; from ctypes import c_int, WINFUNCTYPE, windll &gt;&gt;&gt; from ctypes.wintypes import HWND, LPCSTR, UINT &gt;&gt;&gt; prototype = WINFUNCTYPE(c_int, HWND, LPCSTR, LPCSTR, UINT) &gt;&gt;&gt; paramflags = (1, "hwnd", 0), (1, "text", "Hi"), (1, "caption", None), (1, "flags", 0) &gt;&gt;&gt; MessageBox = prototype(("MessageBoxA", windll.user32), paramflags) &gt;&gt;&gt; The MessageBox foreign function can now be called in these ways: &gt;&gt;&gt; &gt;&gt;&gt; MessageBox() &gt;&gt;&gt; MessageBox(text="Spam, spam, spam") &gt;&gt;&gt; MessageBox(flags=2, text="foo bar") &gt;&gt;&gt; A second example demonstrates output parameters. The win32 GetWindowRect function retrieves the dimensions of a specified window by copying them into RECT structure that the caller has to supply. Here is the C declaration: WINUSERAPI BOOL WINAPI GetWindowRect( HWND hWnd, LPRECT lpRect); Here is the wrapping with ctypes: &gt;&gt;&gt; &gt;&gt;&gt; from ctypes import POINTER, WINFUNCTYPE, windll, WinError &gt;&gt;&gt; from ctypes.wintypes import BOOL, HWND, RECT &gt;&gt;&gt; prototype = WINFUNCTYPE(BOOL, HWND, POINTER(RECT)) &gt;&gt;&gt; paramflags = (1, "hwnd"), (2, "lprect") &gt;&gt;&gt; GetWindowRect = prototype(("GetWindowRect", windll.user32), paramflags) &gt;&gt;&gt; </code></pre> <p>This example works when the function is external, however, let's assume I have a reference to an object, and I want to call a function from that object with params, how do I do that?</p> <p>I did saw the log of all function signatures from 'dumpbin -exports', and I tried using the full name of the function, and still it didn't work.</p> <p>Any other ideas would be blessed.</p>
0
2016-08-17T13:20:57Z
38,998,526
<p>Unfortunately, you can not do that easily and in portable way with <code>ctypes</code>.</p> <p><code>ctypes</code> is designed to call <strong>functions</strong> in DLLs with <strong>C compatible data</strong> types. </p> <p>Since there is no <a href="https://en.wikipedia.org/wiki/Application_binary_interface" rel="nofollow">standard binary interface</a> for C++, you should know how the compiler which generates the DLL, generates the code (i.e class layout ... ).</p> <p>A better solution is to create a new DLL which uses the current DLL and wraps the methods as plain c functions. See <a href="http://www.boost.org/doc/libs/1_61_0/libs/python/doc/html/index.html" rel="nofollow">boost.python</a> or <a href="http://www.swig.org/" rel="nofollow">SWIG</a> for more details.</p>
0
2016-08-17T13:48:15Z
[ "python", "c++", "c", "dll" ]
Python bitwise logic to operate LEDs
38,997,913
<p>So i'm currently playing with my Raspberry Pi and 7 segment(actually 8 because there is dot) display and i need help. I know how to operate it using single LEDs(so for example i know which LEDs i need to light up to create "1" so i can basically operate it) but there was code in manual that's using some bitwise logic which is far beyond my understanding.</p> <pre><code> #!/usr/bin/env python import RPi.GPIO as GPIO import time pins = [11,12,13,15,16,18,22,7] dats = [0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,0x7f,0x6f,0x77,0x7c,0x39,0x5e,0x79,0x71,0x80] def setup(): GPIO.setmode(GPIO.BOARD) for pin in pins: GPIO.setup(pin, GPIO.OUT) # Set pin mode as output GPIO.output(pin, GPIO.LOW) def writeOneByte(val): GPIO.output(11, val &amp; (0x01 &lt;&lt; 0)) GPIO.output(12, val &amp; (0x01 &lt;&lt; 1)) GPIO.output(13, val &amp; (0x01 &lt;&lt; 2)) GPIO.output(15, val &amp; (0x01 &lt;&lt; 3)) GPIO.output(16, val &amp; (0x01 &lt;&lt; 4)) GPIO.output(18, val &amp; (0x01 &lt;&lt; 5)) GPIO.output(22, val &amp; (0x01 &lt;&lt; 6)) GPIO.output(7, val &amp; (0x01 &lt;&lt; 7)) def loop(): while True: for dat in dats: writeOneByte(dat) time.sleep(0.5) def destroy(): for pin in pins: GPIO.output(pin, GPIO.LOW) GPIO.cleanup() # Release resource if __name__ == '__main__': # Program start from here setup() try: loop() except KeyboardInterrupt: # When 'Ctrl+C' is pressed, the child program destroy() will be executed. destroy() </code></pre> <p>The code above cycles through 0-9 and A-F and then dot.</p> <p>Every help/explanation/advice is welcome.</p> <p>EDIT: I GET IT NOW. Just turned on my brain. CLOSED.</p>
2
2016-08-17T13:22:03Z
39,001,354
<h2>SETUP</h2> <p>I'm going to refer to this image I found on a <a href="https://www.reddit.com/r/EngineeringStudents/comments/3pl9jv/designed_my_first_pcb_hope_i_made_you_all_proud/" rel="nofollow">thread on reddit</a>:</p> <p><a href="http://i.stack.imgur.com/a3zfz.png" rel="nofollow"><img src="http://i.stack.imgur.com/a3zfz.png" alt="seven segment truth table"></a></p> <p>So the pins correspond to the segments as follows:</p> <p><strong>A</strong>: 11<br> <strong>B</strong>: 12<br> <strong>C</strong>: 13<br> <strong>D</strong>: 15<br> <strong>E</strong>: 16<br> <strong>F</strong>: 18<br> <strong>G</strong>: 22 </p> <hr> <p>Now let's see what happens when we call <code>writeOneByte</code> with the first value in the list named <code>dats</code>, i.e <strong>0x3f</strong>. </p> <p>The first line in the function is </p> <pre><code>GPIO.output(11, val &amp; (0x01 &lt;&lt; 0)) </code></pre> <p><code>val</code> holds the value <strong>0x3f</strong> which is what was passed into the function. This value is equivalent to <strong>0b00111111</strong> in binary. Looking again at the diagram, we see that the letters <strong>A</strong>-<strong>G</strong> actually correspond to each bit, from the least significant (right most bit) to the second most significant bit. The most significant bit is reserved for the dot.</p> <hr> <h2>BITWISE OPERATIONS</h2> <p>The <code>&lt;&lt;</code> is the left-shift operator. The code <code>0x01 &lt;&lt; 0</code> means shift the number <strong>0x01</strong> <em>zero</em> bits to the left. Therefore, the operation leaves the number unchanged, and the result is still <strong>0x01</strong>, which is equivalent to <strong>0b00000001</strong>. </p> <p>Next up is <code>&amp;</code>, the bitwise <code>AND</code> operator. This performs a logical <code>AND</code> operation on a bit-by-bit basis. It's easy to see in an example:</p> <pre><code>0b00111111 0b00000001 ---------- 0b00000001 </code></pre> <p>Essentially what we are doing is checking the first (least significant) bit of the number in <code>val</code> and checking to see whether the corresponding pin should have a <code>HIGH</code> or a <code>LOW</code> output. In this case, the value of the first bit is 1. After the <code>AND</code> operation, the value passed to <code>GPIO.output</code> for pin 11 (which corresponds to segment <strong>A</strong>), is <strong>0b00000001</strong>. This outputs a <code>HIGH</code> value, because anything that is not all zeroes translates into a boolean true.</p> <p>The process is repeated on the remaining lines of code:</p> <pre><code>GPIO.output(12, val &amp; (0x01 &lt;&lt; 1)) </code></pre> <p>This time <strong>0b00000001</strong> is shifted 1 bit to the left, yielding <strong>0b00000010</strong>. We perform the bitwise <code>AND</code> again:</p> <pre><code>0b00111111 0b00000010 ---------- 0b00000010 </code></pre> <p>which is also a <code>HIGH</code> output for pin 12, and thus segment B is on. </p> <p>In fact, the only time we get a <code>LOW</code> is with pin 7, in the last line:</p> <pre><code>GPIO.output(7, val &amp; (0x01 &lt;&lt; 7)) 0b00111111 0b01000000 ---------- 0b00000000 </code></pre> <p>As you can see in the diagram, the bits that drive the pins take on the appropriate values to yield the number <code>0</code> in the given display arrangement.</p>
1
2016-08-17T16:00:24Z
[ "python", "raspberry-pi", "bit-manipulation" ]
Why does my nested loop throw an exception in Python?
38,998,035
<p>This is a simple code,</p> <pre><code>def door_traversal(): arr = [] for i in range(1, 101, 1): arr.append(0) for i in range(1, 101, 1): for j in range(i, 101, i): arr[j] = not arr[j] count = 0 for i in range(1, 101, 1): if arr[i] == 1: count += 1 return count </code></pre> <p>I get the following error,</p> <pre><code>arr[j] = not arr[j] IndexError: list index out of range </code></pre> <p>When I run the code in the debugger, I see that after executing the inner loop for the first time the program counter skips, it's never running the inner loop 100 times. I'm new to Python, any help appreciated.</p>
0
2016-08-17T13:27:21Z
38,998,179
<p>you're accessing the indices from 1 to 101 but the first index of a list is 0, you should iterate with for i in range(100)</p> <pre><code>def door_traversal(): arr = [0 for i in range(100)] for i in range(100): for j in range(100): arr[j] = not arr[j] count = 0 for i in range(100): if arr[i] == 1: count += 1 return count </code></pre> <p>if you want to use custom indices maybe you could use a dictionary</p> <pre><code>def door_traversal(): arr = {} for i in range(1, 101, 1): arr[i] = 0 for i in range(1, 101, 1): for j in range(i, 101, i): arr[j] = not arr[j] count = 0 for i in range(1, 101, 1): if arr[i] == 1: count += 1 return count </code></pre>
3
2016-08-17T13:34:14Z
[ "python" ]
Why does my nested loop throw an exception in Python?
38,998,035
<p>This is a simple code,</p> <pre><code>def door_traversal(): arr = [] for i in range(1, 101, 1): arr.append(0) for i in range(1, 101, 1): for j in range(i, 101, i): arr[j] = not arr[j] count = 0 for i in range(1, 101, 1): if arr[i] == 1: count += 1 return count </code></pre> <p>I get the following error,</p> <pre><code>arr[j] = not arr[j] IndexError: list index out of range </code></pre> <p>When I run the code in the debugger, I see that after executing the inner loop for the first time the program counter skips, it's never running the inner loop 100 times. I'm new to Python, any help appreciated.</p>
0
2016-08-17T13:27:21Z
38,998,215
<p>Python list indices always start from zero. Thus, the following creates a list containing 100 elements, with indices from 0 to 99 (<em>not</em> from 1 to 100 as you might be expecting):</p> <pre><code>for i in range(1, 101, 1): arr.append(0) </code></pre> <p>Now, the following can try to access the element at index 100, which does not exist:</p> <pre><code>for i in range(1, 101, 1): for j in range(i, 101, i): arr[j] = not arr[j] </code></pre> <p>Hence the exception.</p>
3
2016-08-17T13:35:26Z
[ "python" ]
Why does my nested loop throw an exception in Python?
38,998,035
<p>This is a simple code,</p> <pre><code>def door_traversal(): arr = [] for i in range(1, 101, 1): arr.append(0) for i in range(1, 101, 1): for j in range(i, 101, i): arr[j] = not arr[j] count = 0 for i in range(1, 101, 1): if arr[i] == 1: count += 1 return count </code></pre> <p>I get the following error,</p> <pre><code>arr[j] = not arr[j] IndexError: list index out of range </code></pre> <p>When I run the code in the debugger, I see that after executing the inner loop for the first time the program counter skips, it's never running the inner loop 100 times. I'm new to Python, any help appreciated.</p>
0
2016-08-17T13:27:21Z
38,998,284
<p>In this line you add 100 items to <code>arr</code></p> <pre><code> for i in range(1, 101, 1): arr.append(0) </code></pre> <p>So your <code>arr</code> array is 100 items long. Then in this loop:</p> <pre><code> for i in range(1, 101, 1): for j in range(i, 101, i): arr[j] = not arr[j] </code></pre> <p>You say for <code>i</code> in between 1 and 101 you want to run the inner loop over <code>j</code>. The problem is that indices start at zero in Python, so <code>arr[101]</code> does not exist, only <code>arr[100]</code> If you want to ignore the index zero element, that's fine, you can start iterating through the array at index one, but the final element in the array will still be at place 100, as you have only added one hundred items to the list!</p> <p>You can solve this with:</p> <pre><code>def door_traversal(): arr = [] for i in range(100): arr.append(0) for i in range(1, 100): for j in range(i, 100, i): arr[j] = not arr[j] count = 0 for i in range(0, 100): if arr[i] == 1: count += 1 return count </code></pre>
1
2016-08-17T13:38:42Z
[ "python" ]
Why does my nested loop throw an exception in Python?
38,998,035
<p>This is a simple code,</p> <pre><code>def door_traversal(): arr = [] for i in range(1, 101, 1): arr.append(0) for i in range(1, 101, 1): for j in range(i, 101, i): arr[j] = not arr[j] count = 0 for i in range(1, 101, 1): if arr[i] == 1: count += 1 return count </code></pre> <p>I get the following error,</p> <pre><code>arr[j] = not arr[j] IndexError: list index out of range </code></pre> <p>When I run the code in the debugger, I see that after executing the inner loop for the first time the program counter skips, it's never running the inner loop 100 times. I'm new to Python, any help appreciated.</p>
0
2016-08-17T13:27:21Z
38,998,704
<p>You have some pretty fundamental errors in your understanding.</p> <p>First, lists in python <em>always</em> start with an index of 0. A list of size 3 looks like this:</p> <pre><code>three = [0, 1, 2] </code></pre> <p>The indexes are the values themselves. And yes, you could ignore the first element, and create a list like so:</p> <pre><code>names = [None, 'Wayne', 'CodeMonkey', 'King Arthur'] </code></pre> <p>But it has <em>4</em> elements. Everywhere in your code you're going to have to adjust this. Want to know the length? <code>len(names) - 1</code>. And so on and so forth. And if you're splitting your list, you're going to have to add values to those lists if you want consistent behavior:</p> <pre><code>these_names = names[:2] those_names = [None] + names[2:] </code></pre> <p>That's pretty painful. Don't do that - just get used the the fact that the index of an element in the list means the start of the list + <code>index</code> elements. So the item at the start of the list is the list name, e.g. <code>arr</code>, plus <code>[0]</code> elements.</p> <p>Here's your code re-written in a way that works, under the assumption that everything else is correct.</p> <pre><code>def door_traversal(): # If you really want a list with 101 elements, # So you can access the last item with `arr[100]` rather than `arr[99]`. # If you're using Python2, `range` is a list # already. arr = list(0 for _ in range(101)) # Or use a list comprehension arr = [0 for _ in range(101)] # There are probably better ways to do this, but it works now # also, no need to provide the step size if it's 1 for i in range(1, 101): for j in range(i, 101, i): arr[j] = not arr[j] count = 0 for i in range(1, 101, 1): if arr[i] == 1: count += 1 return count print(door_traversal()) </code></pre> <p>Also, I probably would rename <code>arr</code> to <code>doors</code>, or <code>visited_doors</code>, if that's what they represent. </p>
2
2016-08-17T13:54:10Z
[ "python" ]
Why does my nested loop throw an exception in Python?
38,998,035
<p>This is a simple code,</p> <pre><code>def door_traversal(): arr = [] for i in range(1, 101, 1): arr.append(0) for i in range(1, 101, 1): for j in range(i, 101, i): arr[j] = not arr[j] count = 0 for i in range(1, 101, 1): if arr[i] == 1: count += 1 return count </code></pre> <p>I get the following error,</p> <pre><code>arr[j] = not arr[j] IndexError: list index out of range </code></pre> <p>When I run the code in the debugger, I see that after executing the inner loop for the first time the program counter skips, it's never running the inner loop 100 times. I'm new to Python, any help appreciated.</p>
0
2016-08-17T13:27:21Z
39,000,022
<p>Index problems aside, please consider the following python idioms (with comments which are for pedagogical purposes only):</p> <pre><code>def door_traversal(): """got doc?""" # why does this func. exist? arr = [0] * 100 # list concatenation for i in range(1, 101, 1): for j in range(i, 101, i): arr[j] = not arr[j] return arr.count(1) # use the list method </code></pre>
0
2016-08-17T14:54:42Z
[ "python" ]
Flask permissions for file writing
38,998,060
<p>I'm running a Flask webserver on an EC2 Ubuntu instance. The purpose is to capture the body of an incoming POST, write it to a file locally, then upload that file to S3.</p> <p>The code is, basically:</p> <pre><code>@app.route('/', methods=['GET','POST']) @app.route('/index.html', methods=['GET','POST']) def index_home(): data = request.data with open('test.json', 'w') as f: f.write(data) ## Upload the stuff to S3 </code></pre> <p>When I run it on the local Flask webserver instance and send a POST with a json body from Postman, it works perfectly. But on the EC2 instance I'm getting a permissions error (according to the apache error.log) on the 'test.json' file, which results in 500 error on page-load.</p> <p>I've scoured Google and Stackoverflow (<a href="https://stackoverflow.com/questions/33965370/flask-apache-on-aws-ec2-read-write-failing">Here is a similar question</a>, with no solution) to no avail. This seems like an easy problem, but I've tried everything and can't seem to get it to work: I've added my user to the www-data group, I've changed the /var/www folders and files permissions to every combination of root, ubuntu (the default EC2 Ubuntu user) and www-data I could think of, I've straight 777 the directories...nothing seems to work.</p> <p>Obviously, I'm a bit of a newbie. Is there a configuration file or something that requires a tweak to get this to work?</p>
0
2016-08-17T13:28:34Z
38,998,429
<p>You should make sure the program is actually trying to write in the directory you want it to write to. It could be that it tries to write into the directory of the Python binary (or anything else), that depends on your command and the current working directory. For testing purposes you might try to change the path like so (make sure /tmp is writeable for the user, which should be the case):</p> <pre><code>with open('/tmp/test.json', 'w') as f: f.write(data) </code></pre>
2
2016-08-17T13:44:15Z
[ "python", "ubuntu", "amazon-ec2", "flask" ]
How to replace " ' " in python?
38,998,200
<p>So I just got a quick question. I need to replace (') in python but obviously it is not working.</p> <p>This is the code I use for replaceing things in python:</p> <pre><code>with open('ID.txt','r') as f: newlines = [] for line in f.readlines(): newlines.append(line.replace('Machine',)) with open('ID.txt', 'w') as f: for line in newlines: f.write(line) </code></pre> <p>Replacing Machine works fine but try out (') with the code... it just doesn't work. Can you tell me why? And how can I solve this little problem? ^^</p> <p>NOTE!: The apostrophe I want to replace does not contain the brackets. I just want to replace the apostrophe :)</p>
-5
2016-08-17T13:35:00Z
38,998,351
<p>Using <code>replace(''','')</code> will run into errors. Try this instead:</p> <p><code>line.replace("'","")</code></p>
0
2016-08-17T13:41:05Z
[ "python" ]
How to replace " ' " in python?
38,998,200
<p>So I just got a quick question. I need to replace (') in python but obviously it is not working.</p> <p>This is the code I use for replaceing things in python:</p> <pre><code>with open('ID.txt','r') as f: newlines = [] for line in f.readlines(): newlines.append(line.replace('Machine',)) with open('ID.txt', 'w') as f: for line in newlines: f.write(line) </code></pre> <p>Replacing Machine works fine but try out (') with the code... it just doesn't work. Can you tell me why? And how can I solve this little problem? ^^</p> <p>NOTE!: The apostrophe I want to replace does not contain the brackets. I just want to replace the apostrophe :)</p>
-5
2016-08-17T13:35:00Z
38,998,383
<p>You can write string literals in python in several ways like</p> <p><code>"bla'bla\"bla"</code>, <code>'bla\'bla"bla'</code>, <code>"""bla'bla"bla"""</code>, <code>'''bla'bla"bla'''</code></p> <p>See <a href="https://docs.python.org/3/tutorial/introduction.html#strings" rel="nofollow">https://docs.python.org/3/tutorial/introduction.html#strings</a></p>
0
2016-08-17T13:42:27Z
[ "python" ]
How to replace " ' " in python?
38,998,200
<p>So I just got a quick question. I need to replace (') in python but obviously it is not working.</p> <p>This is the code I use for replaceing things in python:</p> <pre><code>with open('ID.txt','r') as f: newlines = [] for line in f.readlines(): newlines.append(line.replace('Machine',)) with open('ID.txt', 'w') as f: for line in newlines: f.write(line) </code></pre> <p>Replacing Machine works fine but try out (') with the code... it just doesn't work. Can you tell me why? And how can I solve this little problem? ^^</p> <p>NOTE!: The apostrophe I want to replace does not contain the brackets. I just want to replace the apostrophe :)</p>
-5
2016-08-17T13:35:00Z
38,998,561
<pre><code>for a in '', "'", '"': print(''' 1'2'3"4"5 '''.replace(a, '*')) </code></pre>
0
2016-08-17T13:49:44Z
[ "python" ]
How to replace " ' " in python?
38,998,200
<p>So I just got a quick question. I need to replace (') in python but obviously it is not working.</p> <p>This is the code I use for replaceing things in python:</p> <pre><code>with open('ID.txt','r') as f: newlines = [] for line in f.readlines(): newlines.append(line.replace('Machine',)) with open('ID.txt', 'w') as f: for line in newlines: f.write(line) </code></pre> <p>Replacing Machine works fine but try out (') with the code... it just doesn't work. Can you tell me why? And how can I solve this little problem? ^^</p> <p>NOTE!: The apostrophe I want to replace does not contain the brackets. I just want to replace the apostrophe :)</p>
-5
2016-08-17T13:35:00Z
38,998,743
<p>This is very straightforward as it can be handled with replace. There is no "obvious" reason this would not work. There is an "obvious" reason you'd have an error and that is trying to call out a single quot with additional single quotes</p> <pre><code>text = "dog's toy" text.replace("'","-") ==&gt;"dog-s toy" </code></pre> <p>If you try to use single quotes like this:</p> <pre><code>replace(''') </code></pre> <p>You'd fail for any number of reasons, the most "obvious" being that you've commented out all the following code until the next time you use '''</p>
0
2016-08-17T13:55:52Z
[ "python" ]
How to replace " ' " in python?
38,998,200
<p>So I just got a quick question. I need to replace (') in python but obviously it is not working.</p> <p>This is the code I use for replaceing things in python:</p> <pre><code>with open('ID.txt','r') as f: newlines = [] for line in f.readlines(): newlines.append(line.replace('Machine',)) with open('ID.txt', 'w') as f: for line in newlines: f.write(line) </code></pre> <p>Replacing Machine works fine but try out (') with the code... it just doesn't work. Can you tell me why? And how can I solve this little problem? ^^</p> <p>NOTE!: The apostrophe I want to replace does not contain the brackets. I just want to replace the apostrophe :)</p>
-5
2016-08-17T13:35:00Z
38,998,762
<p>Here's a possible solution:</p> <pre><code>with open('ID.txt', 'r') as f: contents = f.read().replace("'", "") with open('ID.txt', 'w') as f2: f2.write(contents) </code></pre>
0
2016-08-17T13:56:48Z
[ "python" ]
How to give beta and gamma in tf.contrib.layers.batch_norm
38,998,238
<p>I'm trying to use normalization layer given by tensorflow. In that <a href="https://www.tensorflow.org/versions/r0.10/api_docs/python/contrib.layers.html#batch_norm" rel="nofollow">function</a>, there is a field to specify whether we are using beta or gamma values.</p> <blockquote> <p><strong>center:</strong> If True, subtract <code>beta</code>. If False, <code>beta</code> is ignored.</p> <p><strong>scale:</strong> If True, multiply by <code>gamma</code>. If False, <code>gamma</code> is not used. When the next layer is linear (also e.g. <code>nn.relu</code>), this can be disabled since the scaling can be done by the next layer.</p> </blockquote> <p>But there is nowhere to input <code>beta</code> and <code>gamma</code> values into the function.</p> <p>I need to know how can I input values for <code>beta</code> and <code>gamma</code>..?</p>
1
2016-08-17T13:36:25Z
38,998,456
<p>The link you provided has specified the function as <code>tf.contrib.layers.batch_norm(*args, **kwargs)</code>.</p> <p>Looks like you should be able to pass <code>beta</code> and <code>gamma</code> as <code>keyword arguments</code> or <code>**kwargs</code> like this:</p> <pre><code>tf.contrib.layers.batch_norm(beta=value, gamma=value) </code></pre>
2
2016-08-17T13:45:40Z
[ "python", "python-2.7", "tensorflow" ]
How to give beta and gamma in tf.contrib.layers.batch_norm
38,998,238
<p>I'm trying to use normalization layer given by tensorflow. In that <a href="https://www.tensorflow.org/versions/r0.10/api_docs/python/contrib.layers.html#batch_norm" rel="nofollow">function</a>, there is a field to specify whether we are using beta or gamma values.</p> <blockquote> <p><strong>center:</strong> If True, subtract <code>beta</code>. If False, <code>beta</code> is ignored.</p> <p><strong>scale:</strong> If True, multiply by <code>gamma</code>. If False, <code>gamma</code> is not used. When the next layer is linear (also e.g. <code>nn.relu</code>), this can be disabled since the scaling can be done by the next layer.</p> </blockquote> <p>But there is nowhere to input <code>beta</code> and <code>gamma</code> values into the function.</p> <p>I need to know how can I input values for <code>beta</code> and <code>gamma</code>..?</p>
1
2016-08-17T13:36:25Z
38,998,510
<p>Beta and gamma are the learnable parameters of the batch normalization layer.</p> <p>As you can see from the image below, these parameters are used to scale and shift the normalized values. The value you can pass to the <code>batch_norm</code> method, are the init value of these parameters.</p> <p><a href="http://i.stack.imgur.com/O606s.png" rel="nofollow"><img src="http://i.stack.imgur.com/O606s.png" alt="batch normalization"></a></p>
0
2016-08-17T13:47:40Z
[ "python", "python-2.7", "tensorflow" ]
Python / Django app: a wine list with filter menu. Where should the filter logic go? Frontend or Backend?
38,998,263
<p>I have created a wine list app and I am starting to question my design. First off if you look at the views.py snippet below, you see a simple solution to send all active Wine objects. But the real question is, how do I create a filter side menu? I like using views for all of the logic, but to me it seems that having a sidebar, especially with ajax would need to be quite a bit of front end code. </p> <p>Here is <a href="http://www.newegg.com/Processors-Mobile/SubCategory/ID-759?Tid=8599" rel="nofollow" title="a example at NewEgg.com">a New Egg filter example.</a></p> <p>I am looking for direction on how to create such a side filter menu using Django. Is this going to be something that is driven by the front end mainly? Can this be driven by views? Is Django Rest framework something I should check out?</p> <pre><code>def wine_list(request): wines = Wine.active.all() return render(request, 'wine/wine_list.html', {'wines': wines}) </code></pre>
0
2016-08-17T13:37:38Z
38,999,056
<p>one solution to your problem is using django forms, so your filter box will be a normal django form, user will select items from those forms then click on submit button</p> <p>in your view method you use submitted data to generate a queryset and render template for user. (check out <a href="http://django-filter.readthedocs.io" rel="nofollow">django-filters</a> module that might be helpful (this solution handles everything on server side)</p> <p>another solution is using rest - you create an api end point for wine <code>Eg /api/wines/</code>, then in website, when user chooses some filters you send a request (with jquery, ...) get new data and put them in result table, without reloading the whole page (this approach needs some client side work) - (django-filters might be helpful here too)</p> <p>based on your project requirements you can choose on of these approaches </p>
0
2016-08-17T14:10:02Z
[ "python", "django", "rest", "filter", "views" ]
Odoo Onchange method not working on many2one field
38,998,333
<p>I have written a onchange method on the many2one field using new api for v9. my code is</p> <pre><code>branch_id = fields.Many2one('branch.branch', 'Branch') @api.onchange('branch_id') def onchange_branch(self): if self.branch_id: self.shop_ids = self.branch_id.shop_ids </code></pre> <p>I have not added the on change on the xml also. when i do the change the many2one field the on change method is not getting called.</p> <p>Also On developer mode tooltip i can not see the onchange while on other filed i can see.</p> <p>Does anyone have idea what I am missing?</p>
1
2016-08-17T13:40:22Z
38,999,837
<p>I faced this kind of issue while migrating code from v7 to v9. where I was changing the methods from old api to odoo new api. that time i forgot to comment the old api method. </p> <p>May be this can be your issue.</p> <p>kindly check your for the method <code>onchange_branch</code>, if you have two method with same name or not. if yes then remove the extra method.</p>
1
2016-08-17T14:46:09Z
[ "python", "openerp", "odoo-9" ]
Odoo: How to process winmail.dat attached in conversations?
38,998,486
<p>We have some customers who uses Microsoft Outlook to send attachments. However in odoo we see only <code>winmail.dat</code> files (while everything looks ok in mail client).</p> <p>Is there any way to force odoo to expose <code>winmail.dat</code> content?</p>
2
2016-08-17T13:46:48Z
38,998,706
<p>The problem is that Microsoft Outlook uses <a href="https://en.wikipedia.org/wiki/Transport_Neutral_Encapsulation_Format" rel="nofollow">Transport Neutral Encapsulation Format</a> and packs all attachments in one file.</p> <p>There is a good python parser for tnef format - <a href="https://pypi.python.org/pypi/tnefparse" rel="nofollow"><code>tnefparse</code></a>. I'd suggest you to use it and write simple module to extend <code>mail.thread</code> model like this</p> <pre class="lang-py prettyprint-override"><code>from tnefparse import TNEF from openerp.osv import osv class MailThread(osv.Model): _inherit = 'mail.thread' def _message_extract_payload(self, message, save_original=False): body, attachments = \ super(MailThread, self)\ ._message_extract_payload(message, save_original=save_original) new_attachments = [] for name, content in attachments: new_attachments.append((name, content)) if name and name.strip().lower() in ['winmail.dat', 'win.dat']: try: winmail = TNEF(content) for attach in winmail.attachments: new_attachments.append((attach.name, attach.data)) except: # some processing here pass return body, new_attachments </code></pre> <p>You can find more information on how to do custom modules <a href="https://www.odoo.com/documentation/8.0/howtos/backend.html" rel="nofollow">here</a>.</p>
1
2016-08-17T13:54:14Z
[ "python", "openerp", "winmail.dat" ]
Differences between scipy and matlab spectogram
38,998,522
<p>I'm attempting to convert a MATLAB script to Python and running into slight differences between the results of the <code>spectrogram</code> function between MATLAB 2012a and Python using scipy v. 0.17.0. In MATLAB I have the code:</p> <pre class="lang-matlab prettyprint-override"><code>WINDOW = 240; NOVERLAP = 180; NFFT = 1024; Fs = 4; [~,F,T,PP] = spectrogram(data,hanning(WINDOW),NOVERLAP,NFFT,Fs); </code></pre> <p>where data is a one-dimensional array of about 15000 points, here PP will give the PSD for each section. </p> <p>In Python the code looks something like this:</p> <pre class="lang-py prettyprint-override"><code>from scipy.signal.spectral import spectrogram WINDOW = 240 NOVERLAP = 180 NFFT = 1024 Fs = 4 [f, ts_i, pp] = spectrogram(data, fs=Fs, window='hanning', nperseg=WINDOW, noverlap=NOVERLAP, nfft=NFFT, detrend=False) </code></pre> <p>When I compare the output (MATLAB -- Python) I get similar but not identical results. Below is an image of the first segment with the Python and MATLAB results plotted along with the absolute difference point by point. This behavior is similar for other segments. Again the differences are not large but I'm curious about what is the ultimate cause of these differences?</p> <p><a href="http://i.stack.imgur.com/e0zJT.png" rel="nofollow"><img src="http://i.stack.imgur.com/e0zJT.png" alt="enter image description here"></a></p>
0
2016-08-17T13:48:04Z
39,004,643
<p>Scipy and MATLAB use different FFT libraries. Scipy uses lapack, while MATLAB uses FFTW. These libraries use different algorithms and produce slightly different results. </p> <p>You can use FFTW with Python using the <a href="https://pypi.python.org/pypi/pyFFTW" rel="nofollow">pyFFTW</a> package, and you can even monkey-patch scipy to <a href="https://hgomersall.github.io/pyFFTW/sphinx/tutorial.html#monkey-patching-3rd-party-libraries" rel="nofollow">use FFTW</a> under-the-hood for its FFT calculations, although even then it may not give numerically-identical results since the FFTW library may be called in different ways.</p>
1
2016-08-17T19:20:01Z
[ "python", "matlab", "scipy" ]
How to read/pass a js var to python script?
38,998,541
<p>I have a .js file (test.js) with a bunch of calculations and variables. Let's just say 1 number (var1) and 1 array (var2).</p> <p>I also have a .py file (test2.py) with a bunch of stuff. Is there any way to pass (var1) and (var2) so test2.py can read it and do some more work on it?</p> <p>Is this possible? If so, what would it look like in Python?</p>
-1
2016-08-17T13:48:59Z
38,998,951
<p>You can't do this . How Python will know javascript variables ?. No language will understand the other languages memory structures . There should be some interface(agreement) to make it understand. For example , Java and C can be using JNI (Java Native Interface) .</p>
0
2016-08-17T14:05:12Z
[ "javascript", "python", "python-2.7" ]
How to read/pass a js var to python script?
38,998,541
<p>I have a .js file (test.js) with a bunch of calculations and variables. Let's just say 1 number (var1) and 1 array (var2).</p> <p>I also have a .py file (test2.py) with a bunch of stuff. Is there any way to pass (var1) and (var2) so test2.py can read it and do some more work on it?</p> <p>Is this possible? If so, what would it look like in Python?</p>
-1
2016-08-17T13:48:59Z
38,998,978
<p>You can export the variables as JSON from Javascript - how depends on which environment you run the script in (nodejs, browser, ...) - and import them in Python <a href="https://docs.python.org/2/library/json.html" rel="nofollow">docs</a>. This works the other way, too.</p>
0
2016-08-17T14:06:28Z
[ "javascript", "python", "python-2.7" ]
Insert space between characters regex
38,998,547
<p>I'm very new to regex, and i'm trying to find instances in a string where there exists a word consisting of either the letter <code>w</code> or <code>e</code> followed by 2 digits, such as <code>e77</code> <code>w10</code> etc.</p> <p>Here's the regex that I currently have, which I think finds that (correct me if i'm wrong)</p> <p><code>([e|w])\d{0,2}(\.\d{1,2})?</code></p> <p>How can I add a space right after the letter <code>e</code> or <code>w</code>? If there are no instances where the criteria is met, I would like to keep the string as is. Do I need to use re.sub? I've read a bit about that.</p> <p>Input: <code>hello e77 world</code></p> <p>Desired output: <code>hello e 77 world</code></p> <p>Thank You.</p>
-2
2016-08-17T13:49:15Z
38,998,838
<p>Your regex needs to just look like this:</p> <pre><code>([ew])(\d{2}) </code></pre> <p>if you want to only match specifically 2 digits, or</p> <pre><code>([ew])(\d{1,2}) </code></pre> <p>if you also want to match single digits like <code>e4</code></p> <p>The brackets are called capturing groups and could be <a class='doc-link' href="http://stackoverflow.com/documentation/regex/4072/back-reference#t=201608171357463222028">back referenced</a> in a search and replace, or with python, using <a href="https://docs.python.org/2/library/re.html#re.sub" rel="nofollow"><code>re.sub</code></a></p> <p>your replace string should look like</p> <pre><code>\1 \2 </code></pre> <p>So it should be as simple as a line like:</p> <pre><code>re.sub(r'([ew])(\d{1,2})', r'\1 \2', your_string) </code></pre> <p>EDIT: working code</p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; your_string = 'hello e77 world' &gt;&gt;&gt; &gt;&gt;&gt; re.sub(r'([ew])(\d{1,2})', r'\1 \2', your_string) 'hello e 77 world' </code></pre>
4
2016-08-17T13:59:45Z
[ "python", "regex" ]
Insert space between characters regex
38,998,547
<p>I'm very new to regex, and i'm trying to find instances in a string where there exists a word consisting of either the letter <code>w</code> or <code>e</code> followed by 2 digits, such as <code>e77</code> <code>w10</code> etc.</p> <p>Here's the regex that I currently have, which I think finds that (correct me if i'm wrong)</p> <p><code>([e|w])\d{0,2}(\.\d{1,2})?</code></p> <p>How can I add a space right after the letter <code>e</code> or <code>w</code>? If there are no instances where the criteria is met, I would like to keep the string as is. Do I need to use re.sub? I've read a bit about that.</p> <p>Input: <code>hello e77 world</code></p> <p>Desired output: <code>hello e 77 world</code></p> <p>Thank You.</p>
-2
2016-08-17T13:49:15Z
38,998,839
<p>This is what you're after:</p> <pre><code>import re print(re.sub(r'([ew])(\d{1,2})', r'\g&lt;1&gt; \g&lt;2&gt;', 'hello e77 world')) </code></pre>
1
2016-08-17T13:59:54Z
[ "python", "regex" ]
Pandas or Numpy, searching, editing and extracting data
38,998,836
<p>Few weeks ago I started to study python in order to write a programme,<br> at the moment I try to extract some information from a file, it looks like this:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>MAEFILE: benopga1.01.mae &amp;gen igeopt=1 iaccg=5 ip160=4 ifreq=1 ip24=2 nogas=2 iacc=1 &amp; &amp;zmat C1 18.7209160000 18.5628090000 15.2914270000 C2 17.4114700000 18.8454610000 15.7184360000 C3 17.0539910000 18.6449570000 17.0518080000 C4 18.0032320000 18.1601840000 17.9688000000 C5 19.3024250000 17.8798070000 17.5452620000 C6 19.6626680000 18.0820920000 16.2013130000 H7 18.9985910000 18.7195810000 14.2522760000 H8 16.6780090000 19.2198900000 15.0089150000 H9 16.0417370000 18.8626870000 17.3826630000 H10 17.7239350000 18.0037410000 19.0076080000 H11 20.0369730000 17.5051670000 18.2535010000 H12 20.6751990000 17.8633650000 15.8718730000 &amp; &amp;guess basgss=6-311g**+ numd=5 1 Orbital Energy -11.241317 Occupation 1.000000 -0.237515017757232 -0.196647289792153 -0.000012299229451 0.000012283693667 -0.000038832391585 -0.002068759436403 0.000019096186058 0.000035102037517 -0.000178850142376 0.000386718554923 0.000028243495837 -0.000010189167830 0.000009719189111 -0.000083379603107 0.000088703347921 -0.000005323744814 0.000074406344067 -0.000034780134268 0.000042134744869 -0.000025018268285 0.000005796046950 0.000032438198590 -0.000151512252705 -0.198843760947433 -0.164626268788198 -0.000032620645254 0.000011142490285 -0.000007071762982 -0.001751134173474 -0.000117771869441 0.000056795470271 -0.000099889624378 0.000355125910896 0.000016162939390 -0.000000591018861 -0.000018504072314 -0.000043258886307 0.000085387104771 -0.000042128218464 0.000032711718420 0.000062742388095 0.000018426112961 -0.000001087454691 -0.000087393288567 0.000036394574524 -0.000046738022296 -0.189838829586922 -0.157171079929277 -0.000027575467355 0.000006987237905 0.000003880133365 -0.001671553419738 -0.000145911512315 0.000031184688524 0.000049574180168 0.000356303208123 0.000008457559748 -0.000002555314618 0.000000156292819 0.000001781216751 0.000074959304234 -0.000076740520986 0.000034291328716 -0.000015539635327 0.000048978495218 0.000007568809345 -0.000078160169234 0.000017433925123 0.000021965260595 -0.206688115052246 -0.171120694083044 -0.000024613036749 0.000000578071180 0.000028857510870 -0.001816148417123 -0.000060499311777 -0.000017129060142 0.000151731576240 0.000366295601898 0.000027273496960 -0.000008681030719 0.000003505182219 -0.000084713189897 0.000079444547592 0.000005268642305 0.000061929650436 -0.000000945876945 0.000025397622782 -0.000006331576449 -0.000059596946982 -0.000005577539402 0.000100798841928 -0.249803952550950 -0.206823550176572 0.000003194386460 -0.000011257593014 0.000044548734829 -0.002165674347528 0.000119312075990 -0.000063891648135 0.000128577103429 0.000383381470817 0.000015141171971 0.000000035916246 -0.000018789517620 -0.000044930372579 0.000110215751912 -0.000065285379334 0.000039159765842 0.000078659142665 0.000027379751909 -0.000029883760840 0.000089805971123 -0.000055471940289 0.000127658675297 -0.282967668103962 -0.234291216881311 0.000022041761553 -0.000002823143502 -0.000015098289029 -0.002411282844625 0.000189683107712 -0.000041945582722 -0.000057757033880 0.000410957267636 -0.000018584696026 0.000002703022996 0.000011405600689 -0.000005600032267 0.000119091011558 -0.000113490979291 0.000058095889213 -0.000027269439738 0.000076776523871 -0.000039022163445 0.000173859295776 -0.000036395429255 -0.000059944178961 -0.000180764515503 0.000007292236479 -0.000211164361974 0.000002900643801 0.000006787640262 -0.000032874030369 -0.000152282839545 0.000001347403058 -0.000192590475337 -0.000022257991946 0.000010326038114 -0.000016900157341 -0.000145389069678 0.000002334090915 -0.000184253055893 -0.000026241454432 0.000005721872839 0.000008503996611 -0.000157846225852 0.000005719915333 -0.000197522897687 -0.000012294624010 -0.000002547402448 0.000026305673479 -0.000190277091678 0.000012467113833 -0.000218567465104 0.000019225415536 -0.000011030299816 0.000023682450623 -0.000214624610593 0.000020667490110 -0.000229289099730 0.000031900177357 -0.000006901099326 -0.000010189424947 ------- 31 Orbital Energy 0.152723 Occupation 0.000000 -0.000001484697707 -0.000002021678521 -0.011269736987441 -0.038830417095759 -0.008858615646339 0.000001192390365 -0.006923508623065 -0.023842815223962 -0.005418954995446 0.000041590787919 -0.067391763573696 -0.232026052460321 -0.052998414149352 0.001793328350150 0.000775609630928 -0.002568937981078 0.003688605910249 -0.001068780674560 -0.006386930085737 -0.000062943108962 0.199687105918283 0.687684976534009 0.156868067056184 0.000000096154362 0.000000657329257 -0.011210137098576 -0.038624144508054 -0.008813875928149 -0.000002083821188 -0.006889998263354 -0.023739788458030 -0.005413447465109 -0.000018259645012 -0.066955664071598 -0.230792413990635 -0.052580672751758 -0.003071293835289 0.004370602232574 -0.001299308397285 -0.005372985400140 -0.002350939654665 -0.002706808510529 -0.000070970422528 0.198318280915318 0.683514266154416 0.155894609381509 0.000000339923235 0.000001176339340 0.000304981657499 0.001042477771998 0.000239760902136 -0.000010467863819 0.000544040658142 0.001845662740944 0.000423422866543 0.000056642800415 0.000984897727369 0.003286180141148 0.000798961685623 0.000314520592607 -0.001550492509766 0.001235971917159 0.000362328854063 0.001051946495198 0.002924677897963 0.000052446885436 0.007592738586630 0.027102621203117 0.006457030833373 -0.000001674148274 -0.000002569702830 0.011036680737231 0.038036534353212 0.008683871836959 0.000011681514030 0.006437710430541 0.022161408213113 0.005042525696551 -0.000073456543616 0.066825871686029 0.230182549919537 0.052602199705660 0.001619905567722 0.001073249176964 -0.002693154744685 0.003395235925365 -0.001233638134137 -0.006656299269408 -0.000031022957851 -0.208382824428751 -0.718837764254747 -0.164641719576342 0.000002139554361 0.000004317465847 0.010966267617752 0.037792975401876 0.008624771875724 -0.000011263540804 0.006373597174822 0.021999897758008 0.005010930775777 -0.000012041105775 0.066365092028384 0.228809219195351 0.052127667273958 -0.003005259795779 0.004486267413809 -0.001481007618030 -0.005217612687906 -0.002459044682008 -0.003155753438819 0.000122889172923 -0.207289443420419 -0.714788889584271 -0.162678954342172 -0.000001113015636 -0.000001539233415 0.000173647770863 0.000591026047632 0.000138309282669 0.000001767411845 0.000457220121974 0.001573303489084 0.000360204439751 0.000025047915999 0.000170009010859 0.000615396416029 0.000093891319707 0.000532222151981 -0.001708952612925 0.001176730460945 0.000768838272606 0.001104781032426 0.002758844326405 -0.000048320919224 0.010021022901790 0.035244457521757 0.007959417545553 -0.000000432884305 0.000043865349832 -0.000082946240504 0.001226683058023 0.004222389372921 0.000970314215579 -0.000002541300496 0.000035298825687 0.000101681117207 0.001224755470991 0.004192362461791 0.000964887073715 -0.000004352857236 0.000035780410422 -0.000112972423150 0.000059020531435 0.000208544008111 0.000046874782483 0.000000639601687 0.000054054494787 0.000026791342731 -0.001291902546627 -0.004454899976684 -0.001026504045236 -0.000006323623792 0.000071261955447 -0.000128521753658 -0.001293454307352 -0.004429301733713 -0.001017753159295 -0.000001046054621 0.000011841859973 0.000073751920645 0.000075884640401 0.000259775657980 0.000060453277266 &amp; &amp;hess 1 1 5.357113E-01 2 -1.203890E-01 2.050867E-01 3 -5.072856E-02 -1.224648E-01 7.247686E-01 4 -2.738767E-01 5.421034E-02 8.516300E-02 6.687076E-01 5 5.862978E-02 -7.841398E-02 -6.986702E-03 -1.530589E-01 2.102981E-01 6 -4.882459E-02 2.176720E-02 -1.508757E-01 3.490960E-02 -1.293015E-01 7 1.397183E-02 -6.213820E-03 3.526196E-02 -1.359815E-01 3.130492E-03 8 -2.648252E-02 1.165820E-02 -6.485242E-03 1.013400E-02 -7.653658E-02 9 1.679309E-01 -3.235383E-02 4.798621E-03 6.244518E-03 5.348205E-02 10 -1.499543E-01 3.053092E-02 -2.007584E-02 7.869050E-02 -3.394869E-03 11 3.073586E-02 -1.093993E-02 1.498358E-03 -6.620322E-03 4.623322E-03 12 -2.113264E-02 1.886220E-03 -3.178300E-03 -1.128905E-02 1.402985E-02 13 1.358396E-01 -2.272879E-02 -9.113526E-03 -6.181379E-02 2.549849E-04 14 -3.477661E-03 4.127380E-03 1.454523E-02 -3.514229E-04 -6.286993E-03 15 -7.888047E-02 2.021552E-02 -3.514837E-02 1.840733E-02 -2.058056E-03 16 -2.177345E-01 7.626153E-02 -1.207416E-01 -3.647403E-02 1.587059E-02 17 5.247322E-02 -1.002916E-01 7.246352E-02 1.945406E-02 2.204342E-03 18 2.208958E-02 4.326027E-02 -2.152098E-01 -7.205723E-02 3.178738E-03 19 -7.725080E-02 -4.733359E-03 7.169356E-02 -1.952258E-03 -5.265493E-03 20 -4.463521E-03 -4.582251E-02 4.403138E-02 1.752013E-03 3.237253E-03 21 7.086791E-02 4.407103E-02 -3.203331E-01 -1.998051E-03 2.097618E-03 22 -1.287577E-02 9.327437E-03 -2.157959E-02 -1.881858E-01 7.230259E-02 23 2.190754E-03 3.617602E-04 4.639266E-03 7.195528E-02 -7.350281E-02 24 8.569006E-03 -4.185411E-03 9.161599E-03 -1.241089E-01 6.861581E-02 25 2.378996E-03 8.676100E-04 2.416760E-03 -4.030590E-03 2.507893E-03 26 8.991614E-04 6.328556E-03 2.086578E-03 -4.549598E-03 4.186961E-03 27 1.667829E-03 2.414920E-03 -5.566737E-03 2.914902E-02 -6.879962E-03 28 -1.480521E-03 2.999713E-04 -7.027812E-04 -1.782413E-03 3.221656E-03 29 4.484685E-04 -7.341012E-04 -1.860347E-05 3.571517E-03 5.682207E-03 30 -7.047879E-04 -1.896539E-04 1.144798E-03 -3.791107E-03 2.806446E-03 31 1.967935E-03 1.052172E-03 2.249519E-03 -1.359768E-04 -4.909666E-04 32 9.264046E-04 6.619953E-03 2.006525E-03 -5.334520E-04 -4.168043E-04 33 2.639645E-03 1.762322E-03 -4.896901E-03 1.372681E-03 -4.518228E-04 34 -1.417455E-02 2.727599E-03 1.044303E-02 -1.172401E-03 3.258573E-03 35 9.736697E-03 1.617405E-03 -4.499427E-03 3.110862E-03 5.445966E-03 36 -2.049141E-02 4.551847E-03 9.548502E-03 -3.059820E-03 2.777782E-03 6 6 6.148960E-01 7 9.694602E-02 6.987643E-01 8 2.440824E-02 -1.503817E-01 2.054470E-01 9 -2.512768E-01 -7.243872E-02 -8.990523E-02 5.654096E-01 10 -1.333717E-01 -2.054959E-01 4.717798E-02 3.344556E-02 5.490687E-01 11 3.904594E-02 7.187216E-02 -9.645819E-02 3.823231E-02 -1.192375E-01 12 -5.054405E-02 -1.138194E-01 6.829035E-02 -2.021683E-01 -6.795284E-02 13 1.102332E-01 -5.969411E-02 3.723179E-02 -1.236615E-01 -2.349015E-01 14 -3.853905E-03 1.553892E-02 2.601743E-03 3.184075E-03 6.357285E-02 15 -6.782885E-02 -6.726040E-03 -5.407333E-03 8.467873E-02 1.300986E-02 16 3.943401E-03 -4.511242E-03 1.382113E-03 -2.390661E-02 1.119908E-02 17 -2.094158E-02 1.540967E-03 -9.168102E-03 2.639755E-02 -2.632153E-02 18 1.416749E-01 -2.532995E-02 2.683847E-02 -1.501283E-01 1.674068E-01 19 2.808227E-02 -4.818105E-03 3.094910E-03 2.058231E-03 -1.745043E-03 20 -6.667732E-03 2.870215E-03 6.262360E-03 5.683060E-04 4.427648E-04 21 -5.175332E-03 2.554751E-03 4.579300E-04 1.979747E-03 -7.062836E-04 22 -1.247529E-01 8.258119E-03 -3.432272E-03 8.252649E-03 2.144433E-03 23 6.881531E-02 3.750150E-03 1.833843E-03 1.047128E-03 4.236422E-04 24 -1.804521E-01 -2.291255E-02 1.036880E-02 -1.292029E-02 3.004725E-03 25 -1.907067E-03 -3.063512E-01 5.888514E-02 8.248172E-02 -1.394043E-02 26 2.208861E-03 5.925325E-02 -5.117732E-02 -1.285134E-02 9.154041E-03 27 -3.215292E-03 8.194643E-02 -1.255761E-02 -8.551740E-02 -1.995845E-02 28 -3.296838E-03 9.060765E-03 2.748152E-03 -2.084458E-02 -7.728528E-02 29 2.687659E-03 -4.066922E-03 1.111791E-03 9.587301E-03 -4.752476E-03 30 -7.099807E-04 8.960116E-03 1.031423E-03 -1.388900E-02 7.175752E-02 31 1.691020E-03 -4.691846E-03 2.565325E-03 3.394495E-03 -1.317085E-02 32 -4.306708E-04 2.862186E-03 6.076609E-03 2.204974E-04 2.751124E-03 33 -5.486880E-04 2.398883E-03 4.941632E-04 1.520535E-03 8.765089E-03 34 -3.900191E-03 1.185306E-03 -4.557608E-04 -8.504399E-04 2.324262E-03 35 3.027231E-03 -4.660645E-04 -6.058911E-04 5.406380E-04 1.162152E-03 36 -1.076955E-03 -6.065414E-04 3.749918E-04 -1.651439E-03 1.559582E-03 11 11 2.036463E-01 12 -1.172782E-01 7.186272E-01 13 3.836605E-02 9.833300E-02 6.189527E-01 14 -8.124822E-02 -7.237159E-03 -1.586210E-01 2.107532E-01 15 2.604649E-03 -1.440396E-01 4.110175E-02 -1.227296E-01 6.810652E-01 16 -4.998799E-03 3.558635E-02 -1.517975E-01 2.806294E-03 7.703362E-02 17 1.156440E-02 -7.570831E-03 2.908585E-02 -7.398307E-02 3.881048E-02 18 -3.234759E-02 6.717726E-03 -5.807469E-02 4.951787E-02 -2.832498E-01 19 3.589195E-04 -4.708646E-04 -1.402206E-03 3.220279E-03 -3.065811E-03 20 -6.839957E-04 -2.250234E-04 3.431037E-03 5.450787E-03 2.657729E-03 21 -2.501729E-04 1.105759E-03 -3.591744E-03 2.836891E-03 -9.231576E-04 22 9.591988E-04 2.154412E-03 -1.186699E-03 -4.080684E-04 1.491628E-03 23 6.348418E-03 2.082719E-03 -5.469945E-05 -4.309774E-04 -5.945081E-04 24 1.834672E-03 -5.234314E-03 1.275562E-03 -5.273805E-04 -1.623391E-04 25 2.339952E-03 1.011159E-02 -6.364443E-04 3.209197E-03 -3.830418E-03 26 5.936686E-04 -4.692742E-03 3.085246E-03 5.692126E-03 3.099157E-03 27 4.112008E-03 9.641439E-03 -3.333572E-03 2.835538E-03 -1.490121E-03 28 -4.639572E-03 7.112198E-02 -2.059962E-03 -5.057039E-03 2.904566E-02 29 -4.581722E-02 4.419494E-02 2.063191E-03 4.243199E-03 -6.499605E-03 30 4.385196E-02 -3.204086E-01 -1.279372E-03 2.454236E-03 -5.470362E-03 31 9.879408E-03 -2.202778E-02 -1.887970E-01 7.219524E-02 -1.241630E-01 32 1.443492E-03 5.036378E-03 7.235257E-02 -7.357053E-02 6.847109E-02 33 -4.034273E-03 8.875759E-03 -1.249539E-01 6.886918E-02 -1.800114E-01 34 9.205108E-04 2.151887E-03 -3.251011E-03 2.100621E-03 -1.955914E-03 35 6.472624E-03 2.166082E-03 -4.961588E-03 3.187735E-03 1.801821E-03 36 2.475965E-03 -5.392252E-03 2.780805E-02 -7.027603E-03 -3.239105E-03 16 16 7.058893E-01 17 -1.554764E-01 2.072989E-01 18 -5.616458E-02 -9.217960E-02 5.520851E-01 19 8.981009E-03 3.289528E-03 -2.141664E-02 7.626286E-02 20 -3.842831E-03 2.156460E-03 1.000977E-02 2.846781E-03 3.642322E-02 21 9.319906E-03 1.309879E-03 -1.410448E-02 -7.646282E-02 -4.860829E-02 22 -4.402991E-03 2.531367E-03 3.289913E-03 9.021696E-04 -1.251841E-03 23 2.725604E-03 6.274671E-03 1.628016E-04 -1.156805E-03 -3.268124E-03 24 2.537554E-03 5.855487E-04 1.563713E-03 -7.394921E-04 -6.175566E-04 25 1.026188E-03 -3.997980E-04 -7.437612E-04 -2.657211E-04 1.335569E-04 26 -2.275656E-04 -6.403373E-04 4.661607E-04 -2.089260E-04 2.334557E-04 27 -8.333180E-04 4.056932E-04 -1.539848E-03 1.552873E-03 -2.872954E-04 28 -4.991017E-03 2.960965E-03 2.222760E-03 -2.021511E-05 -3.472167E-04 29 2.739691E-03 6.103553E-03 3.149083E-04 -3.757001E-04 -1.056348E-03 30 2.773596E-03 4.162969E-04 2.059696E-03 1.871311E-05 -1.472036E-04 31 8.389904E-03 -3.707522E-03 7.624896E-03 3.256189E-04 -1.070285E-04 32 3.342920E-03 8.529872E-04 1.309502E-03 2.234428E-04 9.689788E-05 33 -2.246703E-02 9.836860E-03 -1.293489E-02 -1.083503E-03 6.089104E-04 34 -3.062399E-01 5.922308E-02 8.165886E-02 5.042012E-04 -1.375289E-03 35 5.927026E-02 -5.126865E-02 -1.257008E-02 -1.443801E-03 -3.563906E-03 36 8.262465E-02 -1.283576E-02 -8.543201E-02 3.426350E-04 -1.115803E-03 21 21 3.374350E-01 22 -2.145991E-04 1.952296E-01 23 -7.899096E-04 -7.886814E-02 6.658415E-02 24 2.434416E-04 1.327314E-01 -7.490323E-02 1.874819E-01 25 -1.504871E-04 1.714452E-04 -1.179780E-03 -2.325636E-04 3.220066E-01 26 1.568302E-04 -1.102295E-03 -3.573059E-03 -1.099444E-03 -6.529751E-02 27 -3.836369E-04 -5.860705E-04 -8.976903E-04 1.021072E-03 -8.867881E-02 28 1.218173E-05 3.024906E-04 2.516389E-04 -1.141836E-03 4.239541E-04 29 -1.441930E-04 -1.026389E-04 8.840927E-05 6.332547E-04 -1.291296E-03 30 -1.374519E-04 3.812079E-04 2.389330E-04 -8.747765E-04 -1.502824E-04 31 3.851771E-04 -1.639111E-04 -1.356532E-04 -3.111450E-04 -7.902321E-04 32 1.182647E-04 -2.347572E-04 -1.084055E-03 -1.576438E-04 2.115227E-04 33 -7.593839E-04 -1.667396E-04 -1.008961E-04 -1.123286E-05 5.825404E-04 34 -2.035376E-04 -8.011347E-04 3.153121E-04 4.611029E-04 -1.316073E-04 35 -9.809362E-04 5.440663E-04 6.513052E-05 -1.662642E-04 -2.997207E-04 36 5.655858E-04 -1.044500E-03 2.754315E-04 3.638921E-04 5.800512E-05 26 26 4.236930E-02 27 1.211680E-02 8.569162E-02 28 -1.245167E-03 5.853340E-04 7.688814E-02 29 -3.211526E-03 -1.073037E-03 3.035872E-03 3.637004E-02 30 -9.073261E-04 5.569719E-04 -7.721346E-02 -4.840140E-02 3.370049E-01 31 5.516888E-04 -1.052577E-03 7.862359E-04 -1.339463E-03 -2.253878E-04 32 8.382047E-05 2.822024E-04 -1.251478E-03 -3.643525E-03 -9.503755E-04 33 -1.807402E-04 3.462591E-04 -6.238417E-04 -7.053561E-04 3.763429E-04 34 -3.067637E-04 5.290655E-05 -2.494180E-04 1.374706E-04 -1.399704E-04 35 -1.022331E-03 -2.811845E-04 -2.047648E-04 2.343184E-04 1.575352E-04 36 -2.816129E-04 2.140399E-05 1.520584E-03 -2.731030E-04 -3.847069E-04 31 31 1.959794E-01 32 -7.942207E-02 6.628383E-02 33 1.329428E-01 -7.483048E-02 1.873301E-01 34 1.308904E-04 -1.106336E-03 -1.028018E-04 3.222324E-01 35 -9.751806E-04 -3.283255E-03 -1.006349E-03 -6.565566E-02 4.251950E-02 36 -6.224509E-04 -9.048575E-04 1.125719E-03 -8.805915E-02 1.207815E-02 36 36 8.527950E-02 &amp;</code></pre> </div> </div> </p> <p>I did try to use pandas to look through the file and the extract in a separated file, what is bellow &amp;zmat. I mean lines C1 to H12 </p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>import os import pandas import numpy os.chdir ("D:\\Ubuntu\downloads") dt =pandas.read_fwf ("ga1.01.in", header =None, sep = '\s+')</code></pre> </div> </div> </p> <p>Unfortunately pandas only see two columns and I can not got further.<br> I plan to do the same for the lines bellow &amp;hess. Which is the lower par of a symmetric matrix.</p> <pre><code>http://i.stack.imgur.com/u05ZE.png </code></pre> <p>In this case 36x36, but it is saved by 5 columns, while the rows are enumerated. I still working in a solution once I am able to extract that part, I assume that pandas is a good election for that issue. if someone can give me a idea where to start , I would appreciate ane help.</p> <p>Thanks</p>
1
2016-08-17T13:59:39Z
39,000,690
<p>Try using this line for reading lines C1 to H11 with options to skip first 11 rows, read 12 lines and specify the extents of fixed-width fields of each line.</p> <pre><code>dt =pandas.read_fwf ("ga1.01.in", header =None, skiprows=11, nrows=12, colspecs=[(0,5), (12,35), (36,61),(62,91)]) </code></pre>
0
2016-08-17T15:26:37Z
[ "python", "pandas", "numpy", "scipy", "full-text-search" ]
How can I record a sound and play it back after a user-defined delay in Python?
38,998,920
<p>I'm looking for a Python's code that would record a sound and play it back after a certain delay (for example 10 seconds). In other words, I would like to constantly hear (on my headphones) what's going on outside, but with a certain delay.</p> <p>I found a Python script on GitHub (<a href="https://gist.github.com/larsyencken/5641402" rel="nofollow">https://gist.github.com/larsyencken/5641402</a>) that is supposed to do what I'm looking for. However, when I run the script, the playing starts after 5 seconds (default delay), but it records everything around and plays it in real time (without any delay).</p>
-2
2016-08-17T14:03:43Z
39,231,229
<p>Here is an example using <code>sounddevice</code> , although you can do it using other <code>audio/sound</code> modules as well.</p> <p>Below example records audio from microphone for <code>#seconds</code> as per variable <code>duration</code> which you can modify as per your requirements. Same contents are played back using standard audio output (speakers). More on this <a href="http://python-sounddevice.readthedocs.io/en/0.3.4/" rel="nofollow">here</a></p> <p><strong>Working Code</strong></p> <pre><code>import sounddevice as sd import numpy as np import scipy.io.wavfile as wav fs=44100 duration = 10 # seconds myrecording = sd.rec(duration * fs, samplerate=fs, channels=2, dtype='float64') print "Recording Audio for %s seconds" %(duration) sd.wait() print "Audio recording complete , Playing recorded Audio" sd.play(myrecording, fs) sd.wait() print "Play Audio Complete" </code></pre> <p><strong>Output</strong></p> <pre><code>Python 2.7.9 (default, Dec 10 2014, 12:24:55) [MSC v.1500 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. &gt;&gt;&gt; ================================ RESTART ================================ &gt;&gt;&gt; Recording Audio for 10 seconds Audio recording complete , Playing recorded Audio Play Audio Complete &gt;&gt;&gt; </code></pre>
1
2016-08-30T15:12:56Z
[ "python", "audio", "wav", "wave", "pyaudio" ]
Send value of variable that is in a loop from one script to another script
38,998,988
<p>I've been fiddling with sending a variable from one script to another and have done some basic things pretty easily, but I have gotten stuck and was hoping to get some input.</p> <p>This is my script1.py</p> <pre><code>import time x = 0 while x &lt; 100: x = x+1 time.sleep(1) </code></pre> <p>This is my script2.py</p> <pre><code>import subprocess subprocess.Popen("python script1.py", shell=True) from script1 import x print(x) </code></pre> <p>The output of this is just 100.</p> <p>Is there a way to print the variable <code>x</code> every time it gets updated through script2.py?</p> <p>The reason for all of this is I am reading data from a serial port in a script but I want to use the output in a different script whenever it comes in. So essentially, whenever there is data available from the serial port stored in a variable I want that variable passed to another script.</p> <p>EDIT: I have a python script where it script reads data from one serial port and logs the data.</p> <p>With that being said, I want a second script that can take the list containing the data from the first script in order to manipulate it for a different task.</p> <p>EDIT 2: I have modified the code as follows, but nothing prints. </p> <pre><code>#script 1 import time x = 0 while x &lt; 100: x = x+1 print(x) time.sleep(1) #script 2 import subprocess proc = subprocess.Popen(['python','script1.py'],stdout=subprocess.PIPE) while True: line = proc.stdout.readline() print(line) </code></pre>
0
2016-08-17T14:06:45Z
38,999,199
<p>main.py</p> <pre><code>from subprocess import Popen, PIPE import sys p = Popen(['py', 'client.py'], stdout=PIPE) while True: o = p.stdout.read(1) if o: sys.stdout.write(o.decode('utf-8')) sys.stdout.flush() print '*' else: break </code></pre> <p>client.py</p> <pre><code>import time for a in xrange(3): time.sleep(a) print a </code></pre> <p>OUT:</p> <pre><code>0* * * 1* * * 2* * * </code></pre>
0
2016-08-17T14:15:54Z
[ "python" ]
Send value of variable that is in a loop from one script to another script
38,998,988
<p>I've been fiddling with sending a variable from one script to another and have done some basic things pretty easily, but I have gotten stuck and was hoping to get some input.</p> <p>This is my script1.py</p> <pre><code>import time x = 0 while x &lt; 100: x = x+1 time.sleep(1) </code></pre> <p>This is my script2.py</p> <pre><code>import subprocess subprocess.Popen("python script1.py", shell=True) from script1 import x print(x) </code></pre> <p>The output of this is just 100.</p> <p>Is there a way to print the variable <code>x</code> every time it gets updated through script2.py?</p> <p>The reason for all of this is I am reading data from a serial port in a script but I want to use the output in a different script whenever it comes in. So essentially, whenever there is data available from the serial port stored in a variable I want that variable passed to another script.</p> <p>EDIT: I have a python script where it script reads data from one serial port and logs the data.</p> <p>With that being said, I want a second script that can take the list containing the data from the first script in order to manipulate it for a different task.</p> <p>EDIT 2: I have modified the code as follows, but nothing prints. </p> <pre><code>#script 1 import time x = 0 while x &lt; 100: x = x+1 print(x) time.sleep(1) #script 2 import subprocess proc = subprocess.Popen(['python','script1.py'],stdout=subprocess.PIPE) while True: line = proc.stdout.readline() print(line) </code></pre>
0
2016-08-17T14:06:45Z
39,005,070
<p>I finally got it to work. Thanks to going back and forth with Vadim, I was able to learn how some of this stuff works. Below is what my code is.</p> <p>script1.py:</p> <pre><code>import sys, time x=0 while x&lt;10: print(x) sys.stdout.flush() x = x+1 time.sleep(1) </code></pre> <p>script2.py:</p> <pre><code>import subprocess proc = subprocess.Popen('python script1.py', shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, ) while True: output = proc.stdout.readline() if output == '': break else: print output.rstrip() </code></pre> <p>Output:</p> <pre><code>0 #waits one second 1 #waits one second 2 #waits one second . . . 8 #waits one second 9 #waits one second </code></pre>
0
2016-08-17T19:45:49Z
[ "python" ]
Doing combination of row entries in python
38,998,997
<p>I have a csv with data similar to </p> <pre><code>a,b b,c c,d </code></pre> <p>I am working on a script which does combination (math) operation on this list taking input from each row and printing it to stdout. like below</p> <pre><code>a,b;b,c a,b;c,d b,c;c,d </code></pre> <p>Here is what I am trying:</p> <pre><code>import sys from itertools import combinations with open('d.csv', 'rb') as csvfile: opencsv = csv.reader(csvfile, delimiter=' ', quotechar='|') for row in opencsv: result = ', '.join(row) print type(result) combine = combinations([row], 4) print combine for i in list(combine): print i </code></pre> <p>I dont want the reverse occurance of the combination like, <code>a,b;b,c</code> and <code>b,c;a,b</code> in the output. I was following the steps written here (<a href="http://www.geeksforgeeks.org/permutation-and-combination-in-python/" rel="nofollow">http://www.geeksforgeeks.org/permutation-and-combination-in-python/</a>) but I think it only works if the list have single entries and not double. </p> <p>Can someone help me with this. Thank you.</p>
0
2016-08-17T14:07:14Z
38,999,425
<p>Try below. Why are you doing this result thing ? </p> <pre><code>import csv import sys import sys from itertools import combinations f = open("d.csv", 'rt') reader = csv.reader(f) for row in reader: combine = combinations(row, 2) for i in list(combine): print i </code></pre>
0
2016-08-17T14:26:58Z
[ "python", "csv" ]
Doing combination of row entries in python
38,998,997
<p>I have a csv with data similar to </p> <pre><code>a,b b,c c,d </code></pre> <p>I am working on a script which does combination (math) operation on this list taking input from each row and printing it to stdout. like below</p> <pre><code>a,b;b,c a,b;c,d b,c;c,d </code></pre> <p>Here is what I am trying:</p> <pre><code>import sys from itertools import combinations with open('d.csv', 'rb') as csvfile: opencsv = csv.reader(csvfile, delimiter=' ', quotechar='|') for row in opencsv: result = ', '.join(row) print type(result) combine = combinations([row], 4) print combine for i in list(combine): print i </code></pre> <p>I dont want the reverse occurance of the combination like, <code>a,b;b,c</code> and <code>b,c;a,b</code> in the output. I was following the steps written here (<a href="http://www.geeksforgeeks.org/permutation-and-combination-in-python/" rel="nofollow">http://www.geeksforgeeks.org/permutation-and-combination-in-python/</a>) but I think it only works if the list have single entries and not double. </p> <p>Can someone help me with this. Thank you.</p>
0
2016-08-17T14:07:14Z
39,001,108
<p>You are trying to do three different things all at once. Because you have having trouble, it follows that you should split them up into separate tasks, and figure out each part.</p> <p>First, you want to read the csv file in an unusual way. Second, you want to take combinations. Third, you want to print each combination in an unusual way.</p> <p>I think that your combinations are working fine, but you are not getting the inputs to it that you expected. In order to get the combinations you say you want from the input file you showed, I do not understand why you are using a space as the delimiter. You showed the full row being taken as one string, therefore I think you want delimiter='\n'. Because you then want to take combinations of those rows, I don't think you want them nested inside another list, so I just took row[0] for each row, which is already exactly 1 item, due to the delimiter of '\n'. At this point, I don't know if you need to check for len(row) or handle an exception, but it might not be an issue anyway. I'll leave error handling to you.</p> <p>Having set up the input, we get something nice from combinations, and then it's easy to convert to the desired output with string.join(';')</p> <pre><code>import sys import csv import string from itertools import combinations def get_rows(filename): with open(filename) as f: # may need to check or catch index out of range return [row[0] for row in csv.reader(f, delimiter='\n')] def get_pairs(rows): return [c for c in combinations(rows, 2)] def print_combinations(list_of_combinations): for c in list_of_combinations: print string.join(c, sep=';') print_combinations(get_pairs(get_rows('d.csv'))) </code></pre>
0
2016-08-17T15:48:11Z
[ "python", "csv" ]
Incremental Door Pass Riddle - Only Square Positions Open
38,999,011
<p>There are hundred doors, all closed to start with, a robot makes 100 passes, such that on every pass it increments by the next starting token. Thus,</p> <pre><code>1, 2, 3,..... 2, 4, 6, 8,.... 3, 6, 9, 11,.... 4, 8, 12, 16,.... ....... 100 </code></pre> <p>Every time it visits a door it switches from its current state, thus closes if it was open and opens if it was closed. After 100 passes find the number of doors that are open.</p> <p>The problem is trivial, here's my solution,</p> <pre><code>def door_traversal(): arr = [] arr = [0 for i in range(101)] for i in range(1, 101, 1): for j in range(i, 101, i): arr[j] = not arr[j] count = 0 for i in range(1, 101, 1): if arr[i] == 1: count += 1 return count </code></pre> <p>The answer is 10 and on checking how do I get this number 10, it seems all the door indices which are perfect square are open.Thus the open doors are</p> <pre><code>1,4,9..... </code></pre> <p>What I've been trying to understand is the math behind, this. Any help with that?</p>
0
2016-08-17T14:07:38Z
38,999,044
<p>Factorize the numbers - each factor indicates the 'pass' through which the door is open/closed. Square numbers have odd numbers of factors (9 = 1,3 [twice],9). Everything else has an even number of factors</p>
4
2016-08-17T14:09:28Z
[ "python", "math" ]
execute a python script in django webpage
38,999,015
<p>I have a python script which process text, i want to create webpages with django and then django call the python script to execute it.</p> <p>Here an Example for my case:</p> <p>There is an input text in the web page, when we click in the button, the script take the input text, process it and return the result in the web page.</p> <p>How can i perform this task?</p>
-2
2016-08-17T14:07:49Z
38,999,236
<ol> <li><p>Create a form with a text input, like this:</p> <pre><code>&lt;form action="{% url "hello" %}" method="post"&gt; {% csrf_token %} &lt;input name="hiya"&gt; &lt;input type="submit"&gt; &lt;/form&gt; </code></pre></li> <li><p>Route the <code>hello</code> URL in <code>urls.py</code>:</p> <pre><code>from . import views urlpatterns = [ # ... url(r'^blabla$', views.whatever, name='hello'), ] </code></pre></li> <li><p>In your <code>views.py</code> file, create the needed view:</p> <pre><code>def whatever(request): if request.method == 'POST': import subprocess output = subprocess.check_output(["script.py", "--", request.POST['hiya']) return HttpResponse(output, content_type='text/plain') </code></pre></li> </ol> <p>You probably do not want to do this however. It is much more efficient to call a library function that to create an entire new process, and much easier too in general. Django also has niceties that makes doing anything less than a trivial form nicer, I would recommend reading the Django tutorial to understand them.</p>
4
2016-08-17T14:17:43Z
[ "python", "django", "django-views" ]
Second matplotlib x-axis related to the first one : wrong tick position
38,999,021
<p>I would like to add a second x-axis to a matplotlib plot, not to add a second plot, but to add labels linked to the first axis. The answers in this <a href="http://stackoverflow.com/questions/10514315/how-to-add-a-second-x-axis-in-matplotlib">question</a> somehow fail to adress a problem in the bounds of the second axis :</p> <p>The following code plot the log10 of the first x-axis as a second axis :</p> <pre><code>import numpy as np import matplotlib.pyplot as plt fig = plt.figure(3,figsize = [5,4]) ax1 = fig.add_subplot(111) ax1.set_xlabel('first axis') ax1.set_xlim([0, 120]) ax1.grid(True) ax2 = ax1.twiny() ax2.set_xlim(ax1.get_xlim()) # or alternatively : # ax2.set_xbound(ax1.get_xbound()) second_ticks = np.array([1.,10.,100.]) ax2.set_xticks(second_ticks) ax2.set_xticklabels(np.log10(second_ticks)) ax2.set_xlabel('second axis') plt.show() </code></pre> <p><a href="http://i.stack.imgur.com/FQAYe.png" rel="nofollow"><img src="http://i.stack.imgur.com/FQAYe.png" alt="enter image description here"></a></p> <p>It works ! Now let's change <code>ax1.set_xlim([0, 120])</code> by <code>ax1.set_xlim([20, 120])</code></p> <p><a href="http://i.stack.imgur.com/uIWgV.png" rel="nofollow"><img src="http://i.stack.imgur.com/uIWgV.png" alt="enter image description here"></a></p> <p>Now it fails. I tried with <code>ax2.set_xbound(ax1.get_xbound())</code> with no differences. Somehow <code>ax2.set_xticks</code> fails to place the ticks according to the right x limits. </p> <p>EDIT :</p> <p>I tried to place <code>ax1.set_xlim([20, 120])</code> anywhere after <code>ax2.set_xlim(ax1.get_xlim())</code> it gives again the wrong things :</p> <p><a href="http://i.stack.imgur.com/UedJL.png" rel="nofollow"><img src="http://i.stack.imgur.com/UedJL.png" alt="enter image description here"></a></p> <p>Actually i don't get the meaning of <code>ax2.set_xticks()</code>, It sets position where ticklabels will be displayed no ? </p> <p>EDIT :</p> <p><strong>Ok, we got it : the x_lim definition <code>ax2.set_xlim(ax1.get_xlim())</code> must come after the tick and ticklabel definition.</strong></p> <pre><code>import numpy as np import matplotlib.pyplot as plt plt.close('all') fig = plt.figure(1,figsize = [5,4]) ax1 = fig.add_subplot(111) ax1.set_xlabel('first axis') ax1.grid(True) ax1.set_xlim([10, 120]) ax2 = ax1.twiny() second_ticks = np.array([1.,10.,100.]) ax2.set_xticks(second_ticks) ax2.set_xticklabels(np.log10(second_ticks)) ax2.set_xlabel('second axis') ax2.set_xlim(ax1.get_xlim()) fig.tight_layout() plt.show() </code></pre> <p><a href="http://i.stack.imgur.com/J7Lmk.png" rel="nofollow"><img src="http://i.stack.imgur.com/J7Lmk.png" alt="enter image description here"></a></p> <p>Thanks !</p> <p>Regards,</p>
0
2016-08-17T14:08:08Z
39,002,068
<p>I believe your are getting unexpected results because you are forcing the x-ticks and the x-tick-labels on the second axis to be something predefined. No matter what you put as x-ticks on the second axis they will always be labeled by: <code>ax2.set_xticklabels(np.log10(second_ticks))</code>. Instead, update the x-tick-labels on the second axis <strong>after</strong> you have updated them on the first axis</p> <pre><code>import numpy as np import matplotlib.pyplot as plt fig = plt.figure(3,figsize = [5,4]) ax1 = fig.add_subplot(111) ax1.set_xlabel('first axis') x = np.linspace(0,100,num=200) ax1.set_xlim([0, 120]) ax1.grid(True) ax2 = ax1.twiny() ax2.set_xlim(ax1.get_xlim()) # or alternatively : # ax2.set_xbound(ax1.get_xbound()) # second_ticks = np.array([1.,10.,100.]) # ax2.set_xticks(second_ticks) ax2.set_xlabel('second axis') # Set the xlim on axis 1, then update the x-tick-labels on axis 2 ax1.set_xlim([20, 100]) ax2.set_xticklabels(np.log10(ax1.get_xticks())) plt.show() </code></pre> <p>Does this solve your problem? (Ps. there are several typos in your code...it is not runnable...)</p>
1
2016-08-17T16:41:02Z
[ "python", "matplotlib" ]
How to save certain but also multiple words from a string into a variable?
38,999,037
<p>If I have a string that is like this "Hello everyone Thank you for helping me"</p> <p>Is there any python command that is easy to use that can generate a variable (lets say var) that contains the string "Hello Thank you for helping" based on the numbered order of the words? For example, I want to generate this string variable over multiple rows of a csv file all with the same format and for all of them, I hope to get a variable with the 1st, 3rd, 4th, 5th, and 6th words of the string. </p> <p>I know the split command, but im hoping to generate a variable with multiple words instead of printing just one. </p> <p>Thanks!</p>
-1
2016-08-17T14:09:07Z
38,999,204
<p>You can use a <code>split</code>, followed by a <code>list comprehension</code>, and finally a <code>join</code> like so:</p> <pre><code>&gt;&gt;&gt; s = "Hello everyone Thank you for helping me" &gt;&gt;&gt; " ".join([x for i,x in enumerate(s.split()) if i not in (1,6)]) 'Hello Thank you for helping' </code></pre>
0
2016-08-17T14:16:13Z
[ "python" ]
How to save certain but also multiple words from a string into a variable?
38,999,037
<p>If I have a string that is like this "Hello everyone Thank you for helping me"</p> <p>Is there any python command that is easy to use that can generate a variable (lets say var) that contains the string "Hello Thank you for helping" based on the numbered order of the words? For example, I want to generate this string variable over multiple rows of a csv file all with the same format and for all of them, I hope to get a variable with the 1st, 3rd, 4th, 5th, and 6th words of the string. </p> <p>I know the split command, but im hoping to generate a variable with multiple words instead of printing just one. </p> <p>Thanks!</p>
-1
2016-08-17T14:09:07Z
38,999,209
<p>Based just on what you've provided, to get the, if existing, 1st/3rd/4th/5th/6th words all saved to one var and not a list, you would use</p> <pre><code>string1 = 'Hello everyone Thank you for helping me' var = ' '.join([string1.split(' ')[i] for i in range(len(string1.split())) if i != 1 and i &lt; 6]) </code></pre> <p>I think you need to provide more details though, as this seems to be a very specific use case.</p>
0
2016-08-17T14:16:22Z
[ "python" ]
How to save certain but also multiple words from a string into a variable?
38,999,037
<p>If I have a string that is like this "Hello everyone Thank you for helping me"</p> <p>Is there any python command that is easy to use that can generate a variable (lets say var) that contains the string "Hello Thank you for helping" based on the numbered order of the words? For example, I want to generate this string variable over multiple rows of a csv file all with the same format and for all of them, I hope to get a variable with the 1st, 3rd, 4th, 5th, and 6th words of the string. </p> <p>I know the split command, but im hoping to generate a variable with multiple words instead of printing just one. </p> <p>Thanks!</p>
-1
2016-08-17T14:09:07Z
38,999,240
<p>Why not </p> <pre><code>x="Hello everyone Thank you for helping me".split() del x[6] #throw away seventh word del x[1] #throw away second word s=" ".join(x) </code></pre> <p>?</p>
1
2016-08-17T14:18:11Z
[ "python" ]
Django Test -- Unable to drop and recreate test database
38,999,203
<p>I am running Django 1.9, Postgres 9.5.1 on Mac OS X</p> <p>When I run <code>/manage.py test --settings=myproj.settings.local</code></p> <p>I get :</p> <pre><code>Creating test database for alias 'default'... Creating test database for alias 'userlocation'... Got an error creating the test database: database "test_myproj" already exists Type 'yes' if you would like to try deleting the test database 'test_myproj', or 'no' to cancel: yes Destroying old test database for alias 'userlocation'... Got an error recreating the test database: database "test_myproj" is being accessed by other users DETAIL: There is 1 other session using the database. </code></pre> <p>So, as per <a href="http://stackoverflow.com/questions/5108876/kill-a-postgresql-session-connection">This post</a>, I run:</p> <pre><code>SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE pid &lt;&gt; pg_backend_pid() AND datname = 'test_myproj' ; </code></pre> <p>The proceed to <code>DROP DATABASE test_myproj</code> and try to run tests again only to get the error <code>DETAIL: There is 1 other session using the database.</code></p> <p>Looking as the process list, nothing is attached to the database. I kill the server and restart, but the management command to run tests still gives me the error that there is another session attached to the database.</p> <p>This is a real head scratcher, I have never seen this before -- has anyone else?</p> <p>My settings:</p> <pre><code>DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'myproj', 'USER': 'myuser', 'PASSWORD': 'mypass', 'HOST': 'localhost', 'PORT': '', }, 'userlocation': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': 'og_myproj', 'USER': 'og_myuser', 'PASSWORD': 'mypasswd', 'HOST': 'localhost', 'PORT': '5432', } } </code></pre>
2
2016-08-17T14:16:10Z
39,000,107
<p><code>sudo /etc/init.d/postgresql restart</code> may be a restart will solve this issue</p>
1
2016-08-17T14:58:38Z
[ "python", "django", "postgresql", "postgis" ]
How to simulate saturations and thresholds with Scipy?
38,999,317
<p>how to simulate saturations and thresholds with scipy?</p> <p>I precise my question I want to simulate with scipy a system like the one described by the block diagram below. If the system had only linear transfer functions, there would be no problem, but here I have a non-linear block, a saturation (it could there be a threshold) What is the solution to program and simulate the block diagram. <a href="http://i.stack.imgur.com/16083.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/16083.jpg" alt="enter image description here"></a></p> <p>with:</p> <pre><code>PT2=1/(1+s+s^2) and P=K=100 </code></pre>
-7
2016-08-17T14:22:05Z
39,187,861
<p>You could try <a href="http://pythonhosted.org/bms/getting_started.html" rel="nofollow">Steven Masfaraud's block module simulator (BMS)</a>. As of August 2016 it has nonlinear block elements for Saturation, Coulomb, Dead Zone, and Hysteresis. Here's <a href="https://github.com/masfaraud/BMSpy/blob/master/examples/second_order.py" rel="nofollow">a link to one of his examples</a>.</p> <p>The other option on <a href="https://www.quora.com/When-will-there-be-a-Simulink-like-alternative-for-Python" rel="nofollow">this Quora post</a> is <a href="https://github.com/PyLinX-Project/PyLinX" rel="nofollow">PyLinX</a>.</p> <p>It looks like SciPySim may no longer be under development, from <a href="https://code.google.com/archive/p/scipy-sim/" rel="nofollow">this link</a> that states <em>"Please note that this project is no longer being actively developed or maintained."</em>.</p>
1
2016-08-28T03:54:14Z
[ "python", "scipy" ]
Extract string within parentheses - PYTHON
38,999,344
<p>I have a string "Name(something)" and I am trying to extract the portion of the string within the parentheses! </p> <p>Iv'e tried the following solutions but don't seem to be getting the results I'm looking for. </p> <pre><code>n.split('()') name, something = n.split('()') </code></pre>
0
2016-08-17T14:23:25Z
38,999,572
<p>You can use a simple regex to catch everything between the parenthesis:</p> <pre><code>&gt;&gt;&gt; s = 'Name(something)' &gt;&gt;&gt; re.search('\(([^)]+)', s).group(1) 'something' </code></pre> <p>The regex matches the first "(", then it matches everything that's <em>not</em> a ")":</p> <ul> <li><code>\(</code> matches the character "(" literally</li> <li>the capturing group <code>([^)]+)</code> greedily matches anything that's not a ")"</li> </ul>
3
2016-08-17T14:33:41Z
[ "python", "string", "split", "extract" ]
Extract string within parentheses - PYTHON
38,999,344
<p>I have a string "Name(something)" and I am trying to extract the portion of the string within the parentheses! </p> <p>Iv'e tried the following solutions but don't seem to be getting the results I'm looking for. </p> <pre><code>n.split('()') name, something = n.split('()') </code></pre>
0
2016-08-17T14:23:25Z
38,999,578
<p>You can use split as in your example but this way</p> <pre><code>val = s.split('(', 1)[1].split(')')[0] </code></pre> <p>or using regex</p>
0
2016-08-17T14:34:03Z
[ "python", "string", "split", "extract" ]
Extract string within parentheses - PYTHON
38,999,344
<p>I have a string "Name(something)" and I am trying to extract the portion of the string within the parentheses! </p> <p>Iv'e tried the following solutions but don't seem to be getting the results I'm looking for. </p> <pre><code>n.split('()') name, something = n.split('()') </code></pre>
0
2016-08-17T14:23:25Z
38,999,682
<p>You can use <code>re.match</code>:</p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; s = "name(something)" &gt;&gt;&gt; na, so = re.match(r"(.*)\((.*)\)" ,s).groups() &gt;&gt;&gt; na, so ('name', 'something') </code></pre> <p>that matches two <code>(.*)</code> which means anything, where the second is between parentheses <code>\(</code> &amp; <code>\)</code>.</p>
0
2016-08-17T14:38:54Z
[ "python", "string", "split", "extract" ]
Using a python webserver
38,999,349
<p>I am looking for a web server, where I can upload files and download files from Ubuntu to Windows and the vice versa. I've builded a web server with Python and I share my folder in Ubuntu and download the files in this folder at Windows. Now I want to look up every millisecond if there is a new file and download this new files automatically. Is there any script or something helpfully for me? Is a python web server a good solution?</p>
-2
2016-08-17T14:23:36Z
38,999,734
<p>There are many ways to synchronise folders, even remote. If you need to stick with the python server approach for some reason, look for file system events libraries to trigger your upload code (for example <a href="https://pypi.python.org/pypi/watchdog" rel="nofollow" title="watchdog">watchdog</a>). But if not, it may be simpler to use tools like <a href="http://linux.die.net/man/1/rsync" rel="nofollow">rsync</a> + <a href="http://man7.org/linux/man-pages/man7/inotify.7.html" rel="nofollow">inotify</a>, or simply <a href="https://github.com/axkibe/lsyncd" rel="nofollow">lsync</a>.</p> <p>Good luck!</p> <p><strong>Edit:</strong> I just realized you want linux->windows sync, not the other way around, so since you don't have ssh server on the target (windows), rsync and lsync will not work for you, you probably need <a href="https://www.samba.org/samba/docs/man/manpages/smbclient.1.html" rel="nofollow">smbclient</a>. In python, consider <a href="https://pypi.python.org/pypi/pysmbc" rel="nofollow">pysmbc</a> or <a href="https://pypi.python.org/pypi/PySmbClient" rel="nofollow">PySmbClient</a></p>
0
2016-08-17T14:41:00Z
[ "python", "http", "webserver" ]
Execute flask-SQLAlchemy subquery
38,999,534
<p>I want to execute the following subquery in flask-SQLAlchemy but don't know how:</p> <pre><code>SELECT * FROM ( SELECT * FROM `articles` WHERE publisher_id = "bild" ORDER BY date_time DESC LIMIT 10 ) AS t ORDER BY RAND( ) LIMIT 2 </code></pre> <p>I know I can build the query as:</p> <pre><code>subq = Article.query.filter(Article.publisher_id =='bild').order_by(Article.date_time.desc()).limit(10).subquery() qry = subq.select().order_by(func.rand()).limit(2) </code></pre> <p>However I don't know how to execute it in the same fashion as I would execute e.g.</p> <pre><code>articles = Article.query.filter(Article.publisher_id =='bild').all() </code></pre> <p>i.e. to get all the Article objects. What I can do is call</p> <pre><code>db.session.execute(qry).fetchall() </code></pre> <p>but this only gives me a list with actual row values instead of the objects on which I could for example call another function (like <code>article.to_json()</code>).</p> <p>Any ideas? <code>qry</code> is a <code>sqlalchemy.sql.selectable.Select</code> object and <code>db.session.execute(qry)</code> a <code>sqlalchemy.engine.result.ResultProxy</code> while <code>Article.query</code>, on which I could call <code>all()</code>, is a <code>flask_sqlalchemy.BaseQuery</code>. Thanks!!</p>
1
2016-08-17T14:32:08Z
39,001,648
<p>You can use <a href="http://docs.sqlalchemy.org/en/rel_1_0/orm/query.html#sqlalchemy.orm.query.Query.select_entity_from" rel="nofollow">select_entity_from</a></p> <pre><code>qry = db.session.query(Article).select_entity_from(subq).order_by(func.rand()).limit(2) </code></pre> <p>or <a href="http://docs.sqlalchemy.org/en/rel_1_0/orm/query.html#sqlalchemy.orm.query.Query.from_self" rel="nofollow">from_self</a></p> <pre><code>Article.query.filter(Article.publisher_id =='bild')\ .order_by(Article.date_time.desc())\ .limit(10)\ .from_self()\ .order_by(func.rand())\ .limit(2) </code></pre>
0
2016-08-17T16:16:13Z
[ "python", "mysql", "sqlalchemy", "flask-sqlalchemy" ]
Change pagination based on user type with django rest framework
38,999,535
<p>I try to set the pagination of my WebAPI based on the status of a User. If the user <code>is_anonymous</code> he should not be able to set the page size with a query parameter. I try to do this with one view class. I could do it with two different view classes and limit the access to one of them, but I think this is not a good solution.</p> <p>View Class:</p> <pre><code>class WeathermList(generics.ListAPIView): queryset = WeatherMeasurements.objects.all() serializer_class = WeatherMeasurementsSer filter_backends = (filters.DjangoFilterBackend, filters.OrderingFilter,) filter_class = WeatherMeasurementsFilter ordering_fields = ('measure_datetime',) ordering = ('measure_datetime',) @property def paginator(self): """ The paginator instance associated with the view, or `None`. """ if not hasattr(self, '_paginator'): # import ipdb # ipdb.set_trace() if self.request.user.is_anonymous: self._paginator = AnonymousPaginator else: self._paginator = RegisteredPaginator return self._paginator </code></pre> <p>Pagination classes:</p> <pre><code>class RegisteredPaginator(PageNumberPagination): page_size = 288 page_size_query_param = 'page_size' max_page_size = 10000 class AnonymousPaginator(PageNumberPagination): page_size = 288 </code></pre> <p>Error message:</p> <pre><code>File ".../env/lib/python3.5/site-packages/rest_framework/generics.py", line 172, in paginate_queryset return self.paginator.paginate_queryset(queryset, self.request, view=self) TypeError: paginate_queryset() missing 1 required positional argument: 'request' </code></pre> <p>The <code>property paginator</code> is originally declared in class <a href="https://github.com/tomchristie/django-rest-framework/blob/67ac0486f504d957fd123c8b913fb93a71cacdcd/rest_framework/generics.py" rel="nofollow">GenericAPIView</a>. I am not sure if I reimplement it correctly. Both Custom pagination classes of mine are working when I set them using <code>pagination_class</code></p> <p>Any help to get this working is greatly appreciated.</p>
0
2016-08-17T14:32:08Z
38,999,960
<p>The problem is: <code>self._paginator</code> needs a paginator class instance, not a class itself</p> <p>It should be <code>AnonymousPaginator()</code>and <code>RegisteredPaginator()</code>, not <code>AnonymousPaginator</code>, <code>RegisteredPaginator</code>.</p> <pre><code> if self.request.user.is_anonymous: self._paginator = AnonymousPaginator() else: self._paginator = RegisteredPaginator() </code></pre>
2
2016-08-17T14:52:12Z
[ "python", "django", "pagination", "django-rest-framework" ]
Update webpage after receiving POST request
38,999,552
<p>I've to tried to find out similar issue in stack overflow, but I couldn't. I am using python requests library to send POST request to my personal domain name www.****.com. </p> <pre><code>r = requests.post('http://www.****.com', data = {'temp1':"Anum"}) print r.text </code></pre> <p>When I run the script, the r.text shows me "Welcome Anum". Where I have written a small php script on my website</p> <pre><code>&lt;?php $data=$_POST["temp1"]; echo "Welcome ". $data. "&lt;br /&gt;"; ?&gt; </code></pre> <p>Now the problem is, I am not able to see this get request on actual website, even after refreshing the page. I tried sending POST request in a loop after every 3 seconds, but still can't see any update on actual website. Do I need to loop up my php code to continuously listen for requests from client ? My understanding is that my domain name is working as Server and python script as client, so as the client send request to server, how do I manage my server to catch that request and display on web page ? </p>
0
2016-08-17T14:32:52Z
38,999,640
<p>I understand you want the python script to send a variable, which will be visible to other visitors of the website? You need to store the value which you recieve from python somewhere, like in a database. Then you can read that value and show it to the visitor.</p>
1
2016-08-17T14:37:15Z
[ "php", "python", "http-post" ]
Loading cookies in JSON format into requests
38,999,554
<p>I've got some cookies sent over from a client to allow me to log into his server programatically without needing the credentials.</p> <p>I'm using the requests package to make HTTP requests to his server. The problem is the cookies he has sent are all in JSON format and I can't seem to find any way to load these cookies.</p> <p>Aside from writing a method to convert them into regular cookies are there any existing solutions to load these cookies?</p> <p>Here is my current code:</p> <pre><code>def cookieLogin(cookies): with open(cookies) as f: cookies = requests.utils.cookiejar_from_dict(json.load(f)[0] ) session = requests.session() session.cookies = cookies r = session.get('https://example.com') </code></pre> <p>Cookie example:</p> <pre><code>[ { "domain": ".example.com", "hostOnly": false, "httpOnly": false, "name": "act", "path": "/", "sameSite": "no_restriction", "secure": false, "session": true, "storeId": "0", "value": "875", "id": 1 }, { "domain": ".example.com", "expirationDate": 1479135421.720188, "hostOnly": false, "httpOnly": false, "name": "c_user", "path": "/", "sameSite": "no_restriction", "secure": true, "session": false, "storeId": "0", "value": "109", "id": 2 }, ... </code></pre> <p>Error:</p> <pre><code>Traceback (most recent call last): File "./cookieInviter.py", line 37, in &lt;module&gt; session = cookieLogin(args.cookies) File "/Users/jj/Projects/Jim/login.py", line 78, in cookieLogin r = session.get('https://example.com') File "/Library/Python/2.7/site-packages/requests/sessions.py", line 487, in get return self.request('GET', url, **kwargs) File "/Library/Python/2.7/site-packages/requests/sessions.py", line 461, in request prep = self.prepare_request(req) File "/Library/Python/2.7/site-packages/requests/sessions.py", line 394, in prepare_request hooks=merge_hooks(request.hooks, self.hooks), File "/Library/Python/2.7/site-packages/requests/models.py", line 297, in prepare self.prepare_cookies(cookies) File "/Library/Python/2.7/site-packages/requests/models.py", line 518, in prepare_cookies cookie_header = get_cookie_header(self._cookies, self) File "/Library/Python/2.7/site-packages/requests/cookies.py", line 136, in get_cookie_header jar.add_cookie_header(r) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/cookielib.py", line 1342, in add_cookie _header attrs = self._cookie_attrs(cookies) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/cookielib.py", line 1301, in _cookie_at trs self.non_word_re.search(cookie.value) and version &gt; 0): TypeError: expected string or buffer </code></pre> <p>CookieJar:</p> <pre><code>&lt;RequestsCookieJar[&lt;Cookie domain=.example.com for /&gt;, &lt;Cookie hostOnly=False for /&gt;, &lt;Cookie httpOnly=False for /&gt;, &lt;Cookie id=1 for /&gt;, &lt;Cookie name=act for /&gt;, &lt;Cookie path=/ for /&gt;, &lt;Cookie sameSite=no_restriction for /&gt;, &lt;Cookie s ecure=False for /&gt;, &lt;Cookie session=True for /&gt;, &lt;Cookie storeId=0 for /&gt;, &lt;Cookie value=... for /&gt;]&gt; </code></pre>
1
2016-08-17T14:32:54Z
38,999,760
<p>Use <a href="http://docs.python-requests.org/en/master/api/#requests.utils.cookiejar_from_dict" rel="nofollow">requests.utils.cookiejar_from_dict(cookie_dict)</a> to create a cookie jar from a dict:</p> <pre><code>jar = requests.utils.cookiejar_from_dict(cookie_dict) session = request.Session() session.cookies = jar r = session.get(url) </code></pre>
0
2016-08-17T14:42:14Z
[ "python" ]
Crontab - run command random time
38,999,597
<p>I have created a cron job in which it runs a command within random value (Example 10 mins) at 11pm everyday. I found this example online but I can not find reference. </p> <p>What I have that doesn't work</p> <pre><code>SHELL=/bin/bash PATH=/usr/bin:$PATH LOCAL_CONFIG_DIR=/user/folder 0 11 * * * sleep $(($RANDOM \% 10))m &amp;&amp; python /user/folder/file.py </code></pre> <p>The following works but does not run at random 10 mins:</p> <pre><code>SHELL=/bin/bash PATH=/usr/bin:$PATH LOCAL_CONFIG_DIR=/user/folder 0 11 * * * python /user/folder/file.py </code></pre> <p>Wonder if my issue is with <code>$Random</code>?</p>
1
2016-08-17T14:34:51Z
38,999,776
<p>I'm not really good with bash, but You surely can implement sleep inside your python scipt.</p> <pre><code>import random import time time.sleep(random.randint(1, 10)*60) #Your actual script goes here </code></pre>
2
2016-08-17T14:43:11Z
[ "python", "random", "cron", "crontab" ]
Format the index in connection with to_html in a Pandas DataFrame
38,999,600
<p>I was hoping that it was possible to format the index (column) directly in connection with output to HTML with the to_html() in the Pandas DataFrame?</p> <p>Something like:</p> <pre><code>df = DataFrame([[1, 2]], index=['a'], columns=['A', 'B']) print(df.to_html(formatters={ 'index': lambda elem: '&lt;a href="example.com/{}"&gt;{}&lt;/a&gt;'.format(elem, elem)}, escape=False)) </code></pre> <p>This does not work. I do not get a link.</p> <p>I suppose I would need to do something like</p> <pre><code>dfc = df.copy() dfc.index = ['&lt;a href="example.com/{}"&gt;{}&lt;/a&gt;'.format(i, i) for i in df.index] print(dfc.to_html(escape=False)) </code></pre>
1
2016-08-17T14:35:01Z
38,999,706
<p>you should use <code>__index__</code> instead of <code>index</code>:</p> <pre><code>print(df.to_html(formatters={ '__index__': lambda elem: '&lt;a href="example.com/{}"&gt;{}&lt;/a&gt;'.format(elem, elem)}, escape=False)) </code></pre> <p>Source: <a href="https://github.com/pydata/pandas/pull/2409" rel="nofollow">The pull request that introduced that feature</a>.</p>
1
2016-08-17T14:39:54Z
[ "python", "pandas" ]
Python3 Tracking movement with opencv2
38,999,617
<p>So, I've downloaded this source code from <a href="http://www.pyimagesearch.com/2015/05/25/basic-motion-detection-and-tracking-with-python-and-opencv/" rel="nofollow">http://www.pyimagesearch.com/2015/05/25/basic-motion-detection-and-tracking-with-python-and-opencv/</a> :</p> <pre><code> # import the necessary packages import argparse import datetime import imutils import time import cv2 # construct the argument parser and parse the arguments ap = argparse.ArgumentParser() ap.add_argument("-v", "--video", help="path to the video file") ap.add_argument("-a", "--min-area", type=int, default=500, help="minimum area size") args = vars(ap.parse_args()) # if the video argument is None, then we are reading from webcam if args.get("video", None) is None: camera = cv2.VideoCapture(0) time.sleep(0.25) # otherwise, we are reading from a video file else: camera = cv2.VideoCapture(args["video"]) # initialize the first frame in the video stream firstFrame = None # loop over the frames of the video while True: # grab the current frame and initialize the occupied/unoccupied # text (grabbed, frame) = camera.read() text = "Unoccupied" # if the frame could not be grabbed, then we have reached the end # of the video if not grabbed: break # resize the frame, convert it to grayscale, and blur it frame = imutils.resize(frame, width=500) gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) gray = cv2.GaussianBlur(gray, (21, 21), 0) # if the first frame is None, initialize it if firstFrame is None: firstFrame = gray continue # compute the absolute difference between the current frame and # first frame frameDelta = cv2.absdiff(firstFrame, gray) thresh = cv2.threshold(frameDelta, 25, 255, cv2.THRESH_BINARY)[1] # dilate the thresholded image to fill in holes, then find contours # on thresholded image thresh = cv2.dilate(thresh, None, iterations=2) (cnts, _) = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) # loop over the contours for c in cnts: # if the contour is too small, ignore it if cv2.contourArea(c) &lt; args["min_area"]: continue # compute the bounding box for the contour, draw it on the frame, # and update the text (x, y, w, h) = cv2.boundingRect(c) cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2) text = "Occupied" </code></pre> <p>But when I run it, it gives me this error:</p> <pre><code>Traceback (most recent call last): File "/Users/luistripa/Downloads/basic-motion-detection/motion_detector.py", line 57, in &lt;module&gt; cv2.CHAIN_APPROX_SIMPLE) ValueError: too many values to unpack (expected 2) </code></pre> <p>Can anyone help me fix this?</p>
0
2016-08-17T14:35:50Z
39,009,340
<p>try adding [-2:] behind </p> <p>(cnts, _) = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[-2:]</p>
0
2016-08-18T03:03:14Z
[ "python", "opencv" ]
how to use config in flask extensions when use factory pattern in flask?
38,999,702
<p>I use factory pattern and flask extensions such as flask-admin during the development of web application. I want to load some configurations in flask-admin when the app haven't created. So i use the <code>current_app.config["SOME_CONFIG"]</code> to get the config value.But i got the <code>Working outside of application context.</code> exception. The code as follows:</p> <pre><code># __init__.py from flask import Flask def create_app(config_name): app = Flask(__name__) app.config.from_object(config_name) app.config.from_pyfile("config.py") from admin import admin admin.init_app(app) return app # admin/__init__.py from flask import current_app from flask_admin import Admin admin = Admin(name=current_app.config["ADMIN_NAME"], template="bootstrap2") </code></pre>
0
2016-08-17T14:39:40Z
39,000,316
<p>Your application is still in the setup state during the create_app function (see <a href="http://flask.pocoo.org/docs/0.11/appcontext/" rel="nofollow">http://flask.pocoo.org/docs/0.11/appcontext/</a>). During the setup state you need to have a reference to the application object to access it, you can't use current_app. </p> <p>You could instantiate the Admin object within the create_app function using:</p> <p><code>admin = Admin(name=app.config["ADMIN_NAME"], template="bootstrap2")</code></p> <p>OR</p> <p>change the admin variable and create a function in your <code>admin/__init__.py</code>:</p> <pre><code>admin = object() def instantiate_admin(config): global admin admin = Admin(name=config["ADMIN_NAME"], template="bootstrap2") return admin </code></pre> <p>and use this in create_app():</p> <pre><code>from admin import instantiate_admin admin = instantiate_admin(app.config) admin.init_app(app) </code></pre>
2
2016-08-17T15:07:34Z
[ "python", "flask" ]
how to use config in flask extensions when use factory pattern in flask?
38,999,702
<p>I use factory pattern and flask extensions such as flask-admin during the development of web application. I want to load some configurations in flask-admin when the app haven't created. So i use the <code>current_app.config["SOME_CONFIG"]</code> to get the config value.But i got the <code>Working outside of application context.</code> exception. The code as follows:</p> <pre><code># __init__.py from flask import Flask def create_app(config_name): app = Flask(__name__) app.config.from_object(config_name) app.config.from_pyfile("config.py") from admin import admin admin.init_app(app) return app # admin/__init__.py from flask import current_app from flask_admin import Admin admin = Admin(name=current_app.config["ADMIN_NAME"], template="bootstrap2") </code></pre>
0
2016-08-17T14:39:40Z
39,006,238
<p>All you need to do is set it up like the following.</p> <pre><code># config.py class Config(object): ADMIN_NAME = 'admin' # __init__.py from flask import Flask from flask_admin import Admin # initiate all extensions here admin = Admin(template='bootstrap2') def create_app(config): app = Flask(__name__) app.config.from_object(config) admin.init_app(app) return app # wsgi.py from . import create_app from config import Config app = create_app(Config) if __name__ == '__main__': app.run() </code></pre> <p>And in you admin package</p> <pre><code># admin/__init__.py from .. import admin # import extensions from __init__.py admin.add_view('blah') </code></pre> <p>Below is a link to an real world example. I scrubbed info so it is more generic but this is how i setup all my flask apps.</p> <p><a href="http://hastebin.com/likupoxoxi.py" rel="nofollow">http://hastebin.com/likupoxoxi.py</a></p> <p>As long as you are running the dev server you shouldn't have issues that keeps it in the context of the application.</p>
0
2016-08-17T21:02:37Z
[ "python", "flask" ]
Python - RPG name maker using lists
39,000,032
<p>I am trying to make a 3 part name generator in python for an RPG game. I have a 2 dimensional array in order to combine 3 parts of a name:</p> <pre><code>name = [["Raan","Feim","Od","Yol","Dur"]["Mir","Zii","Ah","Toor","Neh"][ "Tah","Gron","Viing","Shul","Viir"]] </code></pre> <p>However, when I run it, I get the error:</p> <pre><code>TypeError: list indices must be integers or slices, not tuple </code></pre> <p>Is there a way around this/can it be done in a 2d array</p>
1
2016-08-17T14:55:04Z
39,000,197
<p>You need commas between your lists:</p> <pre><code>name = [["Raan","Feim","Od","Yol","Dur"], ["Mir","Zii","Ah","Toor","Neh"], [ "Tah","Gron","Viing","Shul","Viir"]] </code></pre>
1
2016-08-17T15:02:18Z
[ "python" ]
Python - RPG name maker using lists
39,000,032
<p>I am trying to make a 3 part name generator in python for an RPG game. I have a 2 dimensional array in order to combine 3 parts of a name:</p> <pre><code>name = [["Raan","Feim","Od","Yol","Dur"]["Mir","Zii","Ah","Toor","Neh"][ "Tah","Gron","Viing","Shul","Viir"]] </code></pre> <p>However, when I run it, I get the error:</p> <pre><code>TypeError: list indices must be integers or slices, not tuple </code></pre> <p>Is there a way around this/can it be done in a 2d array</p>
1
2016-08-17T14:55:04Z
39,000,218
<p>wrong list syntax. This works:</p> <pre><code>import random name = [["Raan","Feim","Od","Yol","Dur"],["Mir","Zii","Ah","Toor","Neh"],["Tah","Gron","Viing","Shul","Viir"]] print (" ".join([random.choice(nl) for nl in name])) </code></pre>
2
2016-08-17T15:03:07Z
[ "python" ]
Python - RPG name maker using lists
39,000,032
<p>I am trying to make a 3 part name generator in python for an RPG game. I have a 2 dimensional array in order to combine 3 parts of a name:</p> <pre><code>name = [["Raan","Feim","Od","Yol","Dur"]["Mir","Zii","Ah","Toor","Neh"][ "Tah","Gron","Viing","Shul","Viir"]] </code></pre> <p>However, when I run it, I get the error:</p> <pre><code>TypeError: list indices must be integers or slices, not tuple </code></pre> <p>Is there a way around this/can it be done in a 2d array</p>
1
2016-08-17T14:55:04Z
39,000,283
<p>You need commas inbetween each list.</p> <pre><code>name = [["Raan","Feim","Od","Yol","Dur"],["Mir","Zii","Ah","Toor","Neh"],[ "Tah","Gron","Viing","Shul","Viir"]] </code></pre> <p>then to get a random name use:</p> <pre><code>from random import randint print (name[randint(0,2)][randint(0,4)]) </code></pre> <p>and you could do this 3 times or however you want the name to come out</p> <p><strong>UPDATE</strong></p> <p>Something like this is what I'm guessing you want:</p> <pre><code>from random import randint name = [["Raan","Feim","Od","Yol","Dur"],["Mir","Zii","Ah","Toor","Neh"],[ "Tah","Gron","Viing","Shul","Viir"]] print(name[randint(0,2)][randint(0,4)] + name[randint(0,2)][randint(0,4)] + name[randint(0,2)][randint(0,4)]) </code></pre>
2
2016-08-17T15:06:08Z
[ "python" ]
How can I set the colors per value when coloring plots by a DataFrame column?
39,000,115
<p>In matplotlib (in particular, pandas), how can I map specific colors to values of a column that I use for differentiating colors?</p> <p>Let's say I have a column ...</p> <pre><code>&gt;&gt; df["country"] DE EN US DE </code></pre> <p>... and now I'd like to plot values from the DataFrame where each country is colored differently. How can I determine which country gets which color? With a colormap? I wasn't able to find the proper documentation, unfortunately.</p> <p>I would like to apply a dict like this:</p> <pre><code># pseudo-code colormapping = {"DE": "blue", ...} df.plot(colorby="country", colormapping) </code></pre> <p>Edit:</p> <p>Here's a sample DataFrame.</p> <pre><code> outlook play temperature country 0 sunny True 25 DE 1 sunny True 25 EN 2 overcast True 19 DE 3 rain False 21 US 4 overcast False 33 IT 5 rain False 27 EN 6 rain False 22 FR 7 overcast True 26 FR 8 sunny True 13 FR 9 sunny True 16 CH </code></pre>
-1
2016-08-17T14:58:53Z
39,003,608
<p>You can do so by specifying the dictionary mapping of hue levels to corresponding <code>matplotlib</code> colors in the <a href="https://stanford.edu/~mwaskom/software/seaborn/tutorial/color_palettes.html" rel="nofollow"><code>palette</code></a> argument of a <a href="https://stanford.edu/~mwaskom/software/seaborn/tutorial/categorical.html" rel="nofollow"><code>categorical plot</code></a> using <code>seaborn</code> as shown:</p> <pre><code>sns.set(style="whitegrid") sns.swarmplot(x="outlook", y="temperature", hue="country", data=df, size=8, palette={'DE':'b', 'EN':'g', 'US':'r','IT':'c', 'FR':'y', 'CH':'k'}) </code></pre> <p><a href="http://i.stack.imgur.com/s5TVE.png" rel="nofollow"><img src="http://i.stack.imgur.com/s5TVE.png" alt="enter image description here"></a></p>
2
2016-08-17T18:11:23Z
[ "python", "pandas", "matplotlib", "colors", "seaborn" ]
How to display two different outputs in python console
39,000,250
<p>Is there a way to split the output console? I would like to display one section on top (the main program) and the bottom part will display a progress bar for example.</p> <p>(excuse my horrible design skills)</p> <p><a href="http://i.stack.imgur.com/pXcbD.png" rel="nofollow"><img src="http://i.stack.imgur.com/pXcbD.png" alt="enter image description here"></a></p> <p>Any ideas will be greatly appreciated :)</p>
1
2016-08-17T15:04:56Z
39,002,750
<p>If there is one python app that outputs - using curses library as @Rawing suggested: <a href="https://docs.python.org/3.5/howto/curses.html" rel="nofollow">https://docs.python.org/3.5/howto/curses.html</a> . It's prebuilt and at hand.</p> <p>If there are more apps that output data there are several ways to do so. First, you can use byobu or alike and have split terminal with outputs from different apps visible on the same screen. Second, you can have a broadcaster app that collects data from worker apps (or threads) and displays them later with curses (see above).</p> <p>More, you can dump data to a file and then using Linux watch command show contents at regular intervals:</p> <pre><code>watch cat file </code></pre> <p>There are lots of other methods too.</p>
0
2016-08-17T17:19:06Z
[ "python", "split", "terminal" ]
Two y axes for a single plot
39,000,269
<p>I'm trying to create a plot with two Y axes (left and right) for the same data, that is, one is a scaled version of the other. I would like also to preserve the tick positions and grid positions, so the grid will match the ticks at both sides.</p> <p>I'm trying to do this by plotting twice the same data, one as-is and the other scaled, but they are not coincident.</p> <pre><code>import numpy as np import matplotlib.pyplot as plt x = np.arange(17, 27, 0.1) y1 = 0.05 * x + 100 fig, ax1 = plt.subplots() ax2 = ax1.twinx() ax1.plot(x, y1, 'g-') ax2.plot(x, y1/max(y1), 'g-') ax1.set_xlabel('X data') ax1.set_ylabel('Y data', color='g') ax2.set_ylabel('Y data normalized', color='b') plt.grid() plt.show() </code></pre> <p>Any help will be appreciated.</p>
0
2016-08-17T15:05:37Z
39,000,482
<p>Not sure if you can achieve this without getting ugly-looking numbers on your normalized axis. But if that doesn't bother you, try adding this to your code:</p> <pre><code>ax2.set_ylim([ax1.get_ylim()[0]/max(y1),ax1.get_ylim()[1]/max(y1)]) ax2.set_yticks(ax1.get_yticks()/max(y1)) </code></pre> <p>Probably not the most elegant solution, but it scales your axis limits and tick positions similarly to what you do with the data itself so the grid matches both axes.</p>
0
2016-08-17T15:16:10Z
[ "python", "matplotlib" ]
Emit new style PyQt signals with arbitrary signature
39,000,286
<p>I am creating a PyQt GUI for an experimental setup. This will involve computationally heavy operations so I am aiming for an architecture based on the multiprocessing module and inspired from <a href="http://stackoverflow.com/a/30048847/1291711">this answer</a>. </p> <p>The QMainWindow creates</p> <ol> <li>child Processes with an individual "task" Queue to get instructions from the main process and a shared "callback" Queue to send back instructions to the main process</li> <li>a QThread to poll the "callback" queue and translate the messages into signals that are connected to slots of the QMainWindow</li> </ol> <p>The example uses old style signals with arbitrary signature <code>self.emit(QtCore.SIGNAL(signature), args)</code>. <strong>My question is:</strong> is it possible to replicate this functionality with new-style signals ?. </p> <p>I am aware of <a href="http://stackoverflow.com/q/4523006/1291711">this question</a> and of <a href="http://stackoverflow.com/q/11199622/1291711">this one</a>. However, always emitting a <code>valueChanged</code> signal with a general object does not suit my needs since I would like to connect to slots with different names depending on the signature received from one of the child Processes.</p> <p>Here is a working code (note there is only one child process and one slot in the MainWindow for simplicity, but there will be several in the finished code):</p> <pre><code>from multiprocessing import Process, Queue import sys from PyQt4 import QtGui, QtCore class CallbackQueueToSignal(QtCore.QThread): def __init__(self, queue, parent=None): super(CallbackQueueToSignal, self).__init__(parent) self.queue = queue def _emit(self, signature, args=None): if args: self.emit(QtCore.SIGNAL(signature), args) else: self.emit(QtCore.SIGNAL(signature)) def run(self): while True: signature = self.queue.get() self._emit(*signature) class WorkerProcess(Process): def __init__(self, callback_queue, task_queue, daemon=True): super(WorkerProcess, self).__init__() self.daemon = daemon self.callback_queue = callback_queue self.task_queue = task_queue def _process_call(self, func_name, args=None): func = getattr(self, func_name) if args: func(args) else: func() def emit_to_mother(self, signature, args=None): signature = (signature, ) if args: signature += (args, ) self.callback_queue.put(signature) def run(self): while True: call = self.task_queue.get() # print("received: {}".format(call)) self._process_call(*call) def text_upper(self, text): self.emit_to_mother('data(PyQt_PyObject)', (text.upper(),)) class MainWin(QtGui.QMainWindow): def __init__(self, parent=None): super(MainWin, self).__init__(parent) self.data_to_child = Queue() self.callback_queue = Queue() self.callback_queue_watcher = CallbackQueueToSignal(self.callback_queue) self.callback_queue_watcher.start() self.child = WorkerProcess(self.callback_queue, self.data_to_child) self.child.start() self.browser = QtGui.QTextBrowser() self.lineedit = QtGui.QLineEdit('Type text and press &lt;Enter&gt;') self.lineedit.selectAll() layout = QtGui.QVBoxLayout() layout.addWidget(self.browser) layout.addWidget(self.lineedit) self.layout_widget = QtGui.QWidget() self.layout_widget.setLayout(layout) self.setCentralWidget(self.layout_widget) self.lineedit.setFocus() self.setWindowTitle('Upper') self.connect(self.lineedit, QtCore.SIGNAL('returnPressed()'), self.to_child) self.connect(self.callback_queue_watcher, QtCore.SIGNAL('data(PyQt_PyObject)'), self.updateUI) def to_child(self): self.data_to_child.put(("text_upper", ) + (self.lineedit.text(), )) self.lineedit.clear() def updateUI(self, text): text = text[0] self.browser.append(text) def closeEvent(self, event): result = QtGui.QMessageBox.question( self, "Confirm Exit...", "Are you sure you want to exit ?", QtGui.QMessageBox.Yes | QtGui.QMessageBox.No) event.ignore() if result == QtGui.QMessageBox.Yes: # self.pipeWatcher.exit() self.child.terminate() event.accept() if __name__ == '__main__': app = QtGui.QApplication(sys.argv) form = MainWin() form.show() app.aboutToQuit.connect(app.deleteLater) sys.exit(app.exec_()) </code></pre>
1
2016-08-17T15:06:27Z
39,044,391
<p>The <a href="http://pyqt.sourceforge.net/Docs/PyQt4/new_style_signals_slots.html" rel="nofollow">new-style signal and slot syntax</a> requires that signals are pre-defined as class attributes on a class that inherits from <code>QObject</code>. When the class is instantiated, a bound-signal object is automatically created for the instance. The bound-signal object has <code>connect/disconnect/emit</code> methods, and a <code>__getitem__</code> syntax which allows different overloads to be selected.</p> <p>Since bound-signals are <em>objects</em>, it no longer makes sense to allow the dynamic emission of arbitrary signals that was possible with the old-style syntax. This is simply because an arbitrary signal (i.e. one that is not <em>pre-defined</em>) could not have a corresponding bound-signal object for slots to connect to.</p> <p>The example code in the question can still be ported to the new-style syntax, though:</p> <pre><code>class CallbackQueueToSignal(QtCore.QThread): dataSignal = QtCore.pyqtSignal([], [object], [object, object]) ... def _emit(self, signal, *args): getattr(self, signal)[(object,) * len(args)].emit(*args) def run(self): while True: args = self.queue.get() self._emit(*args) class WorkerProcess(Process): ... def emit_to_mother(self, *args): self.callback_queue.put(args) def text_upper(self, text): self.emit_to_mother('dataSignal', (text.upper(),)) class MainWin(QtGui.QMainWindow): def __init__(self, parent=None): ... self.lineedit.returnPressed.connect(self.to_child) self.callback_queue_watcher.dataSignal[object].connect(self.updateUI) </code></pre>
1
2016-08-19T17:05:07Z
[ "python", "python-3.x", "pyqt4", "python-multiprocessing", "qt-signals" ]
How to send the encrypted data to the client?
39,000,296
<p>Here is my client code.</p> <pre><code>import socket, pickle,time from encryption import * def Main(): host = '127.0.0.1' port = 5006 s = socket.socket() s.connect((host, port)) m= encryption() pri_key,pub_key,n=m.generating_keys(1) filename = input("Filename? -&gt; ") if filename != 'q': data=[filename,pub_key,n] msg=pickle.dumps(data) s.send(msg) data = s.recv(1024) data=data.decode('utf-8') if data == '1': size = s.recv(1024) size = int(size.decode('utf-8')) filesize = size message = input("File exists, " + str(filesize) +"Bytes, download? (Y/N)? -&gt; ") if message == 'Y': s.send(b'1') count=0 f = open('new_'+filename, 'wb') data = s.recv(1024) data=int.from_bytes(data,byteorder="little") msg=m.decrypt(data,pri_key,n) totalRecv = len(msg) f.write(msg) #count=0 while totalRecv&lt;filesize: #time.sleep(.300) decipher = s.recv(1024) decipher=int.from_bytes(decipher,byteorder="little") print(decipher) if(decipher==0): break msg=m.decrypt(decipher,pri_key,n) totalRecv += len(msg) f.write(msg) print ("{0:.2f}".format((totalRecv/float(filesize))*100)+ "% Done") print ("Download Complete!") f.close() else: print ("File Does Not Exist!") s.close() if __name__ == '__main__': Main() </code></pre> <p>Here is my server code.</p> <pre><code>import socket,threading,os,pickle from encryption import * def RetrFile(name, sock): m=encryption() filename = sock.recv(1024) dat=pickle.loads(filename) if os.path.isfile(dat[0]): s='1' s=s.encode('utf-8') sock.send(s) k=str(os.path.getsize(dat[0])) k=k.encode('utf-8') sock.send(k) count=8 userResponse = sock.recv(1024) if userResponse[:2] == (b'1'): with open(dat[0],'rb') as f: bytesToSend = f.read(1024) #print(type(bytesToSend)) #print('1') #print(bytesToSend) msg= m.encrypt(bytesToSend,dat[1],dat[2]) #print(msg) #print(1) k=msg.bit_length() if(k%8&gt;=1): k=k+1 msg=msg.to_bytes(k,byteorder="little") #print (msg) #msg=msg.encode('utf-8') #print(msg) sock.send(msg) s='' s=s.encode('utf-8') while bytesToSend != s: bytesToSend = f.read(1024) msg= m.encrypt(bytesToSend,dat[1],dat[2]) k=msg.bit_length() if(k%8&gt;=1): k=k//8+1 msg=msg.to_bytes(k,byteorder="little") sock.send(msg) #count=count.to_bytes(1,byteorder="little") #sock.send(count) else: sock.send(b'ERR') sock.close() def Main(): host = '127.0.0.1' port = 5006 s = socket.socket() s.bind((host,port)) s.listen(5) print ("Server Started.") while True: c, addr = s.accept() print ("client connedted ip:&lt;" + str(addr) + "&gt;") t = threading.Thread(target=RetrFile, args=("RetrThread", c)) t.start() s.close() if __name__ == '__main__': Main() </code></pre> <p>Now my problem is that decipher.recv(1024) in client side is not receiving the message. what should i do.</p>
-1
2016-08-17T15:06:55Z
39,014,705
<p>On the server side, change the code to:</p> <pre><code>while bytesToSend != s: bytesToSend = f.read(1024) length = len(bytesTosend) leng = length.to_bytes(4, 'little') sock.sendall(leng) msg = m.encrypt(bytesToSend, dat[1], dat[2]) k = msg.bit_length() if k % 8 &gt;= 1 : k = k // 8 + 1 else: k = k // 8 msg = msg.to_bytes(k, byteorder='little') sock.sendall(msg) </code></pre> <p>And on the client side:</p> <pre><code>while True: length = s.recv(4) length = int.from_bytes(length, byteorder='little') decipher = s.recv(leng) decipher = int.from_bytes(decipher, byteorder='little') if not decipher: break msg = m.decrypt(decipher, pri_key, n) f.write(msg) f.close() </code></pre>
0
2016-08-18T09:34:32Z
[ "python", "sockets", "python-3.x", "encryption" ]
How to send the encrypted data to the client?
39,000,296
<p>Here is my client code.</p> <pre><code>import socket, pickle,time from encryption import * def Main(): host = '127.0.0.1' port = 5006 s = socket.socket() s.connect((host, port)) m= encryption() pri_key,pub_key,n=m.generating_keys(1) filename = input("Filename? -&gt; ") if filename != 'q': data=[filename,pub_key,n] msg=pickle.dumps(data) s.send(msg) data = s.recv(1024) data=data.decode('utf-8') if data == '1': size = s.recv(1024) size = int(size.decode('utf-8')) filesize = size message = input("File exists, " + str(filesize) +"Bytes, download? (Y/N)? -&gt; ") if message == 'Y': s.send(b'1') count=0 f = open('new_'+filename, 'wb') data = s.recv(1024) data=int.from_bytes(data,byteorder="little") msg=m.decrypt(data,pri_key,n) totalRecv = len(msg) f.write(msg) #count=0 while totalRecv&lt;filesize: #time.sleep(.300) decipher = s.recv(1024) decipher=int.from_bytes(decipher,byteorder="little") print(decipher) if(decipher==0): break msg=m.decrypt(decipher,pri_key,n) totalRecv += len(msg) f.write(msg) print ("{0:.2f}".format((totalRecv/float(filesize))*100)+ "% Done") print ("Download Complete!") f.close() else: print ("File Does Not Exist!") s.close() if __name__ == '__main__': Main() </code></pre> <p>Here is my server code.</p> <pre><code>import socket,threading,os,pickle from encryption import * def RetrFile(name, sock): m=encryption() filename = sock.recv(1024) dat=pickle.loads(filename) if os.path.isfile(dat[0]): s='1' s=s.encode('utf-8') sock.send(s) k=str(os.path.getsize(dat[0])) k=k.encode('utf-8') sock.send(k) count=8 userResponse = sock.recv(1024) if userResponse[:2] == (b'1'): with open(dat[0],'rb') as f: bytesToSend = f.read(1024) #print(type(bytesToSend)) #print('1') #print(bytesToSend) msg= m.encrypt(bytesToSend,dat[1],dat[2]) #print(msg) #print(1) k=msg.bit_length() if(k%8&gt;=1): k=k+1 msg=msg.to_bytes(k,byteorder="little") #print (msg) #msg=msg.encode('utf-8') #print(msg) sock.send(msg) s='' s=s.encode('utf-8') while bytesToSend != s: bytesToSend = f.read(1024) msg= m.encrypt(bytesToSend,dat[1],dat[2]) k=msg.bit_length() if(k%8&gt;=1): k=k//8+1 msg=msg.to_bytes(k,byteorder="little") sock.send(msg) #count=count.to_bytes(1,byteorder="little") #sock.send(count) else: sock.send(b'ERR') sock.close() def Main(): host = '127.0.0.1' port = 5006 s = socket.socket() s.bind((host,port)) s.listen(5) print ("Server Started.") while True: c, addr = s.accept() print ("client connedted ip:&lt;" + str(addr) + "&gt;") t = threading.Thread(target=RetrFile, args=("RetrThread", c)) t.start() s.close() if __name__ == '__main__': Main() </code></pre> <p>Now my problem is that decipher.recv(1024) in client side is not receiving the message. what should i do.</p>
-1
2016-08-17T15:06:55Z
39,023,618
<p>It is rather difficult to check your code without seeing the <code>encryption</code> module referenced in your code. With such functionality absent, testing to find out where the problem is becomes impossible. As such, the following programs are provided along with the implementation of another encryption module.</p> <hr> <p>The server should be run from the command line and requires a port number and password to be supplied upon execution. The only form of authentication or authorization used is proper understanding of the client. The client must use the same password to be understood by the server.</p> <p><strong>Server</strong></p> <pre><code>#! /usr/bin/env python3 import argparse import pathlib import pickle import pickletools import random import socket import socketserver import zlib import encryption BYTES_USED = bytes(range(1 &lt;&lt; 8)) CHAIN_SIZE = 1 &lt;&lt; 8 def main(): """Start a file server and serve clients forever.""" parser = argparse.ArgumentParser(description='Execute a file server demo.') parser.add_argument('port', type=int, help='location where server listens') parser.add_argument('password', type=str, help='key to use on secure line') arguments = parser.parse_args() server_address = socket.gethostbyname(socket.gethostname()), arguments.port server = CustomServer(server_address, CustomHandler, arguments.password) server.serve_forever() class CustomServer(socketserver.ThreadingTCPServer): """Provide server support for the management of encrypted data.""" def __init__(self, server_address, request_handler_class, password): """Initialize the server and keep a set of security credentials.""" super().__init__(server_address, request_handler_class, True) self.key = encryption.Key.new_client_random( BYTES_USED, CHAIN_SIZE, random.Random(password) ) self.primer = encryption.Primer.new_client_random( self.key, random.Random(password) ) class CustomHandler(socketserver.StreamRequestHandler): """Allow forwarding of data to all connected clients.""" def __init__(self, request, client_address, server): """Initialize the handler with security translators.""" self.decoder = encryption.Decrypter(server.key, server.primer) self.encoder = encryption.Encrypter(server.key, server.primer) super().__init__(request, client_address, server) def handle(self): """Run the code to handle clients while dealing with errors.""" try: self.process_file_request() except (ConnectionResetError, EOFError): pass def process_file_request(self): """Deal with clients that wish to download a file.""" segment = self.load() path = pathlib.Path(segment) if path.is_file(): size = path.stat().st_size self.dump(size) accepted = self.load() if accepted: with path.open('rb') as file: while True: buffer = file.read(1 &lt;&lt; 15) self.dump(buffer) if not buffer: break else: error = 'The given path does not specify a file.' self.dump(error) def load(self): """Read the client's connection with blocking.""" data = self.decoder.load_16bit_frame(self.rfile) bytes_object = zlib.decompress(data) return pickle.loads(bytes_object) def dump(self, obj): """Send an object securely over to the client if possible.""" pickle_string = pickle.dumps(obj, pickle.HIGHEST_PROTOCOL) bytes_object = pickletools.optimize(pickle_string) data = zlib.compress(bytes_object, zlib.Z_BEST_COMPRESSION) self.encoder.dump_16bit_frame(data, self.wfile) if __name__ == '__main__': main() </code></pre> <hr> <p>The client should also be run from the command line and requires the host name, port number, and password for the server. Communications are encrypted with the password and cannot be decrypted properly if it is different. Please note that very little checking for errors is present in the two programs.</p> <p><strong>Client</strong></p> <pre><code>#! /usr/bin/env python3 import argparse import pathlib import pickle import pickletools import random import socket import zlib import encryption BYTES_USED = bytes(range(1 &lt;&lt; 8)) CHAIN_SIZE = 1 &lt;&lt; 8 # These are possible answers accepted for yes/no style questions. POSITIVE = tuple(map(str.casefold, ('yes', 'true', '1'))) NEGATIVE = tuple(map(str.casefold, ('no', 'false', '0'))) def main(): """Connect a file client to a server and process incoming commands.""" parser = argparse.ArgumentParser(description='Execute a file client demo.') parser.add_argument('host', type=str, help='name of server on the network') parser.add_argument('port', type=int, help='location where server listens') parser.add_argument('password', type=str, help='key to use on secure line') arguments = parser.parse_args() connection = socket.create_connection((arguments.host, arguments.port)) try: talk_to_server(*make_dump_and_load(connection, arguments.password)) finally: connection.shutdown(socket.SHUT_RDWR) connection.close() def make_dump_and_load(connection, password): """Create objects to help with the encrypted communications.""" reader = connection.makefile('rb', -1) writer = connection.makefile('wb', 0) chaos = random.Random(password) key = encryption.Key.new_client_random(BYTES_USED, CHAIN_SIZE, chaos) chaos = random.Random(password) primer = encryption.Primer.new_client_random(key, chaos) decoder = encryption.Decrypter(key, primer) encoder = encryption.Encrypter(key, primer) def dump(obj): """Write an object to the writer file in an encoded form.""" pickle_string = pickle.dumps(obj, pickle.HIGHEST_PROTOCOL) bytes_object = pickletools.optimize(pickle_string) data = zlib.compress(bytes_object, zlib.Z_BEST_COMPRESSION) encoder.dump_16bit_frame(data, writer) def load(): """Read an object from the reader file and decode the results.""" data = decoder.load_16bit_frame(reader) bytes_object = zlib.decompress(data) return pickle.loads(bytes_object) return dump, load def talk_to_server(dump, load): """Converse with the serve while trying to get a file.""" segment = input('Filename: ') dump(segment) size = load() if isinstance(size, int): print('File exists and takes', size, 'bytes to download.') response = get_response('Continue? ') dump(response) if response: location = input('Where should the new file be created? ') with pathlib.Path(location).open('wb') as file: written = 0 while True: buffer = load() if not buffer: break written += file.write(buffer) print('Progress: {:.1%}'.format(written / size)) print('Download complete!') else: print(size) def get_response(query): """Ask the user yes/no style questions and return the results.""" while True: answer = input(query).casefold() if answer: if any(option.startswith(answer) for option in POSITIVE): return True if any(option.startswith(answer) for option in NEGATIVE): return False print('Please provide a positive or negative answer.') if __name__ == '__main__': main() </code></pre> <hr> <p>Since access to the <code>encryption</code> module was not provided, an alternative implementation has been included below. No guarantee is made for its suitability in any capacity or for any purpose. It may be somewhat slow as the software is currently configured but works well if obfuscation is desired.</p> <p><strong>encryption</strong></p> <pre><code>"""Provide an implementation of Markov Encryption for simplified use. This module exposes primitives useful for executing Markov Encryption processes. ME was inspired by a combination of Markov chains with the puzzles of Sudoku. This implementation has undergone numerous changes and optimizations since its original design. Please see documentation.""" ############################################################################### # Import several functions needed later in the code. from collections import deque from math import ceil from random import Random, SystemRandom from struct import calcsize, pack, unpack from inspect import currentframe __author__ = 'Stephen "Zero" Chappell &lt;Noctis.Skytower@gmail.com&gt;' __date__ = '18 August 2016' __version__ = 2, 0, 8 ############################################################################### # Create some tools to use in the classes down below. _CHAOS = SystemRandom() def slots(names=''): """Set the __slots__ variable in the calling context with private names. This function allows a convenient syntax when specifying the slots used in a class. Simply call it in a class definition context with the needed names. Locals are modified with private slot names.""" currentframe().f_back.f_locals['__slots__'] = \ tuple('__' + name for name in names.replace(',', ' ').split()) ############################################################################### # Implement a Key primitive data type for Markov Encryption. class Key: """Key(data) -&gt; Key instance This class represents a Markov Encryption Key primitive. It allows for easy key creation, checks for proper data construction, and helps with encoding and decoding indexes based on cached internal tables.""" slots('data dimensions base size encoder axes order decoder') @classmethod def new(cls, bytes_used, chain_size): """Return a Key instance created from bytes_used and chain_size. Creating a new key is easy with this method. Call this class method with the bytes you want the key to recognize along with the size of the chains you want the encryption/decryption processes to use.""" selection, blocks = list(set(bytes_used)), [] for _ in range(chain_size): _CHAOS.shuffle(selection) blocks.append(bytes(selection)) return cls(tuple(blocks)) @classmethod def new_deterministic(cls, bytes_used, chain_size): """Automatically create a key with the information provided.""" selection, blocks, chaos = list(set(bytes_used)), [], Random() chaos.seed(chain_size.to_bytes(ceil( chain_size.bit_length() / 8), 'big') + bytes(range(256))) for _ in range(chain_size): chaos.shuffle(selection) blocks.append(bytes(selection)) return cls(tuple(blocks)) @classmethod def new_client_random(cls, bytes_used, chain_size, chaos): """Create a key using chaos as the key's source of randomness.""" selection, blocks = list(set(bytes_used)), [] for _ in range(chain_size): chaos.shuffle(selection) blocks.append(bytes(selection)) return cls(tuple(blocks)) def __init__(self, data): """Initialize the Key instance's variables after testing the data. Keys are created with tuples of carefully constructed bytes arrays. This method tests the given data before going on to build internal tables for efficient encoding and decoding methods later on.""" self.__test_data(data) self.__make_vars(data) @staticmethod def __test_data(data): """Test the data for correctness in its construction. The data must be a tuple of at least two byte arrays. Each byte array must have at least two bytes, all of which must be unique. Furthermore, all arrays should share the exact same byte set.""" if not isinstance(data, tuple): raise TypeError('Data must be a tuple object!') if len(data) &lt; 2: raise ValueError('Data must contain at least two items!') item = data[0] if not isinstance(item, bytes): raise TypeError('Data items must be bytes objects!') length = len(item) if length &lt; 2: raise ValueError('Data items must contain at least two bytes!') unique = set(item) if len(unique) != length: raise ValueError('Data items must contain unique byte sets!') for item in data[1:]: if not isinstance(item, bytes): raise TypeError('Data items must be bytes objects!') next_length = len(item) if next_length != length: raise ValueError('All data items must have the same size!') next_unique = set(item) if len(next_unique) != next_length: raise ValueError('Data items must contain unique byte sets!') if next_unique ^ unique: raise ValueError('All data items must use the same byte set!') def __make_vars(self, data): """Build various internal tables for optimized calculations. Encoding and decoding rely on complex relationships with the given data. This method caches several of these key relationships for use when the encryption and decryption processes are being executed.""" self.__data = data self.__dimensions = len(data) base, *mutations = data self.__base = base = tuple(base) self.__size = size = len(base) offset = -sum(base.index(block[0]) for block in mutations[:-1]) % size self.__encoder = base[offset:] + base[:offset] self.__axes = tuple(reversed([tuple(base.index(byte) for byte in block) for block in mutations])) self.__order = key = tuple(sorted(base)) grid = [] for rotation in range(size): block, row = base[rotation:] + base[:rotation], [None] * size for byte, value in zip(block, key): row[key.index(byte)] = value grid.append(tuple(row)) self.__decoder = tuple(grid[offset:] + grid[:offset]) def test_primer(self, primer): """Raise an error if the primer is not compatible with this key. Key and primers have a certain relationship that must be maintained in order for them to work together. Since the primer understands the requirements, it is asked to check this key for compatibility.""" primer.test_key(self) def encode(self, index): """Encode index based on internal tables and return byte code. An index probes into the various axes of the multidimensional, virtual grid that a key represents. The index is evaluated, and the value at its coordinates is returned by running this method.""" assert len(index) == self.__dimensions, \ 'Index size is not compatible with key dimensions!' *probes, current = index return self.__encoder[(sum( table[probe] for table, probe in zip(self.__axes, probes) ) + current) % self.__size] def decode(self, index): """Decode index based on internal tables and return byte code. Decoding does the exact same thing as encoding, but it indexes into a virtual grid that represents the inverse of the encoding grid. Tables are used to make the process fast and efficient.""" assert len(index) == self.__dimensions, \ 'Index size is not compatible with key dimensions!' *probes, current = index return self.__decoder[sum( table[probe] for table, probe in zip(self.__axes, probes) ) % self.__size][current] @property def data(self): """Data that the instance was initialized with. This is the tuple of byte arrays used to create this key and can be used to create an exact copy of this key at some later time.""" return self.__data @property def dimensions(self): """Dimensions that the internal, virtual grid contains. The virtual grid has a number of axes that can be referenced when indexing into it, and this number is the count of its dimensions.""" return self.__dimensions @property def base(self): """Base value that the internal grid is built from. The Sudoku nature of the grid comes from rotating this value by offsets, keeping values unique along any axis while traveling.""" return self.__base @property def order(self): """Order of base after its values have been sorted. A sorted base is important when constructing inverse rows and when encoding raw bytes for use in updating an encode/decode index.""" return self.__order ############################################################################### # Implement a Primer primitive data type for Markov Encryption. class Primer: """Primer(data) -&gt; Primer instance This class represents a Markov Encryption Primer primitive. It is very important for starting both the encryption and decryption processes. A method is provided for their easy creation with a related key.""" slots('data') @classmethod def new(cls, key): """Return a Primer instance from a parent Key. Primers must be compatible with the keys they are used with. This method takes a key and constructs a cryptographically sound primer that is ready to use in the beginning stages of encryption.""" base = key.base return cls(bytes(_CHAOS.choice(base) for _ in range(key.dimensions - 1))) @classmethod def new_deterministic(cls, key): """Automatically create a primer with the information provided.""" base, chain_size, chaos = key.base, key.dimensions, Random() chaos.seed(chain_size.to_bytes(ceil( chain_size.bit_length() / 8), 'big') + bytes(range(256))) return cls(bytes(chaos.choice(base) for _ in range(chain_size - 1))) @classmethod def new_client_random(cls, key, chaos): """Create a primer using chaos as the primer's source of randomness.""" base = key.base return cls( bytes(chaos.choice(base) for _ in range(key.dimensions - 1)) ) def __init__(self, data): """Initialize the Primer instance after testing validity of data. Though not as complicated in its requirements as keys, primers do need some simple structure in the data they are given. A checking method is run before saving the data to the instance's attribute.""" self.__test_data(data) self.__data = data @staticmethod def __test_data(data): """Test the data for correctness and test the data. In order for the primer to be compatible with the nature of the Markov Encryption processes, the data must be an array of bytes; and to act as a primer, it must contain at least some information.""" if not isinstance(data, bytes): raise TypeError('Data must be a bytes object!') if not data: raise ValueError('Data must contain at least one byte!') def test_key(self, key): """Raise an error if the key is not compatible with this primer. Primers provide needed data to start encryption and decryption. For it be compatible with a key, it must contain one byte less than the key's dimensions and must be a subset of the base in the key.""" if len(self.__data) != key.dimensions - 1: raise ValueError('Key size must be one more than the primer size!') if not set(self.__data).issubset(key.base): raise ValueError('Key data must be a superset of primer data!') @property def data(self): """Data that the instance was initialized with. This is the byte array used to create this primer and can be used if desired to create an copy of this primer at some later time.""" return self.__data ############################################################################### # Create an abstract processing class for use in encryption and decryption. class _Processor: """_Processor(key, primer) -&gt; NotImplementedError exception This class acts as a base for the encryption and decryption processes. The given key is saved, and several tables are created along with an index. Since it is abstract, calling the class will raise an exception.""" slots('key into index from') def __init__(self, key, primer): """Initialize the _Processor instance if it is from a child class. After passing several tests for creating a valid processing object, the key is saved, and the primer is used to start an index. Tables are also formed for converting byte values between systems.""" if type(self) is _Processor: raise NotImplementedError('This is an abstract class!') key.test_primer(primer) self.__key = key self.__into = table = dict(map(reversed, enumerate(key.order))) self.__index = deque(map(table.__getitem__, primer.data), key.dimensions) self.__from = dict(map(reversed, table.items())) def process(self, data): """Process the data and return its transformed state. A cache for the data transformation is created and an internal method is run to quickly encode or decode the given bytes. The cache is finally converted to immutable bytes when returned.""" cache = bytearray() self._run(data, cache.append, self.__key, self.__into, self.__index) return bytes(cache) @staticmethod def _run(data, cache_append, key, table, index): """Run the processing algorithm in an overloaded method. Since this is only an abstract base class for encoding/decoding, this method will raise an exception when run. Inheriting classes should implement whatever is appropriate for the intended function.""" raise NotImplementedError('This is an abstract method!') @property def primer(self): """Primer representing the state of the internal index. The index can be retrieved as a primer, useful for initializing another processor in the same starting state as the current one.""" index = self.__index index.append(None) index.pop() return Primer(bytes(map(self.__from.__getitem__, index))) ############################################################################### # Inherit from _Processor and implement the ME encoding algorithm. class Encrypter(_Processor): """Encrypter(key, primer) -&gt; Encrypter instance This class represents a state-aware encryption engine that can be fed data and will return a stream of coherent cipher-text. An index is maintained, and a state-continuation primer can be retrieved at will.""" slots() @staticmethod def _run(data, cache_append, key, table, index): """Encrypt the data with the given arguments. To run the encryption process as fast as possible, methods are cached as names. As the algorithm operates, only recognized bytes are encoded while running through the selective processing loop.""" encode, index_append = key.encode, index.append for byte in data: if byte in table: index_append(table[byte]) cache_append(encode(index)) else: cache_append(byte) def dump_16bit_frame(self, data, file): """Write the data to the file using a guaranteed frame size.""" size = len(data) if not 1 &lt;= size &lt;= 1 &lt;&lt; 16: raise ValueError('data has an unsupported length') packed = self.process(pack('&lt;H{}s'.format(size), size - 1, data)) if file.write(packed) != len(packed): raise IOError('frame was not properly written to file') ############################################################################### # Inherit from _Processor and implement the ME decoding algorithm. class Decrypter(_Processor): """Decrypter(key, primer) -&gt; Decrypter instance This class represents a state-aware decryption engine that can be fed data and will return a stream of coherent plain-text. An index is maintained, and a state-continuation primer can be retrieved at will.""" slots() SIZE = '&lt;H' DATA = '{}s' @staticmethod def _run(data, cache_append, key, table, index): """Decrypt the data with the given arguments. To run the decryption process as fast as possible, methods are cached as names. As the algorithm operates, only recognized bytes are decoded while running through the selective processing loop.""" decode, index_append = key.decode, index.append for byte in data: if byte in table: index_append(table[byte]) value = decode(index) cache_append(value) index[-1] = table[value] else: cache_append(byte) def load_16bit_frame(self, file): """Read some data from the file using a guaranteed frame size.""" size = unpack(self.SIZE, self.process(self.read_all( file, calcsize(self.SIZE) )))[0] + 1 return unpack(self.DATA.format(size), self.process(self.read_all( file, size )))[0] @staticmethod def read_all(file, size): """Get all the data that has been requested from the file.""" if not 1 &lt;= size &lt;= 1 &lt;&lt; 16: raise ValueError('size has an unsupported value') buffer = bytearray() while size &gt; 0: data = file.read(size) if not data: raise EOFError('file has unexpectedly reached the end') buffer.extend(data) size -= len(data) if size &lt; 0: raise IOError('more data was read than was required') return bytes(buffer) </code></pre>
0
2016-08-18T16:50:48Z
[ "python", "sockets", "python-3.x", "encryption" ]
Openerp - how to update filed with write()
39,000,306
<p>I have this function and up to last update query it works fine. What I tried to do is update the current value of 'number_of_days_temp' field by adding 0.5 to it. But <code>cr.execute</code> doesn't update the field and just return the same old value. Please help me with this with fixing the <code>cr.execute</code> or with <code>write()</code> function.</p> <p>My function</p> <pre><code>def allocate_on_probations(self, cr, uid, ids,tl=False, context=None): result = {} emps=self.pool.get('hr.employee').search(cr, uid, [('current_status','=','active')], context=context) if emps: for r in emps: hol_state=2 gt_dt=cr.execute("""SELECT appointed_date FROM hr_employee WHERE id= %d order by id"""%(r)) gt_dd=cr.fetchone()[0] #getting today details today = datetime.datetime.now() tt=today.date() td=tt.day tm=tt.month ty=tt.year #getting appointment date details app=datetime.datetime.strptime(gt_dd, "%Y-%m-%d").date() ay=app.year am=app.month ad=app.day if ay==ty: #compairing today and appointed date comp=(tt-app) chat=int(comp.days) print chat chat_mod=chat%30 print chat_mod print r if chat_mod==29: hol_obj=self.pool.get('hr.holidays') print hol_obj condition_1=[('employee_id','=',r),('type','=','add'),('holiday_status_id','=',hol_state)] hol_emp=hol_obj.search(cr, uid,condition_1, context=context) if hol_emp: for n in hol_emp: print n hol_tp = self.pool.get('hr.holidays').search(cr, uid, [('id','=',n)], context=None) hol_tp_br = self.pool.get('hr.holidays').browse(cr, uid, hol_tp, context=None) hol_name = hol_tp_br[0].number_of_days_temp print hol_name hol_name=(hol_name+0.5) print hol_name #This is where it dosn't up date the field and up to this the function gives the right values #debug mode and as in here it prints the correct values. cr.execute("""UPDATE hr_holidays SET number_of_days_temp= %d WHERE id= %d"""%(hol_inc,n)) cr.execute("""UPDATE hr_holidays SET number_of_days= %d WHERE id= %d"""%(hol_inc,n)) return True </code></pre>
0
2016-08-17T15:07:15Z
39,002,357
<p>Here is the little optimized version of your method</p> <pre><code>def allocate_on_probations(self, cr, uid, ids, tl=False, context=None): result = {} emp_obj = self.pool.get('hr.employee') emp_ids = emp_obj.search(cr, uid, [('current_status','=','active')], context=context) if emps: for emp in emp_obj.browse(cr, uid, emp_ids, context=context): hol_state=2 gt_dt=cr.execute("""SELECT appointed_date FROM hr_employee WHERE id= %d order by id"""%(r)) gt_dd=cr.fetchone()[0] #getting today details today = datetime.datetime.now() tt=today.date() td=tt.day tm=tt.month ty=tt.year #getting appointment date details app=datetime.datetime.strptime(gt_dd, "%Y-%m-%d").date() ay=app.year am=app.month ad=app.day if ay==ty: #compairing today and appointed date comp=(tt-app) chat=int(comp.days) chat_mod=chat%30 if chat_mod==29: hol_obj=self.pool.get('hr.holidays') condition_1=[('employee_id','=',r),('type','=','add'),('holiday_status_id','=',hol_state)] hol_emp=hol_obj.search(cr, uid,condition_1, context=context) if hol_emp: for holiday_rec in hol_obj.browse(cr, uid, hol_emp, context=context): hol_name = holiday_rec.number_of_days_temp hol_name_add =(hol_name+0.5) hol_obj.write(cr, uid, [holiday_rec.id], {'number_of_days_temp': hol_name_add , 'number_of_days': hol_name} ) return True </code></pre> <p>You have to look at the write and need to change the variable <code>hol_name_add</code> and <code>hol_name</code>.</p> <p>Hope this helps!</p>
1
2016-08-17T16:56:16Z
[ "python", "python-2.7", "openerp", "openerp-7" ]
Fit t distribution using scipy with predetermined mean and std(loc & scale)?
39,000,357
<p>How can I fit t distribution using <code>scipy.stats.t.fit()</code> with predetermined mean and std?</p> <p>The question is, I have a standardized dataset, with <code>mean=0</code> and <code>std=1</code>, I only want to get <code>df</code> of t distribution. But when I do <code>scipy.stats.t.fit(data)</code>, it outputs <code>df, loc, scale</code>, and loc&amp;sclae not necessarily equal to 0&amp;1.</p> <p>How can I solve this? Thanks!</p>
2
2016-08-17T15:09:36Z
39,001,308
<p>In the call to <code>.fit()</code>, use the arguments <code>floc=0</code> and <code>fscale=1</code> to fix these parameters.</p> <p>Here's an example. First, import <code>t</code> and generate a sample to work with:</p> <pre><code>In [24]: from scipy.stats import t In [25]: np.random.seed(123) In [26]: sample = t.rvs(3, loc=0, scale=1, size=10000) </code></pre> <p>Now use the <code>.fit()</code> method to fit the <code>t</code> distribution to the sample, constraining the location to 0 and the scale to 1:</p> <pre><code>In [27]: t.fit(sample, floc=0, fscale=1) Out[27]: (3.1099609375000048, 0, 1) </code></pre> <p>There are more examples (using different distributions) in the <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.rv_continuous.fit.html" rel="nofollow"><code>fit</code> docstring</a> and <a href="http://stackoverflow.com/search?q=%5Bscipy%5D%20floc">here on stackoverflow</a>.</p>
1
2016-08-17T15:57:45Z
[ "python", "scipy" ]
Handling web-log files as a CSV with Python
39,000,374
<p>I'm using the Python 3 CSV Reader to read some web-log files into a namedtuple. I have no control over the log file structures, and there are varying types.</p> <p>The delimiter is a space ( ), the problem is that some log file formats place a space in the timestamp, as Logfile 2 below. The CSV reader then reads the date/time stamp as two fields.</p> <p>Logfile 1</p> <pre><code>73 58 2993 [22/Jul/2016:06:51:06.299] 2[2] "GET /example HTTP/1.1" 13 58 224 [22/Jul/2016:06:51:06.399] 2[2] "GET /example HTTP/1.1" </code></pre> <p>Logfile 2</p> <pre><code>13 58 224 [22/Jul/2016:06:51:06 +0000] 2[2] "GET /test HTTP/1.1" 153 38 224 [22/Jul/2016:06:51:07 +0000] 2[2] "GET /test HTTP/1.1" </code></pre> <p>The log files typically have the timestamp within square quotes, but I cannot find a way of handling them as "quotes". On top of that, square brackets are not always used as quotes within the logs either (see the [2] later in the logs).</p> <p>I've read through the <a href="https://docs.python.org/3/library/csv.html" rel="nofollow">Python 3 CSV Reader documentation</a>, including about dialects, but there doesn't seem to be anything for handling enclosing square brackets.</p> <p>How can I handle this situation automatically?</p>
2
2016-08-17T15:10:33Z
39,000,418
<p>This will do, you need to use a regex in place of sep.<br> This for example will parse NGinx log files into a <code>pandas.Dataframe</code>:</p> <pre><code>import pandas as pd df = pd.read_csv(log_file, sep=r'\s(?=(?:[^"]*"[^"]*")*[^"]*$)(?![^\[]*\])', engine='python', usecols=[0, 3, 4, 5, 6, 7, 8], names=['ip', 'time', 'request', 'status', 'size', 'referer', 'user_agent'], na_values='-', header=None ) </code></pre> <p>Edit : </p> <pre><code>line = '172.16.0.3 - - [25/Sep/2002:14:04:19 +0200] "GET / HTTP/1.1" 401 - "" "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.1) Gecko/20020827"' regex = '([(\d\.)]+) - - \[(.*?)\] "(.*?)" (\d+) - "(.*?)" "(.*?)"' import re print re.match(regex, line).groups() </code></pre> <p>The output would be a tuple with 6 pieces of information</p> <pre><code>('172.16.0.3', '25/Sep/2002:14:04:19 +0200', 'GET / HTTP/1.1', '401', '', 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.1) Gecko/20020827') </code></pre>
1
2016-08-17T15:12:58Z
[ "python", "python-3.x", "csv" ]
converting time into seconds+mili seconds
39,000,429
<p>I have a .csv file which contains a column "Time" which comprises of data in the format "01/02/2016 08:01:29;12", So now I want to separate this into two columns. Can anyone suggest me how to do that in python. </p> <p>I am successfull in splitting the columns, but now i want to convert the time part(08:01:29;12) into seconds. I have written a function but it seems its not working, please help!</p> <p>def time_convert(x): times = x.split(':') time = x.split(";") return (60*int(times[0])+60*int(times[1]))+int(times[2])+int(time[3])</p>
0
2016-08-17T15:13:26Z
39,000,717
<p>Assuming that ";12" in your date are microseconds, and that you want to separate date and time into two columns (if I understood correctly) it would be the best to convert str to datetime:</p> <pre><code>data = "01/02/2016 08:01:29;12" actual_date = datetime.datetime.strptime(data, "%d/%m/%Y %H:%M:%S;%f") </code></pre> <p>and then you can access both date and time part of that datetime object.</p>
1
2016-08-17T15:28:02Z
[ "python", "pandas" ]
Let printed lines disapear in python
39,000,491
<p>How can I tell my program to delete the previous text if <kbd>Enter</kbd> was pressed?</p> <pre><code>print('Information: \n ' ) input('Press Enter to continue.') </code></pre> <p>So if the user read the Info and presses <kbd>Enter</kbd> the text above still remains. </p> <p>How can I remove it?</p>
0
2016-08-17T15:16:37Z
39,000,621
<p>Following script can clear your screen</p> <pre><code>import subprocess as sp sp.call('cls',shell=True) </code></pre>
0
2016-08-17T15:22:49Z
[ "python" ]
Custome delimiter file upload using pyspark function not working
39,000,674
<p>I am using below function to upload custom delimiter file.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>from pyspark.sql.types import * from pyspark.sql import * def loadFile(path, rowDelimeter, columnDelimeter, firstHeaderColName): loadedFile = sc.newAPIHadoopFile(path, "org.apache.hadoop.mapreduce.lib.input.TextInputFormat", "org.apache.hadoop.io.LongWritable", "org.apache.hadoop.io.Text", conf={"textinputformat.record.delimiter": rowDelimeter}) rddData = loadedFile.map(lambda l:l[1].split(columnDelimeter)).filter(lambda f: f[0] != firstHeaderColName) return rddData</code></pre> </div> </div> </p> <p>I called the function below.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>from pyspark.sql.types import * from pyspark.sql import * Schema = StructType([ StructField("FlightID", StringType(), True), StructField("Flightname", StringType(), True), StructField("FlightNo", StringType(), True), StructField("Depaturetime", StringType(), True), StructField("ArrivalTime", StringType(), True), StructField("FromPlace", StringType(), True), StructField("ToPlace", StringType(), True), StructField("Cremember", StringType(), True) ]) Data= loadFile("wasb://Accountnumber@serviceaccount.blob.core.windows.net/Flightdetails.txt", "\r\n","#|#","FlightID") FlightDF = sqlContext.createDataFrame(Data,Schema ) FlightDF.write.saveAsTable("Flightdetail")</code></pre> </div> </div> </p> <p>Source file size is 2GB, the process keeps on running. table is not creating in Azure.</p> <p>What wrong am I doing?</p>
1
2016-08-17T15:25:55Z
39,089,894
<p>Would recommend trying with a smaller dataset or couple of rows. 2 GB data-file may have some data anomalies which may be causing this issue.</p>
0
2016-08-22T22:52:09Z
[ "python", "apache-spark", "pyspark", "windows-azure-storage", "spark-dataframe" ]
Find the sum of values within the values of a nested Dictionary
39,000,681
<p>This is a question based on <em>nested</em> dictionaries.</p> <p>We are given a nested dictionary wherein in the outer dictionary, the name of the match is mentioned and the value for the matches is another dictionary with it's key and values respectively and the name of the function is <code>orangecap(d)</code> which accepts a dictionary in the below format.</p> <p>Here's the sample.</p> <pre><code>d = {'match1':{'player1':57, 'player2':38}, 'match2':{'player3':9, 'player1':42}, 'match3':{'player2':41, 'player4':63, 'player3':91}} </code></pre> <p>So I would like to search by the player key and calculate the total sum for each player and return the largest sum.</p> <p>So the output needs to be <code>('player3', 100)</code></p> <p>This is what i have tried so far but to no avail:</p> <pre><code>def orangecap(d): total=0 for key,value in d.items(): for value in d.items(): if d[key] in d.keys(): total = total+d[value] return(d[key],max(total)) </code></pre>
2
2016-08-17T15:26:12Z
39,000,852
<p>Something like this should work:</p> <pre><code>def orangecap(d): players = {} for match, scores in d.iteritems(): for player, score in scores.iteritems(): if player not in players: players[player] = score else: players[player] += score return sorted(players.items(), key=lambda x: x[1])[-1] </code></pre> <p>This creates a dictionary (<code>players</code>) containing the player's total score. Then it sorts the items from the dictionary using the score and returns the highest.</p>
1
2016-08-17T15:35:24Z
[ "python", "dictionary" ]
Find the sum of values within the values of a nested Dictionary
39,000,681
<p>This is a question based on <em>nested</em> dictionaries.</p> <p>We are given a nested dictionary wherein in the outer dictionary, the name of the match is mentioned and the value for the matches is another dictionary with it's key and values respectively and the name of the function is <code>orangecap(d)</code> which accepts a dictionary in the below format.</p> <p>Here's the sample.</p> <pre><code>d = {'match1':{'player1':57, 'player2':38}, 'match2':{'player3':9, 'player1':42}, 'match3':{'player2':41, 'player4':63, 'player3':91}} </code></pre> <p>So I would like to search by the player key and calculate the total sum for each player and return the largest sum.</p> <p>So the output needs to be <code>('player3', 100)</code></p> <p>This is what i have tried so far but to no avail:</p> <pre><code>def orangecap(d): total=0 for key,value in d.items(): for value in d.items(): if d[key] in d.keys(): total = total+d[value] return(d[key],max(total)) </code></pre>
2
2016-08-17T15:26:12Z
39,000,892
<p>Here's a possible solution:</p> <pre><code>from collections import defaultdict data = { 'match1': {'player1': 57, 'player2': 38}, 'match2': {'player3': 9, 'player1': 42}, 'match3': {'player2': 41, 'player4': 63, 'player3': 91} } def orangecap(d): result = defaultdict(int) for k, v in data.items(): for k1, v1 in v.items(): result[k1] += v1 return sorted(result.items(), key=lambda x: x[1])[-1] print(orangecap(data)) </code></pre>
0
2016-08-17T15:37:36Z
[ "python", "dictionary" ]
Find the sum of values within the values of a nested Dictionary
39,000,681
<p>This is a question based on <em>nested</em> dictionaries.</p> <p>We are given a nested dictionary wherein in the outer dictionary, the name of the match is mentioned and the value for the matches is another dictionary with it's key and values respectively and the name of the function is <code>orangecap(d)</code> which accepts a dictionary in the below format.</p> <p>Here's the sample.</p> <pre><code>d = {'match1':{'player1':57, 'player2':38}, 'match2':{'player3':9, 'player1':42}, 'match3':{'player2':41, 'player4':63, 'player3':91}} </code></pre> <p>So I would like to search by the player key and calculate the total sum for each player and return the largest sum.</p> <p>So the output needs to be <code>('player3', 100)</code></p> <p>This is what i have tried so far but to no avail:</p> <pre><code>def orangecap(d): total=0 for key,value in d.items(): for value in d.items(): if d[key] in d.keys(): total = total+d[value] return(d[key],max(total)) </code></pre>
2
2016-08-17T15:26:12Z
39,001,012
<p>This is a slightly modified answer taken from a <em>previous</em> answer of <strong><a href="http://stackoverflow.com/a/38959235/6320655">mine</a></strong>.</p> <pre><code>def find_totals(d): total = {} for match, results in d.items(): for player, score in results.items(): total[player] = total.get(player, 0) + score highest_score = max(total, key=total.get) return highest_score, total[highest_score] </code></pre> <p><strong>Sample output:</strong></p> <pre><code>&gt;&gt;&gt; d = {'match1':{'player1':57, 'player2':38}, 'match2':{'player3':9, 'player1':42}, 'match3':{'player2':41, 'player4':63, 'player3':91}} &gt;&gt;&gt; print find_totals(d) ('player3', 100) </code></pre> <hr> <p>So what's going on with your code?, Let's examine the algorithm:</p> <p>Firstly, you iterate through the items (<em>keys/values</em>) of <code>d</code>. This is fine, as you're trying to traverse a nested dictionary structure. However instead of traversing the inner most structure using the second <code>for</code> loop (<em>iterating over</em> <code>value</code><em>, instead of</em> <code>d</code>), you instead traverse <code>d</code> again. </p> <p><code>value</code> is now simply a <em>tuple</em> of <strong>key/value</strong> stores in <code>d</code>, rather than the nested dictionary. <code>d[key]</code> is simply the value mapped to the match keys. So how then could a <code>value</code> be in the list of keys -> <code>d.keys()</code> Your <code>if</code> condition never evaluates to <code>true</code>. Despite this, you end up <strong>short-circuiting</strong> the entire iteration to the <code>return</code> statement after only <em>two</em> iterations. Which neither returns the correct player (<code>d[key]</code> <em>is the nested dictionary</em>), and <a href="https://docs.python.org/2/library/functions.html#max" rel="nofollow"><code>max</code></a> takes an iterable argument, not an int.</p> <p>You should learn more about basic control flow, data structures, and algorithm design. I would suggest Google's excellent <em><a href="https://developers.google.com/edu/python/" rel="nofollow">python series</a></em>.</p>
4
2016-08-17T15:43:37Z
[ "python", "dictionary" ]
Find the sum of values within the values of a nested Dictionary
39,000,681
<p>This is a question based on <em>nested</em> dictionaries.</p> <p>We are given a nested dictionary wherein in the outer dictionary, the name of the match is mentioned and the value for the matches is another dictionary with it's key and values respectively and the name of the function is <code>orangecap(d)</code> which accepts a dictionary in the below format.</p> <p>Here's the sample.</p> <pre><code>d = {'match1':{'player1':57, 'player2':38}, 'match2':{'player3':9, 'player1':42}, 'match3':{'player2':41, 'player4':63, 'player3':91}} </code></pre> <p>So I would like to search by the player key and calculate the total sum for each player and return the largest sum.</p> <p>So the output needs to be <code>('player3', 100)</code></p> <p>This is what i have tried so far but to no avail:</p> <pre><code>def orangecap(d): total=0 for key,value in d.items(): for value in d.items(): if d[key] in d.keys(): total = total+d[value] return(d[key],max(total)) </code></pre>
2
2016-08-17T15:26:12Z
39,002,265
<p>Because someone had to do it... Here's a one-liner. </p> <p>EDIT: no longer a one liner because I realised the player was also meant to be returned. So it's now a one-liner in a function.</p> <pre><code>def total_score(*, match_results: dict, player_name: str): return player_name, sum(score for player_scores in match_results.values() for player, score in player_scores.items() if player == player_name) </code></pre>
0
2016-08-17T16:51:07Z
[ "python", "dictionary" ]
Python Simple Class not Recognized
39,000,686
<pre><code>class Example: values=None s1=Example s1.values.append(1) s1.values.append(2) for x in s1.values: print x </code></pre> <p>Using Python 2.7</p> <p>Output:</p> <pre><code>line 8, in Example s1=Example NameError: name 'Example' is not defined enter code here </code></pre> <p>New to python and not sure why it's not recognizing the simple class. </p>
-3
2016-08-17T15:26:26Z
39,001,148
<p>Here's a working example for you:</p> <pre><code>class Example: def __init__(self): self.values = [] s1 = Example() s1.values.append(1) s1.values.append(2) for x in s1.values: print x </code></pre> <p>Also, I'd recommend you to follow some available <a href="https://docs.python.org/2/tutorial/" rel="nofollow">python tutorial</a> out there</p>
2
2016-08-17T15:50:03Z
[ "python" ]
split list by delimited in python
39,000,718
<p>From a dict/list, how to split the list by \n. Eg:</p> <pre><code>In [1]: d = {'key1': 'value1\n value2 \n value3\n'} In [2]: d.values() Out[2]: ['value1\n value2 \n value3\n'] </code></pre> <p>Desired output:</p> <pre><code>['value1', 'value2 ', 'value3'] </code></pre> <p>I looked at existing examples but couldn't find this specific one.</p>
-4
2016-08-17T15:28:07Z
39,000,781
<p>Here you go:</p> <pre><code>d['key1'].split('\n') </code></pre>
0
2016-08-17T15:31:20Z
[ "python", "list", "split" ]
split list by delimited in python
39,000,718
<p>From a dict/list, how to split the list by \n. Eg:</p> <pre><code>In [1]: d = {'key1': 'value1\n value2 \n value3\n'} In [2]: d.values() Out[2]: ['value1\n value2 \n value3\n'] </code></pre> <p>Desired output:</p> <pre><code>['value1', 'value2 ', 'value3'] </code></pre> <p>I looked at existing examples but couldn't find this specific one.</p>
-4
2016-08-17T15:28:07Z
39,000,881
<p>You mean you want the values as a flat list? Something like this?</p> <pre><code>&gt;&gt;&gt; {k: [x.strip() for x in v.splitlines()] for k, v in d.iteritems()} {'key1': ['value1', 'value2', 'value3']} </code></pre>
0
2016-08-17T15:36:56Z
[ "python", "list", "split" ]
split list by delimited in python
39,000,718
<p>From a dict/list, how to split the list by \n. Eg:</p> <pre><code>In [1]: d = {'key1': 'value1\n value2 \n value3\n'} In [2]: d.values() Out[2]: ['value1\n value2 \n value3\n'] </code></pre> <p>Desired output:</p> <pre><code>['value1', 'value2 ', 'value3'] </code></pre> <p>I looked at existing examples but couldn't find this specific one.</p>
-4
2016-08-17T15:28:07Z
39,001,086
<p><strong>Python 2.x</strong></p> <pre><code>d = {'key1': 'value1\n value2 \n value3\n'} print {k: [x.strip() for x in v.splitlines()] for k, v in d.iteritems()} </code></pre> <p><strong>Python 3.x</strong></p> <pre><code>d = {'key1': 'value1\n value2 \n value3\n'} print({k: [x.strip() for x in v.splitlines()] for k, v in d.items()}) </code></pre>
0
2016-08-17T15:47:01Z
[ "python", "list", "split" ]
Why Django generate new migrations file each time I use `makemigrations` command. For ImageFIeld with changed upload_path attribute
39,000,797
<p>I need to get ImageField name in <code>upload_path</code> function.<br> I tried use <code>partial</code> in ImageField definition: </p> <pre><code>class MyModel(models.Model): image = models.ImageField( upload_to=partial(image_upload_path, 'image') ) </code></pre> <p>Now I can get that string by first argument of function: </p> <pre><code>def image_upload_path(field, instance, filename): .... </code></pre> <p>All works fine, but now Django generate migration file, each time I use <code>makemigrations</code>, with same <code>operations</code> list in it: </p> <pre><code>operations = [ migrations.AlterField( model_name='genericimage', name='image', field=core_apps.generic_image.fields.SorlImageField(upload_to=functools.partial(core_apps.generic_image.path.image_upload_path, *('image',), **{}),), ), ] </code></pre> <p>Maybe there is another way to access Field name in <code>upload_path</code> function or somehow I can fix my solution? </p>
0
2016-08-17T15:31:50Z
39,002,452
<p>It seems like you don't need to provide a partial in this case, but just a callable with two parameters like in <a href="https://docs.djangoproject.com/en/1.9/ref/models/fields/#django.db.models.FileField.upload_to" rel="nofollow">this example</a> in the Django documentation.</p> <p>Django will invoke the callable you provide in the <code>upload_to</code> argument with 2 parameters (<code>instance</code> and <code>filename</code>).</p> <p><code>instance</code>:</p> <blockquote> <p>An instance of the model where the FileField is defined. More specifically, this is the <strong>particular instance where the current file is being attached</strong>.</p> </blockquote> <p>This means you can access the <code>name</code> field of the instance like <code>instance.name</code> in the callable you write:</p> <pre><code>class MyModel(models.Model): name = models.CharField(max_length=255) image = models.ImageField(upload_to=image_upload_path) def image_upload_path(instance, filename): # Access the value of the `name` field # of the MyModel instance passed in and save it to a variable: name = instance.name # Code that returns a Unix-style path (with forward slashes) goes here </code></pre>
1
2016-08-17T17:02:21Z
[ "python", "django", "django-models" ]
Why Django generate new migrations file each time I use `makemigrations` command. For ImageFIeld with changed upload_path attribute
39,000,797
<p>I need to get ImageField name in <code>upload_path</code> function.<br> I tried use <code>partial</code> in ImageField definition: </p> <pre><code>class MyModel(models.Model): image = models.ImageField( upload_to=partial(image_upload_path, 'image') ) </code></pre> <p>Now I can get that string by first argument of function: </p> <pre><code>def image_upload_path(field, instance, filename): .... </code></pre> <p>All works fine, but now Django generate migration file, each time I use <code>makemigrations</code>, with same <code>operations</code> list in it: </p> <pre><code>operations = [ migrations.AlterField( model_name='genericimage', name='image', field=core_apps.generic_image.fields.SorlImageField(upload_to=functools.partial(core_apps.generic_image.path.image_upload_path, *('image',), **{}),), ), ] </code></pre> <p>Maybe there is another way to access Field name in <code>upload_path</code> function or somehow I can fix my solution? </p>
0
2016-08-17T15:31:50Z
39,078,879
<p>I decide to build my own field: </p> <pre><code>class SorlImageField(ImageField): def __init__(self, verbose_name=None, name=None, width_field=None, height_field=None, lookup_name=None, **kwargs): self.lookup_name = lookup_name kwargs['upload_to'] = partial(image_upload_path, lookup_name) super(SorlImageField, self).__init__(verbose_name, name, width_field, height_field, **kwargs) def deconstruct(self): name, path, args, kwargs = super(SorlImageField, self).deconstruct() del kwargs['upload_to'] # del upload_to will solve migration issue return name, path, args, kwargs def check(self, **kwargs): errors = super(SorlImageField, self).check(**kwargs) if self.lookup_name != self.name: error = [ checks.Error( 'SorlImageField lookup_name must be equal to ' 'field name, now it is: "{}"'.format(self.lookup_name), hint='Add lookup_name in SorlImageField', obj=self, id='fields.E210', )] errors.extend(error) return errors </code></pre> <p>Problem with migration was solved in <code>deconstruct</code> method, by deleting <code>upload_to</code> argument. Also I add additional argument into <code>__init__</code> which point to field name, <code>check</code> function check for correct <code>lookup_name</code> value. If it not, it will raise an error when migrations starts. </p> <pre><code>class MyModel(models.Model): image = SorlImageField( lookup_name='image' ) </code></pre>
0
2016-08-22T11:53:42Z
[ "python", "django", "django-models" ]
Modify a DBF file
39,000,886
<p>I want to modify one column in a .dpf file using Python with this library <a href="http://pythonhosted.org/dbf/" rel="nofollow">http://pythonhosted.org/dbf/</a>. <br>When I want to print out some column, it works just fine. But when I am trying to modify a column, I get error </p> <blockquote> <p>unable to modify fields individually except in <code>with</code> or <code>Process()</code></p> </blockquote> <p>My code: </p> <pre><code>table = dbf.Table('./path/to/file.dbf') table.open() for record in table: record.izo = sys.argv[2] table.close() </code></pre> <p>In docs, they recommend doing it like </p> <pre><code>for record in Write(table): </code></pre> <p>But I also get an error: </p> <blockquote> <p>name 'Write' is not defined And:</p> </blockquote> <pre><code>record.write_record(column=sys.argv[2]) </code></pre> <p>Also gives me an error that </p> <blockquote> <p>write_record - no such field in table</p> </blockquote> <p>Thanks!</p>
1
2016-08-17T15:37:20Z
39,021,399
<p>My apologies for the state of the docs. Here are a couple options that should work:</p> <pre><code>table = dbf.Table('./path/to/file.dbf') # Process will open and close a table if not already opened for record in dbf.Process(table): record.izo = sys.argv[2] </code></pre> <p>or</p> <pre><code>with dbf.Table('./path/to/file.dbf') # with opens a table, closes when done for record in table: with record: record.izo = sys.argv[2] </code></pre>
1
2016-08-18T14:54:15Z
[ "python" ]
pandas column selection: non commutative bitwise OR when selecting on str and NaN
39,000,907
<h3>Introduction:</h3> <p>Given a dataframe, I though that the following were True:</p> <pre><code>df[(condition_1) | (condition_2)] &lt;=&gt; df[(condition_2) | (condition_1)] </code></pre> <p>as in </p> <pre><code>df[(df.col1==1) | (df.col1==2)] &lt;=&gt; df[(df.col1==2) | (df.col1==1)] </code></pre> <h3>Problem:</h3> <p>But it turns out that it fails in the following situation, where it involves <code>NaN</code> which is probably the reason why it fails:</p> <pre><code>df = pd.DataFrame([[np.nan, "abc", 2], ["abc", 2, 3], [np.nan, 5,6], [8,9,10]], columns=["A", "B", "C"]) df A B C 0 NaN abc 2 1 abc 2 3 2 NaN 5 6 3 8 9 10 </code></pre> <p>The following works as expected:</p> <pre><code>df[(df.A.isnull()) | (df.A.str.startswith("a"))] A B C 0 NaN abc 2 1 abc 2 3 2 NaN 5 6 </code></pre> <p>But if I commute the elements, I get a different result:</p> <pre><code>df[(df.A.str.startswith("a")) | (df.A.isnull())] A B C 1 abc 2 3 </code></pre> <p>I think that the problems comes from this condition:</p> <pre><code>df.A.str.startswith("a") 0 NaN 1 True 2 NaN 3 NaN Name: A, dtype: object </code></pre> <p>Where I have <code>NaN</code> instead of <code>False</code>.</p> <h3>Questions:</h3> <ul> <li>Is this behavior expected? Is it a bug ? Because it can lead <em>to potential loss of data</em> if one is not expecting this kind of behavior.</li> <li>Why it behaves like this (in a non commutative way) ?</li> </ul> <hr> <h3>More details:</h3> <p>More precisely, let's <code>C1 = (df.A.str.startswith("a"))</code> and <code>C2 = (df.A.isnull())</code>:</p> <p>with:</p> <pre><code> C1 C2 NaN True True False NaN True NaN False </code></pre> <p>We have:</p> <pre><code>C1 | C2 0 False 1 True 2 False 3 False Name: A, dtype: bool </code></pre> <p>Here C2 is not evaluated, and NaN becomes False.</p> <p>And here:</p> <pre><code>C2 | C1 0 True 1 True 2 True 3 False Name: A, dtype: bool </code></pre> <p>Where NaN is False (it returns all False with an <code>&amp;</code>) but both conditions are evaluated.</p> <p>Clearly: <code>C1 | C2 != C2 | C1</code></p> <p>I wouldn't mind that <code>NaN</code> produce weird results as long as the commutativity is preserved, but here there is one condition that is not evaluated. </p> <p>Actually the NaN in the input isn't the problem, because you have the same problem on column <code>B</code>:</p> <pre><code>(df.B.str.startswith("a")) | (df.B==2) != (df.B==2) | (df.B.str.startswith("a")) </code></pre> <p>It's because applying <code>str</code> method on other objects returns <code>NaN</code>*, which if evaluated first prevents the second condition to be evaluated. So the main problem remains.</p> <p>*(can be chosen with <code>str.startswith("a", na=False)</code> as @ayhan noticed)</p>
3
2016-08-17T15:38:26Z
39,038,706
<p>After some research, I am rather sure that this is a bug in <code>pandas</code>. I was not able to find the specific reason in their code but my conclusion is that either you should be forbidden to do the comparison at all or there is a bug in evaluating the <code>|</code> expression. You can reproduce the problem with a very simple example, namely:</p> <pre><code>import numpy as np import pandas as pd a = pd.Series(np.nan) b = pd.Series(True) print( a | b ) # Gives False print( b | a ) # Gives True </code></pre> <p>The second result is obviously the correct one. I can only guess the reason, why the first one fails, due to my lack of understanding <code>pandas</code> code base. So if I am mistaken, please correct me or if you feel this is not enough of an answer, please let me know.</p> <p>Generally, <code>np.nan</code> is treated as <code>True</code> all throughout python, as you can easily check:</p> <pre><code>import numpy as np if np.nan: print("I am True") </code></pre> <p>This is valid in <code>numpy</code> and even <code>pandas</code> as well, as you can see by doing:</p> <pre><code>import numpy as np import pandas as pd if np.all(np.array([np.nan])): print("I am True in numpy") if pd.Series(np.nan).astype("bool").bool(): print("and in pandas") </code></pre> <p>or by simply doing <code>pd.Series([np.nan]).astype("bool")</code>.</p> <p>So far everything is consistent. The problem now arises when you do <code>|</code> with a <code>Series</code> containing <code>NaN</code>s. There are multiple other people with similar problems, as for example in this <a href="https://stackoverflow.com/questions/37131462/comparing-logical-values-to-nan-in-pandas-numpy">question</a> or that <a href="https://unsupervised.blogs.balabit.com/2016/05/comparing-logical-arrays-in-numpypandas/" rel="nofollow">blog post</a> (which is for an older version, though). And none give a satisfactory answer to the problem. The only answer to the linked question actually gives no good reason, as <code>|</code> does not even behave the same way as it would for <code>numpy</code> arrays containing the same information. For numpy, <code>np.array(np.nan) | np.array(True)</code> and <code>np.array(np.nan) | np.array(1.0)</code> actually give a <code>TypeError</code> as <code>np.bitwise_or</code> is not able to work on floats.</p> <p>Due to the inconsistent behavior and the lack of any documentation on this, I can only conclude that this is a bug. As a workaround you can fall back to the solution proposed by @ayhan and use the <code>na</code> parameter, if that exists for all functions that you need. You could also use <code>.astype("bool")</code> on the <code>Series</code>/<code>Dataframe</code> that you want to compare. Note however, that this will convert <code>NaN</code> to <code>True</code> as this is the usual <code>python</code> convention (see this <a href="http://stackoverflow.com/a/15686477/6614295">answer</a> for example). If you want to avoid that, you can use <code>.fillna(False).astype("bool")</code>, which I found <a href="https://groups.google.com/forum/#!topic/pydata/U7gQyI_gLMc" rel="nofollow">here</a>. Generally, one should probably file a bug report with pandas, as this behavior is obviously inconsistent!</p>
1
2016-08-19T12:07:05Z
[ "python", "pandas" ]
Extracting information using XPaths
39,000,988
<p>Good afternoon dear community,</p> <p>I have finally compiled a list of working XPaths required to scrape all of the information from URL's that i need.</p> <p>I would like to ask for your suggestion, for a newbie in coding what is the best way to scrape around 50k links using only XPaths (around 100 xpaths for each link)? </p> <p>Import.io is my best tool at the moment, or even SEO tools for Excel, but they both have their own limitations. Import io is expensive, SEO tools for excel isn't suited to extract more than 1000 links.</p> <p>I am willing to learn the system suggested, but please suggest a good way of scraping for my project!</p> # <p>SOLVED! SEO Tools crawler is actually super usefull and I believe I've found what i need. I guess i'll hold off Python or Java until i encounter another tough obstacle. Thank you all!</p>
-2
2016-08-17T15:42:37Z
39,001,165
<p>That strongly depends on what you mean by "scraping information". What exactly do you want to mine from the websites? All major languages (certainly Java and Python that you mentioned) have good solutions for connecting to websites, reading content, parsing HTML using a DOM and using XPath to extract certain fragments. For example, Java has <a href="http://jtidy.sourceforge.net/" rel="nofollow" title="JTidy">JTidy</a>, which allows you to parse even "dirty" HTML from websites into a DOM and manipulate it somewhat. However, the tools needed will depend on the exact data processing needs of your project.</p>
1
2016-08-17T15:50:59Z
[ "java", "python", "xml", "xpath", "import.io" ]
Extracting information using XPaths
39,000,988
<p>Good afternoon dear community,</p> <p>I have finally compiled a list of working XPaths required to scrape all of the information from URL's that i need.</p> <p>I would like to ask for your suggestion, for a newbie in coding what is the best way to scrape around 50k links using only XPaths (around 100 xpaths for each link)? </p> <p>Import.io is my best tool at the moment, or even SEO tools for Excel, but they both have their own limitations. Import io is expensive, SEO tools for excel isn't suited to extract more than 1000 links.</p> <p>I am willing to learn the system suggested, but please suggest a good way of scraping for my project!</p> # <p>SOLVED! SEO Tools crawler is actually super usefull and I believe I've found what i need. I guess i'll hold off Python or Java until i encounter another tough obstacle. Thank you all!</p>
-2
2016-08-17T15:42:37Z
39,001,191
<p>I would encourage you to use Python (I use 2.7.x) w/ Selenium. I routinely automate scraping and testing of websites with this combo (in both a headed and headless manner), and Selenium unlocks the opportunity to interact with scripted sites that do not have explicit webcalls for each and every page. </p> <p>Here is a good, quick tutorial from the Selenium docs: <a href="http://selenium-python.readthedocs.io/getting-started.html" rel="nofollow">2. Getting Started</a></p> <p>There are a lot of great sources out there, and it would take forever to post them all; but, you will find the Python community very helpful and you'll likely see that Python is a great language for this type of web interaction.</p> <p>Good luck!</p>
1
2016-08-17T15:52:01Z
[ "java", "python", "xml", "xpath", "import.io" ]
match changes by words, not by characters
39,001,097
<p>I'm using <code>difflib</code>'s <code>SequenceMatcher</code> to <code>get_opcodes()</code> and than highlight the changes with <code>css</code> to create some kind of web <code>diff</code>.</p> <p>First, I set a <code>min_delta</code> so that I consider two strings different if only 3 or more characters in the whole string differ, one after another (<code>delta</code> means a real, encountered delta, which sums up all one-character changes):</p> <pre class="lang-py prettyprint-override"><code>matcher = SequenceMatcher(source_str, diff_str) min_delta = 3 delta = 0 for tag, i1, i2, j1, j2 in matcher.get_opcodes(): if tag == "equal": continue # nothing to capture here elif tag == "delete": if source_str[i1:i2].isspace(): continue # be whitespace-agnostic else: delta += (i2 - i1) # delete i2-i1 chars elif tag == "replace": if source_str[i1:i2].isspace() or diff_str[j1:j2].isspace(): continue # be whitespace-agnostic else: delta += (i2 - i1) # replace i2-i1 chars elif tag == "insert": if diff_str[j1:j2].isspace(): continue # be whitespace-agnostic else: delta += (j2 - j1) # insert j2-j1 chars return_value = True if (delta &gt; min_delta) else False </code></pre> <p>This helps me to determine, if two strings really differ. Not very efficient, but I didn't think anything better out.</p> <p>Then, I colorize the differences between two strings in the same way:</p> <pre class="lang-py prettyprint-override"><code>for tag, i1, i2, j1, j2 in matcher.get_opcodes(): if tag == "equal": # bustling with strings, inserting them in &lt;span&gt;s and colorizing elif tag == "delete": # ... return_value = old_string, new_string </code></pre> <p>And the result looks pretty ugly (blue for replaced, green for new and red for deleted, nothing for equal):</p> <p><a href="http://i.stack.imgur.com/bFdyS.png" rel="nofollow"><img src="http://i.stack.imgur.com/bFdyS.png" alt="example"></a></p> <p><strong>So</strong>, this is happening because <code>SequenceMatcher</code> matches <em>every single character</em>. But I want for it to match <em>every single word</em> instead (and probably whitespaces around them), or something even more eye-candy because as you can see on the screenshot, the first book is actually moved on the fourth position.</p> <p>It seems to me that something could be done with <code>isjunk</code> and <code>autojunk</code> parameters of <code>SequenceMatcher</code>, but I can't figure out how to write <code>lambda</code>s for my purposes.</p> <p>Thus, I have two <strong>questions</strong>:</p> <ol> <li><p>Is it possible to match by words? Is it possible to do using <code>get_opcodes()</code> and <code>SequenceMatcher</code>? If not, what could by used instead?</p></li> <li><p>Okay, this is rather a corollary, but nevertheless: if matching by words is possible, then I can get rid of the dirty hacks with <code>min_delta</code> and return <code>True</code> as soon as at least one word differs, right?</p></li> </ol>
1
2016-08-17T15:47:36Z
39,075,165
<p><code>SequenceMatcher</code> can accept lists of <code>str</code> as input.</p> <p>You can first split the input into words, and then use <code>SequenceMatcher</code> to help you diff words. Then your colored diff would be <em>by words</em> instead of <em>by characters</em>.</p> <pre><code>&gt;&gt;&gt; def my_get_opcodes(a, b): ... s = SequenceMatcher(None, a, b) ... for tag, i1, i2, j1, j2 in s.get_opcodes(): ... print('{:7} a[{}:{}] --&gt; b[{}:{}] {!r:&gt;8} --&gt; {!r}'.format( ... tag, i1, i2, j1, j2, a[i1:i2], b[j1:j2])) ... &gt;&gt;&gt; my_get_opcodes("qabxcd", "abycdf") delete a[0:1] --&gt; b[0:0] 'q' --&gt; '' equal a[1:3] --&gt; b[0:2] 'ab' --&gt; 'ab' replace a[3:4] --&gt; b[2:3] 'x' --&gt; 'y' equal a[4:6] --&gt; b[3:5] 'cd' --&gt; 'cd' insert a[6:6] --&gt; b[5:6] '' --&gt; 'f' # This is the bad result you currently have. &gt;&gt;&gt; my_get_opcodes("one two three\n", "ore tree emu\n") equal a[0:1] --&gt; b[0:1] 'o' --&gt; 'o' replace a[1:2] --&gt; b[1:2] 'n' --&gt; 'r' equal a[2:5] --&gt; b[2:5] 'e t' --&gt; 'e t' delete a[5:10] --&gt; b[5:5] 'wo th' --&gt; '' equal a[10:13] --&gt; b[5:8] 'ree' --&gt; 'ree' insert a[13:13] --&gt; b[8:12] '' --&gt; ' emu' equal a[13:14] --&gt; b[12:13] '\n' --&gt; '\n' &gt;&gt;&gt; my_get_opcodes("one two three\n".split(), "ore tree emu\n".split()) replace a[0:3] --&gt; b[0:3] ['one', 'two', 'three'] --&gt; ['ore', 'tree', 'emu'] # This may be the result you want. &gt;&gt;&gt; my_get_opcodes("one two emily three ha\n".split(), "ore tree emily emu haha\n".split()) replace a[0:2] --&gt; b[0:2] ['one', 'two'] --&gt; ['ore', 'tree'] equal a[2:3] --&gt; b[2:3] ['emily'] --&gt; ['emily'] replace a[3:5] --&gt; b[3:5] ['three', 'ha'] --&gt; ['emu', 'haha'] # A more complicated example exhibiting all four kinds of opcodes. &gt;&gt;&gt; my_get_opcodes("one two emily three yo right end\n".split(), "ore tree emily emu haha yo yes right\n".split()) replace a[0:2] --&gt; b[0:2] ['one', 'two'] --&gt; ['ore', 'tree'] equal a[2:3] --&gt; b[2:3] ['emily'] --&gt; ['emily'] replace a[3:4] --&gt; b[3:5] ['three'] --&gt; ['emu', 'haha'] equal a[4:5] --&gt; b[5:6] ['yo'] --&gt; ['yo'] insert a[5:5] --&gt; b[6:7] [] --&gt; ['yes'] equal a[5:6] --&gt; b[7:8] ['right'] --&gt; ['right'] delete a[6:7] --&gt; b[8:8] ['end'] --&gt; [] </code></pre> <p>You can also diff <em>by line</em>, <em>by book</em>, or <em>by segments</em>. You only need to prepare a function that can preprocess the whole passage string into desired diff chunks.</p> <p>For example:</p> <ul> <li>To diff <em>by line</em> - You probably could use <code>splitlines()</code></li> <li>To diff <em>by book</em> - You probably could implement a function that strips off the <code>1.</code>, <code>2.</code></li> <li>To diff <em>by segments</em> - You could throw in the API like this way <code>([book_1, author_1, year_1, book_2, author_2, ...], [book_1, author_1, year_1, book_2, author_2, ...])</code>. And then your coloring would be <em>by segment</em>.</li> </ul>
2
2016-08-22T08:57:08Z
[ "python", "string", "python-3.x", "diff", "difflib" ]
In Keras, If samples_per_epoch is less than the 'end' of the generator when it (loops back on itself) will this negatively affect result?
39,001,104
<p>I'm using Keras with Theano to train a basic logistic regression model.</p> <p>Say I've got a training set of 1 million entries, it's too large for my system to use the standard <code>model.fit()</code> without blowing away memory.</p> <ul> <li>I decide to use a python generator function and fit my model using <code>model.fit_generator()</code>. </li> <li>My generator function returns batch sized chunks of the 1M training examples (they come from a DB table, so I only pull enough records at a time to satisfy each batch request, keeping memory usage in check). </li> <li>It's an endlessly looping generator, once it reaches the end of the 1 million, it loops and continues over the set</li> </ul> <p>There is a mandatory argument in <code>fit_generator()</code> to specify <code>samples_per_epoch</code>. The documentation indicates</p> <blockquote> <p><strong>samples_per_epoch:</strong> integer, number of samples to process before going to the next epoch.</p> </blockquote> <p>I'm assuming the <code>fit_generator()</code> doesn't reset the generator each time an epoch runs, hence the need for a infinitely running generator.</p> <p>I typically set the <code>samples_per_epoch</code> to be the size of the training set the generator is looping over.</p> <p>However, if <code>samples_per_epoch</code> this is smaller than the size of the training set the generator is working from and the <code>nb_epoch</code> > 1:</p> <ul> <li>Will you get odd/adverse/unexpected training resulting as it seems the epochs will have differing sets training examples to fit to?</li> <li>If so, do you 'fastforward' you generator somehow?</li> </ul>
0
2016-08-17T15:48:03Z
39,093,328
<p>I'm dealing some something similar right now. I want to make my epochs shorter so I can record more information about the loss or adjust my learning rate more often. </p> <p>Without diving into the code, I think the fact that <code>.fit_generator</code> works with the randomly augmented/shuffled data produced by the keras builtin <code>ImageDataGenerator</code> supports your suspicion that it doesn't reset the generator per epoch. So I believe you should be fine, as long as the model is exposed to your whole training set it shouldn't matter if some of it is trained in a separate epoch.</p> <p>If you're still worried you could try writing a generator that randomly samples your training set.</p>
0
2016-08-23T05:53:41Z
[ "python", "machine-learning", "deep-learning", "theano", "keras" ]
Where can I find a python source file by the import?
39,001,135
<p>There is this line in a python class file, and I am trying to find the python file that defines the PeieApi</p> <pre><code>from peieapi.peieapi import PeieApi </code></pre> <p>I've recursively searched in the project folder for "class PeieApi", didn't find it.</p> <p>I've check the directory where this file is located for any file or directory with the name peieapi, didn't find any.</p> <p>So, where else can I find the source file that defines this python class PeieApi? </p>
0
2016-08-17T15:49:25Z
39,009,498
<p>It was actually installed into this directory by pip when running the project installation script. I saw it showed up from the list returned by this command.</p> <pre><code>pip list </code></pre> <p>Seems if it's not in the project directory, it will be in the global python library directory, in my case on a Mac, it's in </p> <pre><code>/usr/local/lib/python2.7/site-packages/ </code></pre>
0
2016-08-18T03:22:25Z
[ "python", "import" ]
Matplotlib secondary axis with equal aspect ratio
39,001,152
<p>I'm trying to create a secondary axis to an axis with equal aspect ratio using <code>twinx()</code>, however, as can be seen in the example below, the secondary axis does not match the aspect ratio of the original.</p> <p>Is there something additional that needs to be done, or is this a bug in matplotlib?</p> <hr> <p><strong>Code:</strong></p> <pre><code>from matplotlib import pyplot as plt fig = plt.figure() ax1 = fig.add_subplot(111, adjustable='box-forced', aspect='equal') ax2 = ax1.twinx() plt.show() </code></pre> <p><strong>Output figure:</strong></p> <p><a href="http://i.stack.imgur.com/ny6iK.png" rel="nofollow"><img src="http://i.stack.imgur.com/ny6iK.png" alt="matplotlib output"></a></p>
2
2016-08-17T15:50:13Z
39,078,948
<p>Creating the host axis with <code>host_subplot</code> like in the <a href="http://matplotlib.org/mpl_toolkits/axes_grid/users/overview.html#parasiteaxes" rel="nofollow">matplotlib example</a> on parasitic axes instead of <code>fig.add_subplot</code> appears to resolve the issue. The plots now occupy the same space and have equal aspect ratios.</p> <pre><code>from matplotlib import pyplot as plt from mpl_toolkits.axes_grid1 import host_subplot fig = plt.figure() ax1 = host_subplot(111, adjustable='box-forced', aspect='equal') ax2 = ax1.twinx() plt.show() </code></pre> <hr> <p>I was able to achieve the same as above with the object-oriented API used in my actual program by creating the host axis with <code>SubplotHost</code></p> <pre><code>from PyQt5 import QtWidgets from matplotlib.figure import Figure from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas from mpl_toolkits.axes_grid1.parasite_axes import SubplotHost app = QtWidgets.QApplication([]) fig = Figure() ax1 = SubplotHost(fig, 111, adjustable='box-forced', aspect='equal') ax2 = ax1.twinx() fig.add_subplot(ax1) canvas = FigureCanvas(fig) canvas.show() app.exec_() </code></pre>
0
2016-08-22T11:56:43Z
[ "python", "matplotlib" ]
Web Scraping Data to File with Results Separated by Commas
39,001,195
<p>I took a python class last semester and we went over web scraping for about a week. I realized that it can be very helpful in some data entry I'm doing for my job right now but am having troubles figuring it out. I am trying to get all of the model numbers for a part number on <a href="http://servicenet.dewalt.com/Parts/Detail/29730" rel="nofollow">http://servicenet.dewalt.com/Parts/Detail/29730</a> (You have to click on "You can see full list here" to see model numbers). Here is a screenshot of the model numbers <a href="http://i.stack.imgur.com/dVIMe.png" rel="nofollow"><img src="http://i.stack.imgur.com/dVIMe.png" alt="Here is a screenshot of the model numbers"></a>.</p> <p>So far this is what I have but I'm sure I'm way off:</p> <pre><code>from bs4 import BeautifulSoup import requests import uuid import json import os.path from multiprocessing.dummy import Pool as Threadpool ############# # get data for given url ############# def getdata(url): save_path=r'/Users/crazy4byu/PycharmProjects/ServiceNetWebScraping/Data' FitList=[] html = requests.get(url).text soup = BeautifulSoup(html,'html5lib') DW704 = soup.find_all('td',{'class':None}) for item1 in DW704: FitList.append( { 'Model':item1.find('a').text } ) with open(os.path.join(save_path,'data_'+str(uuid.uuid1())+'.json'),'w') as outfile: json.dump(FitList,outfile) ############# # Main ############# if'__main__' == __name__: #makes a list of my urls urls=[] urls.append(r'http://servicenet.dewalt.com/Parts/Detail/29730') pool = Threadpool(25) pool.map(getdata, urls) pool.close() pool.join() </code></pre> <p>In the end I want a text file that will basically be in this format: 110 Type 1, 1301 Type 100, 1317 Type 100, etc. (each model number separated by a comma).</p> <p>Currently, I am getting an error that says "AttributeError: 'NoneType' object has no attribute 'text'" but I'm sure that is not the only problem. I really appreciate your help! Thanks guys!</p>
2
2016-08-17T15:52:11Z
39,001,428
<p>In your <code>get_data</code> function, instead of focusing the on the specific data you're after, you grab <em>all</em> <code>td</code> tags that don't have a class. Instead of doing such a wide search, why not target your data specifically?</p> <p>The list of parts you're after is contained in a <code>table</code> tag. so, search for the first table..</p> <pre><code>import requests from bs4 import BeautifulSoup r = requests.get('http://servicenet.dewalt.com/Parts/Detail/29730') soup = BeautifulSoup(r.content, 'lxml') table = soup.find('table') </code></pre> <p>Then isolate the tags you're after (the <code>tr</code> tags):</p> <pre><code>for tr in table.find_all('tr'): print(tr.text) </code></pre> <p>This gives me an output of:</p> <pre><code> Model Number Parts Diagram 110 Type 1 1301 Type 100 </code></pre> <p>And so on for the rest of the models. From this, you should be able to figure out how to parse the text to remove whitespace, etc.</p>
0
2016-08-17T16:05:07Z
[ "python", "web-scraping", "beautifulsoup", "comma", "nonetype" ]
Web Scraping Data to File with Results Separated by Commas
39,001,195
<p>I took a python class last semester and we went over web scraping for about a week. I realized that it can be very helpful in some data entry I'm doing for my job right now but am having troubles figuring it out. I am trying to get all of the model numbers for a part number on <a href="http://servicenet.dewalt.com/Parts/Detail/29730" rel="nofollow">http://servicenet.dewalt.com/Parts/Detail/29730</a> (You have to click on "You can see full list here" to see model numbers). Here is a screenshot of the model numbers <a href="http://i.stack.imgur.com/dVIMe.png" rel="nofollow"><img src="http://i.stack.imgur.com/dVIMe.png" alt="Here is a screenshot of the model numbers"></a>.</p> <p>So far this is what I have but I'm sure I'm way off:</p> <pre><code>from bs4 import BeautifulSoup import requests import uuid import json import os.path from multiprocessing.dummy import Pool as Threadpool ############# # get data for given url ############# def getdata(url): save_path=r'/Users/crazy4byu/PycharmProjects/ServiceNetWebScraping/Data' FitList=[] html = requests.get(url).text soup = BeautifulSoup(html,'html5lib') DW704 = soup.find_all('td',{'class':None}) for item1 in DW704: FitList.append( { 'Model':item1.find('a').text } ) with open(os.path.join(save_path,'data_'+str(uuid.uuid1())+'.json'),'w') as outfile: json.dump(FitList,outfile) ############# # Main ############# if'__main__' == __name__: #makes a list of my urls urls=[] urls.append(r'http://servicenet.dewalt.com/Parts/Detail/29730') pool = Threadpool(25) pool.map(getdata, urls) pool.close() pool.join() </code></pre> <p>In the end I want a text file that will basically be in this format: 110 Type 1, 1301 Type 100, 1317 Type 100, etc. (each model number separated by a comma).</p> <p>Currently, I am getting an error that says "AttributeError: 'NoneType' object has no attribute 'text'" but I'm sure that is not the only problem. I really appreciate your help! Thanks guys!</p>
2
2016-08-17T15:52:11Z
39,001,527
<p>It fails because in some cells there is no link - item1.find('a') is None and so you can't get "text" property of it.</p> <p>Also you don't need to use JSON at all as you want output file to be just model numbers separated by comma).</p> <p>Here is my code:</p> <pre><code>from bs4 import BeautifulSoup import requests import uuid import os.path from multiprocessing.dummy import Pool as Threadpool ############# # get data for given url ############# def getdata(url): save_path='./' FitList=list() html = requests.get(url).text soup = BeautifulSoup(html) DW704 = soup.find_all('td',{'class':None}) for item1 in DW704: print(item1.find('a')) if item1.find('a') is not None: if item1.find('a').text.strip() != "": FitList.append(item1.find('a').text) with open(os.path.join(save_path,'data_'+str(uuid.uuid1())+'.json'),'w') as outfile: outfile.write(",".join(FitList)) ############# # Main ############# if'__main__' == __name__: #makes a list of my urls urls=[] urls.append(r'http://servicenet.dewalt.com/Parts/Detail/29730') pool = Threadpool(25) pool.map(getdata, urls) pool.close() pool.join() </code></pre>
1
2016-08-17T16:10:03Z
[ "python", "web-scraping", "beautifulsoup", "comma", "nonetype" ]
Web Scraping Data to File with Results Separated by Commas
39,001,195
<p>I took a python class last semester and we went over web scraping for about a week. I realized that it can be very helpful in some data entry I'm doing for my job right now but am having troubles figuring it out. I am trying to get all of the model numbers for a part number on <a href="http://servicenet.dewalt.com/Parts/Detail/29730" rel="nofollow">http://servicenet.dewalt.com/Parts/Detail/29730</a> (You have to click on "You can see full list here" to see model numbers). Here is a screenshot of the model numbers <a href="http://i.stack.imgur.com/dVIMe.png" rel="nofollow"><img src="http://i.stack.imgur.com/dVIMe.png" alt="Here is a screenshot of the model numbers"></a>.</p> <p>So far this is what I have but I'm sure I'm way off:</p> <pre><code>from bs4 import BeautifulSoup import requests import uuid import json import os.path from multiprocessing.dummy import Pool as Threadpool ############# # get data for given url ############# def getdata(url): save_path=r'/Users/crazy4byu/PycharmProjects/ServiceNetWebScraping/Data' FitList=[] html = requests.get(url).text soup = BeautifulSoup(html,'html5lib') DW704 = soup.find_all('td',{'class':None}) for item1 in DW704: FitList.append( { 'Model':item1.find('a').text } ) with open(os.path.join(save_path,'data_'+str(uuid.uuid1())+'.json'),'w') as outfile: json.dump(FitList,outfile) ############# # Main ############# if'__main__' == __name__: #makes a list of my urls urls=[] urls.append(r'http://servicenet.dewalt.com/Parts/Detail/29730') pool = Threadpool(25) pool.map(getdata, urls) pool.close() pool.join() </code></pre> <p>In the end I want a text file that will basically be in this format: 110 Type 1, 1301 Type 100, 1317 Type 100, etc. (each model number separated by a comma).</p> <p>Currently, I am getting an error that says "AttributeError: 'NoneType' object has no attribute 'text'" but I'm sure that is not the only problem. I really appreciate your help! Thanks guys!</p>
2
2016-08-17T15:52:11Z
39,001,567
<p>The text you want is inside anchor inside the first td in the rows of the tbody of the <em>table</em> with the <em>id</em> <em>customerList</em>, don't grab every td available on the page, even if there was an anchor inside that has text it by no way means is it anyways related to the table or content you want.:</p> <pre><code>from bs4 import BeautifulSoup import io import requests soup = BeautifulSoup(requests.get("http://servicenet.dewalt.com/Parts/Detail/29730").content) # Get all the specific table rows. rows = soup.select("#customerList tbody tr") # use io.open to handle the non ascii. with io.open("data.txt", "w", encoding="utf-8") as f: for row in rows: # get text from first anchor inside the first td f.write(row.select_one("td a").text + u"\n") </code></pre> <p>data.txt will look like:</p> <pre><code>110 Type 1 1301 Type 100 1317 Type 100 1317 Type 101 1317-44 Type 100 1338 Type 100 1339 Type 100 1348 Type 100 1348K Type 100 2214 Type 100 2214-90 Type 101 22810 Type 1 etc............ </code></pre> <p>if you really want a single line comma delimited, you can <em>str.join</em> each element:</p> <pre><code>rows = soup.select("#customerList tbody tr") with io.open("data.txt", "w", encoding="utf-8") as f: f.write(u",".join([row.select_one("td a").text for row in rows])) </code></pre> <p>which will give you:</p> <pre><code>110 Type 1,1301 Type 100,1317 Type 100,1317 Type 101,1317-44 Type 100,1338 Type 100,1339 Type 100,1348 Type 100,1348K Type 100,2214 Type 100,2214-90 Type 101,22810 Type 1,23802 Type 1,23808-BDK Type 100,24873 Type 1,2610-220 Type 1,2670 Type 100,2670 Type 101,2670G Type 100,2674 Type 100,2674-34 Type 1,2675 Type 100,2675 Type 101,2683 Type 1,2683-220 Type 1,2684 Type 1,2684-34 Type 1,2685 Type 1,2694 Type 1,2695 Type 1,2697 Type 1,2697 Type 2,2698 Type 1,27111 Type 1,27111 Type 2,27126 Type 1,27126 Type 2,27128 Type 1,27128 Type 2,2717 Type 100,2717 Type 101,27182 Type 1,27182 Type 2,27188 Type 1,27513-BDK Type 100,27513-BDK Type 3,27713 Type 1,27997 Type 3,3057 Type 1,3057-44 Type 1,3057-48 Type 1,3060 Type 1,3064 Type 1,3064-44 Type 1,3103 Type 100,3103 Type 101,3104 Type 100,3105 Type 100,3105 Type 101,3105K Type 101,3105K Type 102,3107 Type 100,3107 Type 101,3108 Type 100,3108K Type 100,3110 Type 100,3110K Type 100,3110K Type 101,3110KG Type 100,3660 Type 1,3660 Type 2,3660 Type 3,3680 Type 1,3680 Type 2,3680 Type 3,4252 Type 100,4255 Type 100,4267 Type 1,4292 Type 1,5036 Type 100,5036K Type 100,5321 Type 100,6101 Type 100,6112 Type 100,6112 Type 101,6112-90 Type 100,6124 Type 100,6124 Type 101,6126 Type 100,6127 Type 100,6129 Type 100,6138 Type 100,6138 Type 101,6138 Type 102,6138-34 Type 100,6138-34 Type 102,6513 Type 100,6513 Type 101,6934 Type 100,6940 Type 100,6943 Type 100,6943 Type 101,6943 Type 102,6945 Type 100,6945 Type 101,BD4500 Type 1,DW120K Type 1,DW130 Type 1,DW130 Type 2,DW130 Type 3,DW130-220 Type 2,DW130-220 Type 3,DW140 Type 1,DW140 Type 2,DW142 Type 1,DW142 Type 2,DW290 Type 1,DW290 Type 2,DW290-220 Type 1,DW290-B2 Type 1,DW290-BR Type 1,DW290G Type 1,DW290K Type 2,DW291 Type 1,DW291 Type 2,DW291-B2 Type 1,DW291-B3 Type 1,DW296 Type 1,DW296 Type 2,DW304K Type 1,DW304K Type 2,DW304K-35 Type 1,DW304K-35 Type 2,DW304K-44 Type 1,DW305K Type 1,DW305K Type 2,DW306K Type 1,DW306K Type 2,DW306K220 Type 2,DW306KG Type 2,DW352-AR Type 2,DW352-AR Type 3,DW352-AR Type 4,DW352-B2 Type 1,DW352-B2 Type 2,DW352-B2 Type 3,DW352-B2 Type 4,DW352-B3 Type 1,DW352-B3 Type 2,DW352-B3 Type 3,DW352-B3 Type 4,DW352-BR Type 2,DW352-BR Type 3,DW352-BR Type 4,DW357 Type 1,DW358 Type 1,DW358-35 Type 1,DW358-44 Type 1,DW359 Type 1,DW359 Type 2,DW359 Type 3,DW359 Type 4,DW359-220 Type 1,DW359-B2 Type 1,DW359-B2 Type 2,DW359-B3 Type 1,DW359-B3 Type 2,DW359K Type 1,DW359K Type 2,DW359K Type 3,DW359K Type 4,DW360 Type 1,DW360 Type 2,DW361 Type 1,DW361 Type 2,DW362 Type 1,DW362 Type 2,DW362 Type 4,DW362K Type 2,DW362K Type 4,DW364 Type 1,DW364 Type 2,DW364 Type 3,DW364 Type 4,DW364 Type 5,DW364 Type 6,DW364K Type 3,DW364K Type 5,DW364K Type 6,DW384 Type 1,DW384 Type 2,DW384 Type 3,DW384 Type 4,DW384 Type 5,DW389-AR Type 1,DW389-B2 Type 1,DW389-B2 Type 2,DW389-B3 Type 1,DW389-B3 Type 2,DW389-BR Type 2,DW704 Type 1,DW704 Type 2,DW704 Type 3,DW704 Type 4,DW704 Type 4A,DW704 Type 5,DW705 Type 1,DW705 Type 2,DW705 Type 3,DW705 Type 4,DW705 Type 4A,DW705 Type 5,DW705 Type 6,DW705 Type 7,DW705 Type 8,DW705-220 Type 1,DW705-220 Type 2,DW705-35 Type 1,DW705-35 Type 2,DW705-35 Type 3,DW705-35 Type 4,DW705-44 Type 1,DW705-44 Type 2,DW705-AR Type 6,DW705-B2 Type 4,DW705-B2 Type 5,DW705-B2 Type 6,DW705-B2 Type 7,DW705-B3 Type 5,DW705-B3 Type 6,DW705-B3 Type 7,DW705-BR Type 7,DW705S Type 5,DW705S Type 6,DW705S Type 7,DW705S Type 8,DW708 Type 1,DW708 Type 3,DW715 Type 1,DW744 Type 1,DW744 Type 2,DW744 Type 3,DW744S Type 2,DW744S Type 3,DW744SB Type 3,DW845 Type 1,DW845 Type 2,DW845 Type 3,DW847 Type 1,DW847 Type 2,DW849 Type 1,DW849 Type 2,DW849 Type 3,DW849-AR Type 1,DW849-AR Type 2,DW849-AR Type 3,DW849-B2 Type 1,DW849-B2 Type 2,DW849-B2 Type 3,DW849-B3 Type 1,DW849-BR Type 1,DW849-BR Type 2,DW849-BR Type 3,DW880 Type 1,DW880 Type 2,DW880 Type 3,DW888 Type 1,DW888 Type 2,DW888 Type 3,DW888-AR Type 3,DW888-B2 Type 3,EP9500 Type 101,EP9500 Type 102,ET1460 Type 1,ET1475 Type 100,ET1475 Type 101,ET1475 Type 102,ET1480 Type 1,ET1490 Type 1,ET1560 Type 1,EW5000 Type 100,G-2610 Type 100,G-2610 Type 101,MT6129 Type 100,MTE33 Type 101,MTE36 Type 101,MTE36 Type 102,Q400 Type 1,Q450 Type 1,Q450K Type 1,Q510 Type 1,Q600 Type 1,QP350K Type 1 </code></pre>
1
2016-08-17T16:12:15Z
[ "python", "web-scraping", "beautifulsoup", "comma", "nonetype" ]
self.env for manually defined model raise an error
39,001,201
<p>I'm trying to create country guess application for Odoo 9, based on barcode value, for this I've created following models:</p> <pre class="lang-py prettyprint-override"><code>class InstantProductTemplate(models.Model): _name = 'product.template' _inherit = 'product.template' country_of_origin = fields.Many2one('res.country', string='Country of origin', compute="_guess_country", store=True) @api.one @api.depends('barcode', 'res.country.ean_range') # @api.onchange('barcode') def _guess_country(self): _logger.info("entered guess country!!") ean_len = 13 if isinstance(self.barcode, (str, unicode)): barcode_len = len(self.barcode) else: return if barcode_len == ean_len: barcode = self.barcode elif barcode_len &lt; ean_len: barcode = '0' * (ean_len - barcode_len) + self.barcode else: # could not guess country of origin return prefix = int(barcode[:3]) for ean in self.env['res.country.ean_range'].search([]): if ean.range_start &lt;= prefix &lt;= ean.range_end: self.country_of_origin = ean.country break class InstantCountryRanges(models.Model): _name = 'res.country' _inherit = 'res.country' ean_range = fields.One2many('res.country.ean_range', 'range_id') class InstantCountry(models.Model): _name = 'res.country.ean_range' name = fields.Char() range_id = fields.Integer() range_start = fields.Integer("Range start") range_end = fields.Integer("Range end") </code></pre> <p>But it doesn't work, and installation fails with error stack trace:</p> <pre><code>Traceback (most recent call last): File "/usr/lib/python2.7/dist-packages/openerp/http.py", line 647, in _handle_exception return super(JsonRequest, self)._handle_exception(exception) File "/usr/lib/python2.7/dist-packages/openerp/http.py", line 684, in dispatch result = self._call_function(**self.params) File "/usr/lib/python2.7/dist-packages/openerp/http.py", line 320, in _call_function return checked_call(self.db, *args, **kwargs) File "/usr/lib/python2.7/dist-packages/openerp/service/model.py", line 118, in wrapper return f(dbname, *args, **kwargs) File "/usr/lib/python2.7/dist-packages/openerp/http.py", line 313, in checked_call result = self.endpoint(*a, **kw) File "/usr/lib/python2.7/dist-packages/openerp/http.py", line 963, in __call__ return self.method(*args, **kw) File "/usr/lib/python2.7/dist-packages/openerp/http.py", line 513, in response_wrap response = f(*args, **kw) File "/usr/lib/python2.7/dist-packages/openerp/addons/web/controllers/main.py", line 901, in call_button action = self._call_kw(model, method, args, {}) File "/usr/lib/python2.7/dist-packages/openerp/addons/web/controllers/main.py", line 889, in _call_kw return getattr(request.registry.get(model), method)(request.cr, request.uid, *args, **kwargs) File "/usr/lib/python2.7/dist-packages/openerp/api.py", line 250, in wrapper return old_api(self, *args, **kwargs) File "/usr/lib/python2.7/dist-packages/openerp/addons/base/module/module.py", line 459, in button_immediate_install return self._button_immediate_function(cr, uid, ids, self.button_install, context=context) File "/usr/lib/python2.7/dist-packages/openerp/api.py", line 250, in wrapper return old_api(self, *args, **kwargs) File "/usr/lib/python2.7/dist-packages/openerp/addons/base/module/module.py", line 533, in _button_immediate_function registry = openerp.modules.registry.RegistryManager.new(cr.dbname, update_module=True) File "/usr/lib/python2.7/dist-packages/openerp/modules/registry.py", line 386, in new openerp.modules.load_modules(registry._db, force_demo, status, update_module) File "/usr/lib/python2.7/dist-packages/openerp/modules/loading.py", line 338, in load_modules loaded_modules, update_module) File "/usr/lib/python2.7/dist-packages/openerp/modules/loading.py", line 237, in load_marked_modules loaded, processed = load_module_graph(cr, graph, progressdict, report=report, skip_modules=loaded_modules, perform_checks=perform_checks) File "/usr/lib/python2.7/dist-packages/openerp/modules/loading.py", line 136, in load_module_graph registry.setup_models(cr, partial=True) File "/usr/lib/python2.7/dist-packages/openerp/modules/registry.py", line 203, in setup_models model._setup_complete(cr, SUPERUSER_ID) File "/usr/lib/python2.7/dist-packages/openerp/api.py", line 250, in wrapper return old_api(self, *args, **kwargs) File "/usr/lib/python2.7/dist-packages/openerp/api.py", line 354, in old_api result = method(recs, *args, **kwargs) File "/usr/lib/python2.7/dist-packages/openerp/models.py", line 3081, in _setup_complete field.setup_triggers(self.env) File "/usr/lib/python2.7/dist-packages/openerp/fields.py", line 643, in setup_triggers self._add_trigger(env, path_str) File "/usr/lib/python2.7/dist-packages/openerp/fields.py", line 627, in _add_trigger field = model._fields[name] KeyError: 'res' </code></pre> <p>I believe I'm missing something, but can't understand what exactly, any help will be highly appreciated. </p>
2
2016-08-17T15:52:29Z
39,001,682
<p>You cannot make a dependency from another model filed in <a href="https://www.odoo.com/documentation/8.0/reference/orm.html#openerp.api.depends" rel="nofollow"><code>@api.depends</code></a>. Decorator expects that you supply a list of <em>current</em> model fields:</p> <blockquote> <p>Each argument must be a string that consists in a dot-separated sequence of field names:</p> </blockquote> <p>So odoo orm is unable to find <code>res</code> field in <code>product.template</code>.</p>
2
2016-08-17T16:18:05Z
[ "python", "openerp", "odoo-9" ]
How to put a JSON file's content in a response
39,001,230
<p>I have a file on my computer that I'm trying to serve up as JSON from a django view.</p> <pre><code>def serve(request): file = os.path.join(BASE_DIR, 'static', 'files', 'apple-app-site-association') response = HttpResponse(content=file) response['Content-Type'] = 'application/json' </code></pre> <p>What I get back is the path to the file when navigating to the URL</p> <pre><code>/Users/myself/Developer/us/www/static/files/apple-app-site-association </code></pre> <p>What am I doing wrong here?</p>
2
2016-08-17T15:53:47Z
39,001,468
<p><code>os.path.join</code> returns a string, it's why you get a path in the content of the response. You need to read the file at that path first.</p> <h1>For a static file</h1> <p>If the file is static and on disk, you could just return it using the webserver and avoid using python and django at all. If the file needs authenticating to be downloaded, you could still handle that with django, and return a <a href="https://www.nginx.com/resources/wiki/start/topics/examples/xsendfile/" rel="nofollow"><code>X-Sendfile</code> header</a> (this is dependant on the webserver).</p> <p>Serving static files is a job for a webserver, Nginx and Apache are really good at this, while Python and Django are tools to handle application logic.</p> <h1>Simplest way to read a file</h1> <pre><code>def serve(request): path = os.path.join(BASE_DIR, 'static', 'files', 'apple-app-site-association') with open(path , 'r') as myfile: data=myfile.read() response = HttpResponse(content=data) response['Content-Type'] = 'application/json' </code></pre> <p>This is inspired by <a href="http://stackoverflow.com/a/8369345/1218980">How do I read a text file into a string variable in Python</a></p> <h2>For a more advanced solution</h2> <p>See <a href="http://stackoverflow.com/a/39001489/1218980">dhke's answer</a> on <code>StreamingHttpResponse</code>.</p> <h1>Additional information</h1> <ul> <li><a href="https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files" rel="nofollow">Reading and writing files</a></li> <li><a href="https://docs.djangoproject.com/en/1.10/topics/files/" rel="nofollow">Managing files with Django</a></li> </ul>
2
2016-08-17T16:06:48Z
[ "python", "json", "django", "file" ]
How to put a JSON file's content in a response
39,001,230
<p>I have a file on my computer that I'm trying to serve up as JSON from a django view.</p> <pre><code>def serve(request): file = os.path.join(BASE_DIR, 'static', 'files', 'apple-app-site-association') response = HttpResponse(content=file) response['Content-Type'] = 'application/json' </code></pre> <p>What I get back is the path to the file when navigating to the URL</p> <pre><code>/Users/myself/Developer/us/www/static/files/apple-app-site-association </code></pre> <p>What am I doing wrong here?</p>
2
2016-08-17T15:53:47Z
39,001,489
<p>If you feed <code>HttpResponse</code> a string a <code>content</code> you tell it to <a href="https://docs.djangoproject.com/en/1.10/ref/request-response/#id3" rel="nofollow">serve that string</a> as HTTP body:</p> <blockquote> <p><code>content</code> should be an iterator or a string. If it’s an iterator, it should return strings, and those strings will be joined together to form the content of the response. If it is not an iterator or a string, it will be converted to a string when accessed.</p> </blockquote> <p>Since you seem to be using your static storage directory, you might as well use <code>staticfiles</code> to handle content:</p> <pre><code>from django.contrib.staticfiles.storage import staticfiles_storage from django.http.response import StreamingHttpResponse file_path = os.path.join('files', 'apple-app-site-association') response = StreamingHttpResponse(content=staticfiles_storage.open(file_path)) return response </code></pre> <p>As noted in <a href="https://stackoverflow.com/questions/39001230/simple-django-json-response/39001468#answer-39001468">@Emile Bergeron's answer</a>, for static files, this should already be overkill, since those are supposed to be accessible from outside, anyway. So a simple redirect to <code>static(file_path)</code> should do the trick, too (given your webserver is correctly configured).</p> <p>To serve an arbitrary file:</p> <pre><code>from django.contrib.staticfiles.storage import staticfiles_storage from django.http.response import StreamingHttpResponse file_path = ... response = StreamingHttpResponse(content=open(file_path, 'rb')) return response </code></pre> <p>Note that from Django 1.10 and on, the file handle will be closed automatically.</p> <p>Also, if the file is accessible from your webserver, consider using <a href="https://pypi.python.org/pypi/django-sendfile" rel="nofollow"><code>django-sendfile</code></a>, so that the file's contents don't need to pass through Django at all.</p>
2
2016-08-17T16:07:50Z
[ "python", "json", "django", "file" ]
How can I extract data from a file?
39,001,249
<p>I have a file data like below, I want to calculate the time difference between two line for each station (here PAR and PAY), I mean for example for PAR we are going to calculate '7 48 42.64 - 7 48 42.24' (7=hour, 48=minute, and 42.64 is second).</p> <pre><code>2006 03 20 07 47 46.7 32.314 55.843 15.5 4.5 PAR GZ IP 7 48 42.24 PAR GZ IPg 7 48 42.64 PAR GZ EP 7 48 42.34 PAY GZ IPg 7 48 57.96 PAY GZ IP 7 48 57.59 PAY GZ EP 7 48 57.74 </code></pre> <p>In my code the information of first line is saved in a list named "event_REF1", and for each line to a list named "REF1_station". It search for 'IP' first and then 'IPg', for PAR there is no problem, but for PAY it make wrong result because first we have 'IPg' in data for this station.</p> <pre><code>if (REF1_station[0][2] == "IP "): earlier = (float(REF1_station[0][3])*3600+ float(REF1_station[0][4])*60+ float(REF1_station[0][5])- float(event_REF1[3])*3600- float(event_REF1[4])*60- float(event_REF1[5])) if (REF1_station[0][2] == "IPg"): later = (float(REF1_station[0][3])*3600+ float(REF1_station[0][4])*60+ float(REF1_station[0][5])- float(event_REF1[3])*3600- float(event_REF1[4])*60- float(event_REF1[5])) error = float((later - earlier)/2) </code></pre> <p>The result is:</p> <p>PAR = 0.199999999999</p> <p>PAY = 7.86</p>
-1
2016-08-17T15:54:32Z
39,002,931
<p>If your lines are consistently separated by whitespace, then you can just iterate through the file to get all of the lines in a usable format and subtract whatever two lines that you want.</p> <pre><code>all_lines = open('your_file.txt', 'r').readlines() all_lines = [l.split() for l in all_lines] # Hour is index 3, Minute is 4, seconds is 5 </code></pre>
0
2016-08-17T17:30:31Z
[ "python", "python-2.7" ]
Defining external path variable for python package on installation
39,001,278
<p>If I have a Python package, <code>foo</code>, and I want a path variable that is user-defined during package installation (<code>foo.ext_path = '/Home/User_name/Data_files/foo_data'</code> or something), what is the best/recommended/most pythonic manner to accomplish this? I do not want to include the data within the python package; this is something that is both necessary to run foo, and necessary for the user to provide.</p>
0
2016-08-17T15:55:55Z
39,002,244
<p>Required configuration usually falls into the category of things belonging in an external configuration file. </p> <p>The package can define a configuration file path, in posix this is usually something under <code>/etc</code>, and ask that the user populate it with appropriate entries for their configuration.</p> <p>Best practice is for the package to create an example configuration file for example <code>/etc/my_package/my_package.example</code> or similar, to show all available configuration entries and example values.</p> <p>Python has built in support for configuration files via <a href="https://docs.python.org/2/library/configparser.html?highlight=cfg" rel="nofollow">ConfigParser</a> though YAML based config files are usually easier to use and frequently more common.</p>
1
2016-08-17T16:50:11Z
[ "python", "packages" ]
Opencv webcam and Kivy GUI actionbar simultaneously
39,001,299
<p>Hey so I am trying to work with opencv and kivy. My code returns a class called KivyCamera which unables me to add an actionbar on the top of the screen. Is there any way that I can simultaneously add an action bar and an opencv webcam in Kivy GUI framework? Thanks. Also if you do </p> <p>def build: pass in the python script instead of the build function in camApp you can see the actionbar. It is just that I don't know how to combine them together. </p> <p>Python file: </p> <pre><code>from kivy.app import App from kivy.uix.image import Image from kivy.clock import Clock from kivy.graphics.texture import Texture import cv2 class KivyCamera(Image): def __init__(self, capture, fps, **kwargs): super(KivyCamera, self).__init__(**kwargs) self.capture = capture Clock.schedule_interval(self.update, 1.0 / fps) def update(self, dt): ret, frame = self.capture.read() if ret: # convert it to texture buf1 = cv2.flip(frame, 0) buf = buf1.tostring() image_texture = Texture.create( size=(frame.shape[1], frame.shape[0]), colorfmt='bgr') image_texture.blit_buffer(buf, colorfmt='bgr', bufferfmt='ubyte') # display image from the texture self.texture = image_texture class CamApp(App): def build(self): self.capture = cv2.VideoCapture(1) self.my_camera = KivyCamera(capture=self.capture, fps=30) return self.my_camera def on_stop(self): #without this, app will not exit even if the window is closed self.capture.release() if __name__ == '__main__': CamApp().run() </code></pre> <p>kv file : </p> <pre><code>#:kivy 1.8.0 #:import KivyLexer kivy.extras.highlight.KivyLexer #:import Factory kivy.factory.Factory &lt;ActionSpinnerOptions@SpinnerOption&gt; background_color: .4, .4, .4, 1 &lt;ActionSpinner@Spinner+ActionItem&gt; canvas.before: Color: rgba: 0.128, 0.128, 0.128, 1 Rectangle: size: self.size pos: self.pos border: 27, 20, 12, 12 background_normal: 'atlas://data/images/defaulttheme/action_group' option_cls: Factory.ActionSpinnerOptions &lt;ActionDropdown&gt;: on_size: self.width = '220dp' &lt;ShowcaseScreen&gt;: ScrollView: do_scroll_x: False do_scroll_y: False if root.fullscreen else (content.height &gt; root.height - dp(16)) AnchorLayout: size_hint_y: None height: root.height if root.fullscreen else max(root.height, content.height) GridLayout: id: content cols: 1 spacing: '8dp' padding: '8dp' size_hint: (1, 1) if root.fullscreen else (.8, None) height: self.height if root.fullscreen else self.minimum_height BoxLayout: orientation: 'vertical' canvas.before: Color: rgb: .6, .6, .6 Rectangle: size: self.size source: 'data/background.png' ActionBar: ActionView: id: av ActionPrevious: with_previous: (False if sm.current_screen.name == 'button' else True) if sm.current_screen else False title: 'Showcase' + ('' if not app.current_title else ' - {}'.format(app.current_title)) on_release: app.go_hierarchy_previous() ActionSpinner: id: spnr important: True text: 'Jump to Screen' values: app.screen_names on_text: if sm.current != args[1]:\ idx = app.screen_names.index(args[1]);\ app.go_screen(idx) ActionToggleButton: text: 'Toggle sourcecode' icon: 'data/icons/sourcecode.png' on_release: app.toggle_source_code() ActionButton: text: 'Previous screen' icon: 'data/icons/prev.png' on_release: app.go_previous_screen() ActionButton: text: 'Next screen' icon: 'data/icons/next.png' on_release: app.go_next_screen() important: True ScrollView: id: sv size_hint_y: None height: 0 CodeInput: id: sourcecode lexer: KivyLexer() text: app.sourcecode readonly: True size_hint_y: None font_size: '12sp' height: self.minimum_height ScreenManager: id: sm on_current_screen: spnr.text = args[1].name idx = app.screen_names.index(args[1].name) if idx &gt; -1: app.hierarchy.append(idx) </code></pre>
0
2016-08-17T15:57:09Z
39,182,766
<p>(Note: I haven't worked with opencv yet and I can't find it on pypi)</p> <p>I see that your class <code>KivyCamera</code> is just a casual widget used in Kivy. What happens when you do <code>def build(self): pass</code> is, that it opens the <code>kv</code> file and finds something that can be used as a root widget - in your case probably the <code>BoxLayout:</code> under <code>&lt;ShowcaseScreen&gt;:</code>.</p> <p>What you can do with this is: try to put <code>&lt;KivyCamera&gt;:</code> into your <code>kv</code> file. Just that, nothing else under that. then put <code>KivyCamera:</code> somewhere into that <code>BoxLayout:</code> (the best would be into that <code>ScreenManager</code> as a separate <code>Screen</code>) and it should display it. Sizing shouldn't be an issue here as it's <code>BoxLayout</code>, which should prohibit overlaping of <code>ActionBar</code> and <code>KivyCamera</code> by default.</p>
0
2016-08-27T15:28:47Z
[ "python", "opencv", "kivy", "webcam", "kivy-language" ]
Can't finish the loop when asking for valid answers
39,001,305
<p>I have a problem with my code that I can't find the solution as well. I ask for questions that has to be valid but the loops just continues, and let me input. </p> <pre><code>print('Do you want to go to the store or woods?') lists = ('woods', 'store') while True: answers = input() if answers == 'store': break print('Going to the store...') elif answers == 'woods': break print('Going to the woods...') while lists not in answers: print('That is not a valid answer') </code></pre>
-2
2016-08-17T15:57:39Z
39,001,408
<p>You want to check if the user's answer is not in your list of valid answers. What you're doing is the other way around. Try this:</p> <pre><code>if answers not in lists: print('That is not a valid answer') </code></pre> <p>You'll also want to either <code>break</code> at that point, or print your prompt message again.</p>
2
2016-08-17T16:03:49Z
[ "python", "adventure" ]
Can't finish the loop when asking for valid answers
39,001,305
<p>I have a problem with my code that I can't find the solution as well. I ask for questions that has to be valid but the loops just continues, and let me input. </p> <pre><code>print('Do you want to go to the store or woods?') lists = ('woods', 'store') while True: answers = input() if answers == 'store': break print('Going to the store...') elif answers == 'woods': break print('Going to the woods...') while lists not in answers: print('That is not a valid answer') </code></pre>
-2
2016-08-17T15:57:39Z
39,001,412
<p>Try this:</p> <pre><code>print('Do you want to go to the store or woods?') places = ('woods', 'store') while True: answer = input() if answer in places: print ("Going to the {0}...".format(answer)) break else: print('That is not a valid answer') </code></pre>
1
2016-08-17T16:03:57Z
[ "python", "adventure" ]
Can't finish the loop when asking for valid answers
39,001,305
<p>I have a problem with my code that I can't find the solution as well. I ask for questions that has to be valid but the loops just continues, and let me input. </p> <pre><code>print('Do you want to go to the store or woods?') lists = ('woods', 'store') while True: answers = input() if answers == 'store': break print('Going to the store...') elif answers == 'woods': break print('Going to the woods...') while lists not in answers: print('That is not a valid answer') </code></pre>
-2
2016-08-17T15:57:39Z
39,001,636
<p>First of all, your <code>print</code> statements are unreachable. You can find more information <a href="https://docs.python.org/3/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops" rel="nofollow">here</a>.</p> <pre class="lang-py prettyprint-override"><code>#... if answers == 'store': print('Going to the store...') break elif answers == 'woods': print('Going to the woods...') break #... </code></pre> <p>Then, your second <code>while</code> statement makes no sense in this way. If you just wanted to print <code>That is not a valid answer</code> in case the input differs from <code>store</code> or <code>woods</code> and give a user another try - then you can just use <code>else</code>, without <code>lists</code> at all:</p> <pre class="lang-py prettyprint-override"><code>print('Do you want to go to the store or woods?') # no lists while True: answers = input() if answers == 'store': print('Going to the store...') break elif answers == 'woods': print('Going to the woods...') break else: print('That is not a valid answer') </code></pre> <p>If you instead would like to check, whether the user's input is encountered in <code>lists</code>, then you need to do this <code>in</code> trick inside out: </p> <pre><code>print('Do you want to go to the store or woods?') lists = ('woods', 'store') while True: answers = input() if answers == 'store': print('Going to the store...') break elif answers == 'woods': print('Going to the woods...') break elif answers not in lists: print('That is not a valid answer') else: # some default case, for example sys.exit() (needs sys to be imported) </code></pre>
1
2016-08-17T16:15:45Z
[ "python", "adventure" ]
Convert MySQL Query to Django query
39,001,317
<p>I'm converting a FlaskApp to Django. In my Flask App I was doing straight DB queries w/o an ORM like MySQLAlchemy.</p> <p>I'm having trouble converting my count queries for use in Django. Seems simple enought, but I'm missing something.</p> <p><strong>OLD FUNCTION W/ QUERY</strong></p> <pre><code>def countClients(db, begin, end, type): c = db.cursor() query = "SELECT COUNT(*) FROM newclients WHERE method LIKE %s AND (enddate BETWEEN %s AND %s)" c.execute(query, (type, begin, end)) output = int(c.fetchone()[0]) return output </code></pre> <p><strong>NEW QUERY</strong></p> <pre><code>for year in range(2015, today.year): for month in range(1, 13): startdate = datetime.date(year, month, 1) enddate = last_day_of_month(startdate) try: Count14.append( newclients.objects.filter(method = 'Test Drive', enddate__range=(startdate, enddate) ) ).count() </code></pre> <p><strong>WHAT I'VE TRIED</strong></p> <ul> <li>Query without Try:Except</li> </ul> <p>w/o the try except I get a traceback </p> <pre><code>'NoneType' object has no attribute 'count' </code></pre> <ul> <li>Adding a int() around the query</li> </ul> <p>But the int function can't accept a queryset.</p> <p><strong>NOTE</strong> I have used portions of these queries successfully, but these what I'm trying here is more complex than the others.</p> <p>i.e. This one works, but is simpler.</p> <pre><code>clients = newclients.objects.filter(method=method_query).filter(enddate__range=(begindate, enddate)) </code></pre>
0
2016-08-17T15:58:06Z
39,001,403
<p>Your <code>.count()</code> is in the wrong place. It needs to be after the second close parenthesis, not the third.</p> <p>As it is, you are calling it on the result of <code>append</code>, which is always None.</p>
1
2016-08-17T16:03:41Z
[ "python", "mysql", "django" ]
Pymongo check user permissions on connection
39,001,450
<p>I enabled authentication on my MongoDB database, and I'm connecting to it through pymongo. Everything works well when the user connecting to the DB has all the relevant permissions, but when a user with limited permissions connects, an exception is raised only when executing the first command. Is there a way I can check the user's permissions on connection?</p>
1
2016-08-17T16:06:08Z
39,009,930
<p>If you are using a recent version of pymongo you may want to check this <a href="https://api.mongodb.com/python/current/migrate-to-pymongo3.html#mongoclient-connects-asynchronously" rel="nofollow">page of the docs</a> </p> <blockquote> <p>In PyMongo 3, the MongoClient constructor no longer blocks while connecting to the server or servers, and it no longer raises ConnectionFailure if they are unavailable, nor ConfigurationError if the user’s credentials are wrong. Instead, the constructor returns immediately and launches the connection process on background threads. The connect option is added to control whether these threads are started immediately, or when the client is first used. </p> </blockquote> <p>They also provide a 'workaround' if you want to know directly whether the connection was successfully established with this </p> <pre><code>from pymongo.errors import ConnectionFailure client = MongoClient(connect=False) try: result = client.admin.command("ismaster") except ConnectionFailure: print("Server not available") </code></pre> <p>The reason for using the above <code>client.admin.command("ismaster")</code> is due to the fact that no special permissions are need to execute it </p> <blockquote> <p>Any operation can be used to determine if the server is available. We choose the “ismaster” command here because it is cheap and does not require auth, so it is a simple way to check whether the server is available.</p> </blockquote>
0
2016-08-18T04:18:49Z
[ "python", "mongodb", "pymongo" ]
Change working directory of a imported module
39,001,455
<p>i am having trouble with some modules i want to import, so let's me put a sample to explain better.</p> <pre><code>proyect/ helpers/ config.py locations/ loc1.py pages/ page1.py Tools/ myTool.py </code></pre> <p>So whats happening is that in <code>myTool.py</code> i'm importing <code>page1.py</code> that import from <code>loc1.py</code>. to do that i'm appendind '../ ' to <code>sys.path</code>. The problem is that in loc1 is imported <code>config.py</code> and initialize, when it do that it working dir is TOols/ but i need it to be my proyect dir.</p>
0
2016-08-17T16:06:20Z
39,001,840
<p>Modules don't have working dirs, only the program as a whole does.</p> <p>You should add the proyect dir to sys.path at the start of the script, then import loc1 from locations.</p>
1
2016-08-17T16:27:00Z
[ "python", "python-2.7" ]
hdf5 not supported (please install/reinstall h5py) Scipy not supported! when importing TFLearn?
39,001,457
<p>I'm getting this error:</p> <pre><code>hdf5 not supported (please install/reinstall h5py) Scipy not supported! </code></pre> <p>when I try to import <code>tflearn</code>. And I think due to this problem my TFLearn code is not working properly?</p>
1
2016-08-17T16:06:25Z
39,005,705
<p>I ran into the same issue a few minutes ago, pretty much you just need to reinstall h5py using the package manager of your current environment. </p> <p><a href="http://docs.h5py.org/en/latest/build.html" rel="nofollow">http://docs.h5py.org/en/latest/build.html</a></p>
0
2016-08-17T20:27:53Z
[ "python", "scipy", "tensorflow" ]
Manage secret key in django settings
39,001,568
<p>Following <a href="http://fearofcode.github.io/blog/2013/01/15/how-to-scrub-sensitive-information-from-django-settings-dot-py-files/" rel="nofollow">this post</a> and <a href="http://stackoverflow.com/a/31883650/5530234">this answer</a> I have set up a separate file for storing <code>SECRETY_KEY</code> and importing it into the main <code>settings.py</code> file. However, I am getting the following error:</p> <pre><code>ImportError: No module named 'settings_secret' </code></pre> <p><strong>settings_secret.py</strong></p> <pre><code># SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '..key' </code></pre> <p><strong>settings.py</strong></p> <pre><code>from settings_secret import * </code></pre> <p>and <strong>.gitignore</strong></p> <pre><code># Secret Settings settings_secret.py </code></pre>
0
2016-08-17T16:12:18Z
39,001,640
<p>Just try, <code>from .settings_secret import *</code> . [dot] ensures that you are importing from the current module.</p>
0
2016-08-17T16:15:51Z
[ "python", "django" ]