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
How to check in python that at least one of the default parameters of the function specified
38,881,888
<p>What is the best practice in python to check if at least one of the default parameters of the function is specified?</p> <p>Let's suppose we have some function:</p> <pre><code>def some_function(arg_a=None, arg_b=None, arg_c=False) </code></pre> <p>with some default parameters. In my case, I need to check if either <code>arg_a</code> or <code>arg_b</code> is specified. So I thought of implementing something like this:</p> <pre><code>def some_function(arg_a=None, arg_b=None, arg_c=False): ... if arg_a is not None: ... elif arg_b is not None: ... else: raise ValueError('Expected either arg_a or arg_b args') ... ... </code></pre> <p>So, what is more pythonic way to implement such kind of functionality?</p>
4
2016-08-10T19:22:48Z
38,882,106
<p>You may consider using <code>kwargs</code> if you have quite a number of such named arguments with <em>mismatching</em> default values:</p> <pre><code>def some_function(**kwargs): reqd = ['arg_a', 'arg_b'] if not all(i in kwargs for i in reqd): raise ValueError('Expected either {} args'.format(' or '.join(reqd))) arg_a = kwargs.get('args_a') arg_b = kwargs.get('args_b') arg_c = kwargs.get('args_c', False) </code></pre>
1
2016-08-10T19:37:27Z
[ "python", "function", "parameter-passing" ]
How to check in python that at least one of the default parameters of the function specified
38,881,888
<p>What is the best practice in python to check if at least one of the default parameters of the function is specified?</p> <p>Let's suppose we have some function:</p> <pre><code>def some_function(arg_a=None, arg_b=None, arg_c=False) </code></pre> <p>with some default parameters. In my case, I need to check if either <code>arg_a</code> or <code>arg_b</code> is specified. So I thought of implementing something like this:</p> <pre><code>def some_function(arg_a=None, arg_b=None, arg_c=False): ... if arg_a is not None: ... elif arg_b is not None: ... else: raise ValueError('Expected either arg_a or arg_b args') ... ... </code></pre> <p>So, what is more pythonic way to implement such kind of functionality?</p>
4
2016-08-10T19:22:48Z
38,882,167
<blockquote> <p>To check if at least one of the default parameters of the function specified</p> </blockquote> <p>The solution using <code>locals</code>, <code>dict.values</code> and <code>any</code> functions:</p> <pre><code>def some_function(arg_a=None, arg_b=None, arg_c=False): args = locals() if (any(args.values()) == True): print('Ok') else: raise ValueError('At least one default param should be passed!') some_function(False, 1) # Ok some_function('text', False, None) # Ok some_function(0, False, None) # Error </code></pre> <p><a href="https://docs.python.org/2/library/functions.html#any" rel="nofollow">https://docs.python.org/2/library/functions.html#any</a></p>
0
2016-08-10T19:40:46Z
[ "python", "function", "parameter-passing" ]
How to sum all integer after running a loop
38,882,132
<p>I have written a script, but I don't know if it's possible to have the total. My script would give me total number per loop, but I want to have the lump sum of everything. For instance, if I input 6, I would expect the result to be 168. if I input 5, I would expect the result to be 105.</p> <p>Thanks</p> <p>My script is as follow:</p> <pre><code>def multiples(n, high): i = 0 res = 0 while i &lt;= high: res = res + (n+i) i = i + 1 print res return res def p(high): i = 1 while i &lt;= high: multiples(i, i) i = i + 1 p(6) # Expected Output: 168 </code></pre>
0
2016-08-10T19:38:53Z
38,882,236
<p>With the most minimal change, this would allow <code>p(6)</code> to return <code>168</code>:</p> <pre><code>def multiples(n, high): i = 0 res = 0 while i &lt;= high: res = res + (n+i) i = i + 1 print res return res def p(high): i = 1 lumpSum = 0 while i &lt;= high: lumpSum += multiples(i, i) i = i + 1 return lumpSum print p(6) </code></pre> <p>Alternatively, you can shorten <code>p</code>:</p> <pre><code>def p(high): return sum([multiples(i, i) for i in range(1, high + 1)]) </code></pre> <p>Edit: The entire code can indeed be reduced to this: <a href="http://stackoverflow.com/users/3058609/adam-smith">Adam Smith</a> pointed out in <a href="http://stackoverflow.com/questions/38882132/how-to-sum-all-integer-after-running-a-loop/38882236?noredirect=1#comment65125810_38882236">his comment</a>.</p> <p><code>p = lambda n: sum(i+j for i in range(n) for j in range(i))</code></p>
0
2016-08-10T19:45:16Z
[ "python", "python-2.7", "python-3.x" ]
How to sum all integer after running a loop
38,882,132
<p>I have written a script, but I don't know if it's possible to have the total. My script would give me total number per loop, but I want to have the lump sum of everything. For instance, if I input 6, I would expect the result to be 168. if I input 5, I would expect the result to be 105.</p> <p>Thanks</p> <p>My script is as follow:</p> <pre><code>def multiples(n, high): i = 0 res = 0 while i &lt;= high: res = res + (n+i) i = i + 1 print res return res def p(high): i = 1 while i &lt;= high: multiples(i, i) i = i + 1 p(6) # Expected Output: 168 </code></pre>
0
2016-08-10T19:38:53Z
38,882,264
<p>A few things,</p> <p>First off, this is a very old-school type of looping.</p> <pre><code>i = 0 while i &lt;= some_number: do_something i = i + 1 </code></pre> <p>The last language I used that required a pattern like that was Basic. Use <code>for</code> loops. A standard <code>for</code> loop (note: NOT Python's, but I'll get to that in a minute) looks like <code>for i=0; i&lt;=some_number; i++ { do_something }</code>. That is:</p> <ol> <li>Initialize <code>i</code></li> <li>Conditional for when to keep looping</li> <li>What to do after each loop block</li> </ol> <p>Python is even more clear. <code>for</code> loops over any iterable, so:</p> <pre><code>for element in [1,3,5,7,9]: ... </code></pre> <p>Gives you <code>1</code>, then <code>3</code>, then <code>5</code>, then <code>7</code>, then <code>9</code> as <code>element</code> in the loop body. Use this in conjunction with the <code>range</code> built-in to loop <code>N</code> times.</p> <pre><code>for i in range(high): # do something `high` number of times </code></pre> <p>A naive re-write looks like:</p> <pre><code>def multiples(k, n): res = 0 for i in range(n): res += (k+i) print(res) return res def p(n): for i in range(n): multiples(i, i) </code></pre> <p>However that doesn't really give you what you want either. What you WANT is to assign the value <code>multiples(i, i)</code> TO something.</p> <pre><code>def p(n): total = 0 for i in range(n): total += multiples(i, i) return total </code></pre> <p>Now we're tracking your grand total inside <code>p</code>, and returning it afterwards.</p> <pre><code>result = p(6) print(result) # does what you want </code></pre> <p><hr> Of course there's no good reason to break up these two functions. You could just as easily write:</p> <pre><code>def p(n): total = 0 for i in range(n): for j in range(i): total += j+i return total </code></pre>
1
2016-08-10T19:46:52Z
[ "python", "python-2.7", "python-3.x" ]
Problems with sockets
38,882,137
<p>I'm trying to set up a small server where when the client logs in gets some messages. </p> <p><strong>The server code</strong> </p> <pre><code>import socket #Networking s = socket.socket() print("Network successfully created") port = 3642 s.bind(('',port)) print("Network has been binded to %s" %(port)) s.listen(5) print("Waiting for connections") while True: c, addr = s.accept() print("Got a connection from",addr) c.send(bytes("Thank you for connecting to me. Currently we","utf-8")) c.send(bytes("Working on the server","utf-8")) c.close() </code></pre> <p><strong>This is the client code</strong></p> <pre><code># Import socket module import socket # Create a socket object s = socket.socket() # Define the port on which you want to connect port = 3642 # connect to the server on local computer s.connect(('MyIp..', port)) # receive data from the server print(s.recv(1024)) # close the connection s.close() </code></pre> <p>Everything works fine such as the connecting and the first message gets printed, however I can't get the second message to get printed. The one that says working on the server. I have just began learning about sockets and barely know anything about them so the solution probably is obvious it's just I can't seem to figure it out. Thank you for any responses. (I would appreciate thorough responses)</p>
0
2016-08-10T19:38:59Z
38,991,599
<p>If the two sent buffers happen to not get consolidated into a single buffer in the <code>recv</code> (which can happen based on timing, which OS you're running and other factors), then it makes sense that you would not see the second buffer because you're only making one <code>recv</code> call. If you want to receive everything the server sent, put the <code>recv</code> in a loop until it returns an empty string. (Empty string indicates end-of-file [i.e. socket closed by the other end].) – Gil Hamilton</p>
0
2016-08-17T08:24:59Z
[ "python", "sockets", "python-3.x" ]
What is the difference between using the '@patch.object' and 'with patch.object' in Python?
38,882,187
<p>In writing unit tests for my application, I have always been using the <code>@mock.patch</code> and <code>@patch.object</code> decorators. But now, for some unit tests when I use the decorator, I receive an error '<strong>TypeError: staticmethod object is not an iterator</strong>'.</p> <p>But with the same code, if I use <code>mock.patch.object</code> or <code>mock.patch.object</code>, everything works just fine.</p> <p>For example, in my test class I have this method:</p> <pre><code>@staticmethod def my_mock(): ...do something </code></pre> <p>When I try the following unit test</p> <pre><code>@mock.patch('mypackage.mymodule.my_method', side_effect=my_mock) def test_something(self, my_method_mocked): ...test something </code></pre> <p>I receive the error message stated before '<strong>TypeError: staticmethod object is not an iterator</strong>'.</p> <p>But when I try this way</p> <pre><code>def test_something(self): with patch.object(mymodule, "my_method") as mocked_method: mocked_method.side_effect = self.my_mock ...test something </code></pre> <p>then everything works perfectly.</p> <p>I've read the Python documentation about mock and unit tests, but I couldn't find any explanation for this behavior. </p> <p>What is the difference between using the <strong>decorator pattern</strong> and the <strong>with</strong> pattern? Where I can find more about this?</p> <p>Just to be more clear, this my code structure:</p> <pre><code>class TestClass(unittest.TestCase): @staticmethod def my_mock(): ...mock return service # doesn't work @mock.patch('mypackage.mymodule.my_method', side_effect=my_mock) def test_something(self, my_method_mocked): ...test something # work def test_something(self): with patch.object(mymodule, "my_method") as mocked_method: mocked_method.side_effect = self.my_mock ...test something </code></pre> <p>That's why I can't do <code>TestClass.my_mock</code>. If I do, I get a reference error.</p>
3
2016-08-10T19:42:14Z
38,882,551
<p>I think you just need to add the class name</p> <pre><code>class mymodule: @staticmethod def my_mock(): ...do something ... @mock.patch('mypackage.mymodule.my_method', side_effect=mymodule.my_mock) def test_something(self, my_method_mocked): ...test something </code></pre>
0
2016-08-10T20:03:57Z
[ "python", "python-2.7", "unit-testing", "python-unittest", "python-mock" ]
What is the difference between using the '@patch.object' and 'with patch.object' in Python?
38,882,187
<p>In writing unit tests for my application, I have always been using the <code>@mock.patch</code> and <code>@patch.object</code> decorators. But now, for some unit tests when I use the decorator, I receive an error '<strong>TypeError: staticmethod object is not an iterator</strong>'.</p> <p>But with the same code, if I use <code>mock.patch.object</code> or <code>mock.patch.object</code>, everything works just fine.</p> <p>For example, in my test class I have this method:</p> <pre><code>@staticmethod def my_mock(): ...do something </code></pre> <p>When I try the following unit test</p> <pre><code>@mock.patch('mypackage.mymodule.my_method', side_effect=my_mock) def test_something(self, my_method_mocked): ...test something </code></pre> <p>I receive the error message stated before '<strong>TypeError: staticmethod object is not an iterator</strong>'.</p> <p>But when I try this way</p> <pre><code>def test_something(self): with patch.object(mymodule, "my_method") as mocked_method: mocked_method.side_effect = self.my_mock ...test something </code></pre> <p>then everything works perfectly.</p> <p>I've read the Python documentation about mock and unit tests, but I couldn't find any explanation for this behavior. </p> <p>What is the difference between using the <strong>decorator pattern</strong> and the <strong>with</strong> pattern? Where I can find more about this?</p> <p>Just to be more clear, this my code structure:</p> <pre><code>class TestClass(unittest.TestCase): @staticmethod def my_mock(): ...mock return service # doesn't work @mock.patch('mypackage.mymodule.my_method', side_effect=my_mock) def test_something(self, my_method_mocked): ...test something # work def test_something(self): with patch.object(mymodule, "my_method") as mocked_method: mocked_method.side_effect = self.my_mock ...test something </code></pre> <p>That's why I can't do <code>TestClass.my_mock</code>. If I do, I get a reference error.</p>
3
2016-08-10T19:42:14Z
38,882,589
<p>You are seeing the effect of Python's descriptor protocol. The difference is not in how you are calling <code>patch</code>, but in the value you are assigning to the <code>side_effect</code> attribute in each case.</p> <pre><code>class A(object): @staticmethod def my_mock(): pass print type(my_mock) # As in your decorator case # As in your context manager case print type(A.my_mock) print type(A().my_mock) </code></pre> <p>If you run this code, you'll see that the <code>print</code> statement inside the class declaration outputs <code>&lt;type 'staticmethod'&gt;</code>, because you have a reference to the method itself.</p> <p>The other two <code>print</code> statements output <code>&lt;type 'function'&gt;</code> because you <em>don't</em> have a reference to the method; you have a reference to the return value of the method's <code>__get__</code> method. The two calls are equivalent to</p> <pre><code>print type(A.__dict__['my_mock'].__get__(A)) print type(A.__dict__['my_mock'].__get__(A())) </code></pre> <p>See <a href="https://docs.python.org/2/howto/descriptor.html" rel="nofollow">https://docs.python.org/2/howto/descriptor.html</a> for a fuller discussion of how descriptors are used to implement the three types of methods (static, class, and instance).</p> <hr> <p>The actual error comes about because <code>patch</code> expects a callable as the value of the <code>side_effect</code> argument, and failing that, it needs an iterable of return values. A <code>staticmethod</code> object is neither callable nor iterable. (Try it: <code>A.__dict__['my_mock']()</code>.)</p> <p>To ensure you get the function, you need to access the method through the class.</p> <pre><code>class Foo(object): @staticmethod def my_mock(): "whatever it does" @mock.patch('mypackage.mymodule.my_method', side_effect=Foo.my_mock) def test_something(self, my_method_mocked): ...test something </code></pre>
1
2016-08-10T20:06:33Z
[ "python", "python-2.7", "unit-testing", "python-unittest", "python-mock" ]
Why are my list structure math operations off by a couple billionths?
38,882,255
<p>I have some pretty simple function that tries to return a list that is the distance between the inputted list and the average of that list. The code <em>almost</em> works. Any thoughts as to why the results are slightly off?</p> <pre><code>def distances_from_average(test_list): average = [sum(test_list)/float(len(test_list))]*len(test_list) return [x-y for x,y in zip(test_list, average)] </code></pre> <p>Here are my example results: [-4.200000000000003, 35.8, 2.799999999999997, -23.200000000000003, -11.200000000000003] should equal [4.2, -35.8, -2.8, 23.2, 11.2] </p>
3
2016-08-10T19:46:05Z
38,882,281
<p>This is due to the way computers represent floating point numbers.</p> <p>They are not always accurate in the way you expect, and thus should not be used to check equality, or represent things like amounts of money.</p> <p>How are these numbers being used? If you need that kind of accuracy perhaps there are better ways to use the information, like checking for a range instead of checking equality.</p> <p><a href="https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html" rel="nofollow">Here is some good reading material on the subject</a></p>
7
2016-08-10T19:48:26Z
[ "python", "list" ]
Why are my list structure math operations off by a couple billionths?
38,882,255
<p>I have some pretty simple function that tries to return a list that is the distance between the inputted list and the average of that list. The code <em>almost</em> works. Any thoughts as to why the results are slightly off?</p> <pre><code>def distances_from_average(test_list): average = [sum(test_list)/float(len(test_list))]*len(test_list) return [x-y for x,y in zip(test_list, average)] </code></pre> <p>Here are my example results: [-4.200000000000003, 35.8, 2.799999999999997, -23.200000000000003, -11.200000000000003] should equal [4.2, -35.8, -2.8, 23.2, 11.2] </p>
3
2016-08-10T19:46:05Z
38,882,506
<p>Floating point can leading to surprising results if you do not fully consider how floating point is represented in binary and the rounding errors that can result. Floating point rounding errors are exacerbated in series summation. </p> <p>Examples:</p> <pre><code>&gt;&gt;&gt; sum([.1]*10) 0.9999999999999999 # 1.0 expected in decimal &gt;&gt;&gt; sum([.1]*1000) 99.9999999999986 # 100.0 expected &gt;&gt;&gt; sum([1, 1e100, 1, -1e100] * 10000) 0.0 # 20000 expected </code></pre> <p>There are numerous ways to get results that are exact (using the Decimal module, using the Fractions module, etc) Among other techniques, rounding errors can be eliminated by cancelation during summation. You can use <a href="https://docs.python.org/2/library/math.html#math.fsum" rel="nofollow">fsum</a> from the Python math library for more exact results with summation:</p> <pre><code>&gt;&gt;&gt; import math &gt;&gt;&gt; math.fsum([.1]*10) 1.0 &gt;&gt;&gt; math.fsum([.1]*1000) 100.0 &gt;&gt;&gt; math.fsum([1, 1e100, 1, -1e100] * 10000) 20000.0 </code></pre> <p>The <code>fsum</code> function is based on Raymond Hettinger's <a href="https://code.activestate.com/recipes/393090/" rel="nofollow">Active State</a> recipes. It is not <em>perfect</em> (try <code>math.fsum([1.1,2.2]*1000)</code>...) but it is pretty good. </p>
2
2016-08-10T20:01:42Z
[ "python", "list" ]
How to store X-Y data in order to use the functions in Numpy?
38,882,257
<p>Both <strong>Numpy</strong> and <strong>Scipy</strong> have a number of useful functions for performing operations on data (i.e. integrating, Fourier transforms, baseline correction, etc.). However, I haven't seen documentation regarding the general form for inputing X-Y data into these functions. Say I have a spectrum of wavelength and absorbance values, or stress and strain data from a mechanical properties test.</p> <p>Does one generally:</p> <ol> <li><p>Use two 1-D Numpy arrays, one for X, and one for Y?</p></li> <li><p>Use one 2-D Numpy array, with X on one axis, and Y on the other?</p></li> <li><p>Use a single <a href="http://stackoverflow.com/questions/15815999/is-there-a-standard-way-to-store-xy-data-in-python">structured array</a>?</p></li> </ol> <p>How does this change when you have XY-Z data?</p> <p>What is the most general data structure for XY data that allows me to input my data directly into <em>most</em> of these functions without redefining how I store my data?</p>
1
2016-08-10T19:46:20Z
38,883,395
<p>Check the documentation for each package and operational class or function. <code>scipy</code> is a collection of packages, written by different people, and often serving a interfaces to even older Fortran or C packages. So the input format is constrained by those sources. And they also depend on what is suitable for the problem.</p> <p>Often it is convenient to generate values on a regular grid. For example use <code>np.meshgrid</code> or <code>np.mgrid</code> with <code>arange</code> or <code>linspace</code> values to define a 2d space. The result can be 3 2d arrays - the <code>x</code> and <code>y</code> values, and the <code>z</code> as a function of those.</p> <p>But realworld data is often available as scatter points. Each point is then a <code>x</code>, <code>y</code> location with a <code>z</code> value. You can't cast those as 2d arrays, at least not without interpolation. So three 1d arrays is the appropriate representation. Or a <code>(n, 3)</code> matrix, one column for each of the variables. Or if the values have different dtype - say integer for x and y, float for z, then a structured array with 3 fields.</p> <p>Often data is loaded from csv files - the columns representing those <code>x,y,z</code> values, maybe with string labels, and multiple <code>z</code> values. With a mix of data types they are often loaded with <code>genfromtxt</code>, resulting in a 1d structured array.</p> <p>It's easy to map from structured arrays to multiple arrays with uniform dtype. Sometimes you do this by just indexing with the field name, other cases might require a <code>view</code>.</p> <p>To delve into this more you might need to expand on the data type(s), and the packages that you need to use. </p> <p><a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.griddata.html#scipy.interpolate.griddata" rel="nofollow">http://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.griddata.html#scipy.interpolate.griddata</a>. <code>interpolate.griddata</code> illustrates the use of both point data and grid data.</p>
2
2016-08-10T20:57:03Z
[ "python", "python-2.7", "numpy", "scientific-computing" ]
Lists in Python targeting specific characters
38,882,432
<p>I'm currently learning about lists in Python and I have a specific case that I don't really understand.</p> <pre><code>L=['hello','pie'] L[0][1] 'e' </code></pre> <p>Why does L[0][1] output as 'e'? I understand that L[0] = 'hello'. So I don't really understand how L[0][1] = 'e'.</p>
1
2016-08-10T19:57:14Z
38,882,472
<p>Because you can also index <strong>strings</strong> in Python.</p> <pre><code>In [1]: L = ['hello', 'pie'] In [2]: L[0] Out[2]: 'hello' In [3]: 'hello'[1] Out[3]: 'e' In [4]: L[0][1] Out[4]: 'e' </code></pre>
4
2016-08-10T19:59:16Z
[ "python" ]
Lists in Python targeting specific characters
38,882,432
<p>I'm currently learning about lists in Python and I have a specific case that I don't really understand.</p> <pre><code>L=['hello','pie'] L[0][1] 'e' </code></pre> <p>Why does L[0][1] output as 'e'? I understand that L[0] = 'hello'. So I don't really understand how L[0][1] = 'e'.</p>
1
2016-08-10T19:57:14Z
38,882,493
<p>A string in python is treated as a sequence of characters for purposes of indexing. Thus the string <code>'hello'</code> can be indexed as if it was the list <code>['h', 'e', 'l', 'l', 'o']</code>. As the index <code>[1]</code> refers to the second item in a sequence, you'll get the second letter of the string, <code>'e'</code>.</p>
4
2016-08-10T20:00:58Z
[ "python" ]
inherited class can not call base method in python using exec
38,882,434
<p>I have following code as text file (for example: code.txt)</p> <pre><code>from PyQt4 import QtGui, QtCore class Window(QtGui.QWidget): def __init__(self): QtGui.QWidget.__init__(self) self.button = QtGui.QPushButton('Test', self) self.button.clicked.connect(self.handleButton) layout = QtGui.QVBoxLayout(self) layout.addWidget(self.button) def handleButton(self): str = ''' class A: def a(self): print('Hello') pass class B(A): def a(self): super(B,self).a() print('World') pass b = B() b.a() ''' exec(str ) if __name__ == '__main__': import sys app = QtGui.QApplication(sys.argv) window = Window() window.show() sys.exit(app.exec_()) </code></pre> <p>run this command, I got following error:</p> <pre><code>Traceback (most recent call last): File "C:/Users/xxx/xxx/w.py", line 28, in handleButton exec(str ) File "&lt;string&gt;", line 14, in &lt;module&gt; File "&lt;string&gt;", line 9, in a NameError: name 'B' is not defined </code></pre> <p>without 'super(B,self).a()', it is ok. And if execute code in code.txt, it is also no problem</p>
0
2016-08-10T19:57:23Z
38,919,708
<p>Change code as following works:</p> <pre><code>from PyQt4 import QtGui, QtCore class Window(QtGui.QWidget): def __init__(self): QtGui.QWidget.__init__(self) self.button = QtGui.QPushButton('Test', self) self.button.clicked.connect(self.handleButton) layout = QtGui.QVBoxLayout(self) layout.addWidget(self.button) def handleButton(self): str = ''' class A: def a(self): print('Hello') pass class B(A): def a(self): super(B,self).a() print('World') pass b = B() b.a() ''' exec(str,globals() ) if __name__ == '__main__': import sys app = QtGui.QApplication(sys.argv) window = Window() window.show() sys.exit(app.exec_()) </code></pre> <p>you can see only difference is exec(str) and exec(str,globals()) </p>
0
2016-08-12T13:52:43Z
[ "python", "inheritance", "exec", "base" ]
Irregular Error - python cv2.imshow NameError: name "definition" is not defined
38,882,437
<p>I am running a video feed through a <code>cv2.imshow</code> operator. Most of the time, the code runs when I call it in command line, but occasionally I get the following NameError:</p> <pre><code>NameError: name 'masked' is not defined </code></pre> <p>However, 'masked' is absolutely defined before it is called in cv2.imshow:</p> <pre><code>image = frame.array miniframe = image masked = cv2.bitwise_and(image, image, mask=circle_img) cv2.imshow("frame", masked) </code></pre> <p>same thing happens when 'masked' is defined this way:</p> <pre><code>image = frame.array miniframe = image M = np.float32([[1,0,x+w/2],[0,1,y+h/2]]) masked = cv2.warpAffine(image, M, (x+w, y+h)) cv2.imshow("frame", masked) </code></pre> <p>When <code>print masked</code> is inserted above the <code>cv2.imshow</code> line, it results in the array printed as numbers - when the code is working. When it is not working, it results in the NameError traceback pointing to <code>print masked</code>.</p> <p>And to be clear, in either scenario the NameError happens seemingly randomly, without modification to the code. So, I can run it once or 20 times just fine, but then it will suddenly not work in command line, with a traceback to the <code>cv2.imshow</code> line. Sometimes, copy-pasting identical blocks of code from previous versions will get it to work again, but after a few unmodified tries, back to <code>NameError</code>. </p> <p>I have read over <a href="http://stackoverflow.com/questions/5756777/python-nameerror-when-var-is-most-definitely-defined">Python NameError when var IS most definitely defined</a>, and used <code>cat -A filename.py</code> to check the invisible control characters. After de- and re-indenting, it worked 2 more times, and then right back to the NameError.</p> <p>Any help would be much appreciated!</p>
0
2016-08-10T19:57:26Z
38,926,648
<p>Found a resolution. My problem was related to a condition in 'masked' that was not fulfilled. This is a program that relies on face detection, but my problem would be the same for any random, ongoing condition that must be fulfilled.</p> <p>Troubleshooting steps included: - reviewing my tracebacks - testing IRL by having a face in front of the camera on start, and then a hand over the camera on start. This confirmed that the program would run if a face was detected on start, but not if there was no face.</p> <p>To resolve the issue, I used a try/except condition for <code>cv2.imshow("frame", masked)</code>, resulting in code that looked like:</p> <pre><code>image = frame.array miniframe = image M = np.float32([[1,0,x+w/2],[0,1,y+h/2]]) masked = cv2.warpAffine(image, M, (x+w, y+h)) try: cv2.imshow("frame", masked) except NameError: cv2.imshow("frame", image) </code></pre> <p>I am a rank beginner, this really taught me the value of testing and reviewing tracebacks!</p>
0
2016-08-12T21:23:24Z
[ "python", "opencv", "nameerror", "imshow" ]
how do I create a wide-format data entry form if data is stored in long form in django
38,882,483
<p>Suppose I have a model for 'species' and a model for geographic 'locations'.</p> <pre><code>class species(models.Model): name = models.CharField(max_length=100) class location(models.Model): name=models.CharField(max_length=100) </code></pre> <p>I also have a third model <code>occurrences</code> that keeps track of occurrences of species at locations. (I realized I could also use a many-to-many field with a through table, but this is legacy code so I would prefer to keep it as is).</p> <pre><code>class occurrences(models.Model): species = models.ForeignKey(species) location = models.ForeignKey(location) </code></pre> <p>Ideally, I would like users to be able to enter new <code>occurrences</code> in a wide-table format. So schematically, the html form would look like this, with checkboxes:</p> <pre><code> | Location1 | Location2 | SpeciesA | x | | SpeciesB | | x | </code></pre> <p>When this form gets submitted it would create two new <code>occurrences</code> (SpeciesA at Location1, and SpeciesB at Location2).</p> <p><strong>This seems like a use case that others must have had, because users like spreadsheet formats. Is there a pre-existing django solution for allowing users to enter data in this format?</strong></p>
0
2016-08-10T20:00:07Z
38,885,384
<p>Building a <code>ManyToMany</code> relationship with these models will not break your existing code nor will it make any changes to the database. In fact you already have a <code>ManyToMany</code>, you just have to mark it as such.</p> <pre><code>class species(models.Model): name = models.CharField(max_length=100) species_locations = models.ManyToManyField(Locations,through='Occurrences') </code></pre> <p>When you run the migration you will note that it doesn't actually make any changes to the database.</p> <p>Additionally, you have an error in this model.</p> <pre><code>class occurrences(models.Model): species = models.ForeignKey(location) location = models.ForeignKey(location) </code></pre> <p>I do believe you intended <code>species</code> to be a foreign key to <code>Species</code></p> <p>The second part of the problem is mostly in HTML rendering, the django component to be used is <a href="https://docs.djangoproject.com/en/1.10/topics/forms/modelforms/#overriding-methods-on-an-inlineformset" rel="nofollow">InlineFormSet</a> this allows related models to be edited easily. (you do not need ManyToMany here if the Occcurence model is what's been edited in the form)</p>
1
2016-08-11T00:06:31Z
[ "python", "django", "forms", "django-forms" ]
Python: Using readine() in "for line in file:" Loop
38,882,522
<p>Lets say I have a text file that looks like:</p> <pre><code>a b start_flag c d e end_flag f g </code></pre> <p>I wish to iterate over this data line by line, but when I encounter a 'start_flag', I want to iterate until I reach an 'end_flag' and count the number of lines in between:</p> <pre><code>newline = '' for line in f: count = 0 if 'start_flag' in line: while 'end_flag' not in newline: count += 1 newline = f.readline() print(str(count)) </code></pre> <p>What is the expected behavior of this code? Will it iterate like:</p> <pre><code>a b start_flag c d e end_flag f g </code></pre> <p>Or:</p> <pre><code>a b start_flag c d e end_flag c d e end_flag f g </code></pre>
0
2016-08-10T20:02:21Z
38,882,663
<p>Use this: </p> <pre><code>enter = False count = 0 for line in f: if 'start_flag' in line: enter = True if 'end_flag' in line: print count count = 0 enter = False if enter is True: count+=1 </code></pre>
0
2016-08-10T20:11:59Z
[ "python" ]
Python: Using readine() in "for line in file:" Loop
38,882,522
<p>Lets say I have a text file that looks like:</p> <pre><code>a b start_flag c d e end_flag f g </code></pre> <p>I wish to iterate over this data line by line, but when I encounter a 'start_flag', I want to iterate until I reach an 'end_flag' and count the number of lines in between:</p> <pre><code>newline = '' for line in f: count = 0 if 'start_flag' in line: while 'end_flag' not in newline: count += 1 newline = f.readline() print(str(count)) </code></pre> <p>What is the expected behavior of this code? Will it iterate like:</p> <pre><code>a b start_flag c d e end_flag f g </code></pre> <p>Or:</p> <pre><code>a b start_flag c d e end_flag c d e end_flag f g </code></pre>
0
2016-08-10T20:02:21Z
38,882,715
<p>There shouldn't be any need to use <code>readline()</code>. Try it like this:</p> <pre><code>with open(path, 'r') as f: count = 0 counting = False for line in f: if 'start_flag' in line: counting = True elif 'end_flag' in line: counting = False #do something with your count result count = 0 #reset it for the next start_flag if counting is True: count += 1 </code></pre> <p>This handles it all with the <code>if</code> statements in the correct order, allowing you to just run sequentially through the file in one go. You could obviously add more operations into this, and do things with the results, for example appending them to a list if you expect to run into multiple start and end flags.</p>
0
2016-08-10T20:14:55Z
[ "python" ]
shift pandas multiindex values such that they don't have blanks below non blanks
38,882,595
<p>consider the following <code>df</code> with <code>pd.MultiIndex</code></p> <pre><code>col = pd.MultiIndex.from_tuples([('stat1', '', ''), ('stat2', '', ''), ('A', 'mean', 'blue'), ('A', 'mean', 'red'), ('B', 'var', 'blue'), ('B', 'var', 'red')]) df = pd.DataFrame(np.arange(24).reshape(4, 6), list('abcd'), col) df </code></pre> <p><a href="http://i.stack.imgur.com/zdk0a.png" rel="nofollow"><img src="http://i.stack.imgur.com/zdk0a.png" alt="enter image description here"></a></p> <p>I don't want <code>stat1</code> and <code>stat2</code> up on top. I want them at the bottom like this:</p> <p><a href="http://i.stack.imgur.com/QaDWe.png" rel="nofollow"><img src="http://i.stack.imgur.com/QaDWe.png" alt="enter image description here"></a></p> <hr> <p>An exaggerated example to get more to the point</p> <pre><code>col = pd.MultiIndex.from_tuples([('a', '', ''), ('', 'b', ''), ('c', 'd', ''), ('e', '', 'f'), ('g', 'h', 'i'), ('', 'j', 'k')]) df = pd.DataFrame(np.arange(24).reshape(4, 6), list('abcd'), col) df </code></pre> <p><a href="http://i.stack.imgur.com/Hf34p.png" rel="nofollow"><img src="http://i.stack.imgur.com/Hf34p.png" alt="enter image description here"></a></p> <p>Should look like:</p> <p><a href="http://i.stack.imgur.com/337MC.png" rel="nofollow"><img src="http://i.stack.imgur.com/337MC.png" alt="enter image description here"></a></p> <hr> <p>I've tried:</p> <pre><code>c = np.array(col.values.tolist()) c_ = pd.MultiIndex.from_tuples(np.sort(c).tolist()) pd.DataFrame(df.values, df.index, c_) </code></pre> <p><a href="http://i.stack.imgur.com/PSbx0.png" rel="nofollow"><img src="http://i.stack.imgur.com/PSbx0.png" alt="enter image description here"></a></p> <p>This isn't correct as some of the columns got sorted in ways that I didn't want.</p> <hr> <h3>Timing</h3> <p>So far, @root has the timing prize. I don't think I care too much about much larger indices. This is mainly for reporting.</p> <p><strong>code</strong></p> <pre><code>def pir(df): base = df.columns.to_series().apply(pd.Series).reset_index(drop=True) rplc = pd.DataFrame(np.where(base == '', None, base)) data = {k:v.dropna()[::-1].reset_index(drop=True) for k, v in rplc.iterrows()} new_col = pd.MultiIndex.from_tuples(pd.DataFrame(data)[::-1].fillna('').T.values.tolist()) return pd.DataFrame(df.values, df.index, new_col) def kartik(df): new_cols = [] for col in df.columns: col = list(col) if col[2] == '': col[2] = col[0] col[0] = '' new_cols.append(col) return pd.DataFrame(df.values, df.index, list(map(list, zip(*new_cols)))) def so44(df): tuple_list = df.columns.values new_tuple_list = [] for t in tuple_list: if t[2] == '': if t[1] == '': t = (t[1], t[2], t[0]) else: t = (t[2], t[0], t[1]) elif t[1] == '' and t[0] != '': t = (t[1], t[0], t[2]) new_tuple_list.append(t) return pd.DataFrame(df.values, df.index, pd.MultiIndex.from_tuples(new_tuple_list)) def root(df): new_cols = [['']*col.count('')+[x for x in col if x] for col in df.columns.values] return pd.DataFrame(df.values, df.index, pd.MultiIndex.from_tuples(new_cols)) return pd.DataFrame(df.values, df.index, pd.MultiIndex.from_tuples(new_tuple_list)) </code></pre> <p><a href="http://i.stack.imgur.com/dk77e.png" rel="nofollow"><img src="http://i.stack.imgur.com/dk77e.png" alt="enter image description here"></a></p>
3
2016-08-10T20:06:52Z
38,882,997
<p>piRSquared, try this:</p> <pre><code>In [1]: import pandas as pd import numpy as np In [2]: col = pd.MultiIndex.from_tuples([('a', '', ''), ('', 'b', ''), ('c', 'd', ''), ('e', '', 'f'), ('g', 'h', 'i'), ('', 'j', 'k')]) df = pd.DataFrame(np.arange(24).reshape(4, 6), list('abcd'), col) df Out[2]: a c e g b d h j f i k a 0 1 2 3 4 5 b 6 7 8 9 10 11 c 12 13 14 15 16 17 d 18 19 20 21 22 23 In [3]: new_cols = [] for col in df.columns: b = np.argsort([1 if (v != '') else 0 for v in col]) col = [col[i] for i in b] new_cols.append(col) df.columns = list(map(list, zip(*new_cols))) df Out[3]: g c e h j a b d f i k a 0 1 2 3 4 5 b 6 7 8 9 10 11 c 12 13 14 15 16 17 d 18 19 20 21 22 23 </code></pre> <hr> <h1>Timings</h1> <p>Running only one loop because:</p> <ol> <li>Getting cached copy warning</li> <li>OP probably will only run it once a time. Speed ups due to cached copies will be useless</li> </ol> <p><a href="http://i.stack.imgur.com/xHGyA.png" rel="nofollow"><img src="http://i.stack.imgur.com/xHGyA.png" alt="Timing Profiles"></a></p>
3
2016-08-10T20:31:18Z
[ "python", "pandas", "multi-index" ]
shift pandas multiindex values such that they don't have blanks below non blanks
38,882,595
<p>consider the following <code>df</code> with <code>pd.MultiIndex</code></p> <pre><code>col = pd.MultiIndex.from_tuples([('stat1', '', ''), ('stat2', '', ''), ('A', 'mean', 'blue'), ('A', 'mean', 'red'), ('B', 'var', 'blue'), ('B', 'var', 'red')]) df = pd.DataFrame(np.arange(24).reshape(4, 6), list('abcd'), col) df </code></pre> <p><a href="http://i.stack.imgur.com/zdk0a.png" rel="nofollow"><img src="http://i.stack.imgur.com/zdk0a.png" alt="enter image description here"></a></p> <p>I don't want <code>stat1</code> and <code>stat2</code> up on top. I want them at the bottom like this:</p> <p><a href="http://i.stack.imgur.com/QaDWe.png" rel="nofollow"><img src="http://i.stack.imgur.com/QaDWe.png" alt="enter image description here"></a></p> <hr> <p>An exaggerated example to get more to the point</p> <pre><code>col = pd.MultiIndex.from_tuples([('a', '', ''), ('', 'b', ''), ('c', 'd', ''), ('e', '', 'f'), ('g', 'h', 'i'), ('', 'j', 'k')]) df = pd.DataFrame(np.arange(24).reshape(4, 6), list('abcd'), col) df </code></pre> <p><a href="http://i.stack.imgur.com/Hf34p.png" rel="nofollow"><img src="http://i.stack.imgur.com/Hf34p.png" alt="enter image description here"></a></p> <p>Should look like:</p> <p><a href="http://i.stack.imgur.com/337MC.png" rel="nofollow"><img src="http://i.stack.imgur.com/337MC.png" alt="enter image description here"></a></p> <hr> <p>I've tried:</p> <pre><code>c = np.array(col.values.tolist()) c_ = pd.MultiIndex.from_tuples(np.sort(c).tolist()) pd.DataFrame(df.values, df.index, c_) </code></pre> <p><a href="http://i.stack.imgur.com/PSbx0.png" rel="nofollow"><img src="http://i.stack.imgur.com/PSbx0.png" alt="enter image description here"></a></p> <p>This isn't correct as some of the columns got sorted in ways that I didn't want.</p> <hr> <h3>Timing</h3> <p>So far, @root has the timing prize. I don't think I care too much about much larger indices. This is mainly for reporting.</p> <p><strong>code</strong></p> <pre><code>def pir(df): base = df.columns.to_series().apply(pd.Series).reset_index(drop=True) rplc = pd.DataFrame(np.where(base == '', None, base)) data = {k:v.dropna()[::-1].reset_index(drop=True) for k, v in rplc.iterrows()} new_col = pd.MultiIndex.from_tuples(pd.DataFrame(data)[::-1].fillna('').T.values.tolist()) return pd.DataFrame(df.values, df.index, new_col) def kartik(df): new_cols = [] for col in df.columns: col = list(col) if col[2] == '': col[2] = col[0] col[0] = '' new_cols.append(col) return pd.DataFrame(df.values, df.index, list(map(list, zip(*new_cols)))) def so44(df): tuple_list = df.columns.values new_tuple_list = [] for t in tuple_list: if t[2] == '': if t[1] == '': t = (t[1], t[2], t[0]) else: t = (t[2], t[0], t[1]) elif t[1] == '' and t[0] != '': t = (t[1], t[0], t[2]) new_tuple_list.append(t) return pd.DataFrame(df.values, df.index, pd.MultiIndex.from_tuples(new_tuple_list)) def root(df): new_cols = [['']*col.count('')+[x for x in col if x] for col in df.columns.values] return pd.DataFrame(df.values, df.index, pd.MultiIndex.from_tuples(new_cols)) return pd.DataFrame(df.values, df.index, pd.MultiIndex.from_tuples(new_tuple_list)) </code></pre> <p><a href="http://i.stack.imgur.com/dk77e.png" rel="nofollow"><img src="http://i.stack.imgur.com/dk77e.png" alt="enter image description here"></a></p>
3
2016-08-10T20:06:52Z
38,883,135
<pre><code>tuple_list = df.columns.values new_tuple_list = [] for t in tuple_list: if t[2] == '': if t[1] == '': t = (t[1], t[2], t[0]) else: t = (t[2], t[0], t[1]) elif t[1] == '' and t[0] != '': t = (t[1], t[0], t[2]) new_tuple_list.append(t) df.columns = pd.MultiIndex.from_tuples(new_tuple_list) </code></pre> <p>This is better and should work for headers with more levels:</p> <pre><code>tuple_list = df.columns.values new_tuple_list = [] for t in tuple_list: header_only = [x for x in t if x != ''] leading_empty = ['' for x in range(0, 3-len(header_only))] new_tuple = tuple(leading_empty + header_only) new_tuple_list.append(new_tuple) df.columns = pd.MultiIndex.from_tuples(new_tuple_list) </code></pre>
3
2016-08-10T20:40:50Z
[ "python", "pandas", "multi-index" ]
shift pandas multiindex values such that they don't have blanks below non blanks
38,882,595
<p>consider the following <code>df</code> with <code>pd.MultiIndex</code></p> <pre><code>col = pd.MultiIndex.from_tuples([('stat1', '', ''), ('stat2', '', ''), ('A', 'mean', 'blue'), ('A', 'mean', 'red'), ('B', 'var', 'blue'), ('B', 'var', 'red')]) df = pd.DataFrame(np.arange(24).reshape(4, 6), list('abcd'), col) df </code></pre> <p><a href="http://i.stack.imgur.com/zdk0a.png" rel="nofollow"><img src="http://i.stack.imgur.com/zdk0a.png" alt="enter image description here"></a></p> <p>I don't want <code>stat1</code> and <code>stat2</code> up on top. I want them at the bottom like this:</p> <p><a href="http://i.stack.imgur.com/QaDWe.png" rel="nofollow"><img src="http://i.stack.imgur.com/QaDWe.png" alt="enter image description here"></a></p> <hr> <p>An exaggerated example to get more to the point</p> <pre><code>col = pd.MultiIndex.from_tuples([('a', '', ''), ('', 'b', ''), ('c', 'd', ''), ('e', '', 'f'), ('g', 'h', 'i'), ('', 'j', 'k')]) df = pd.DataFrame(np.arange(24).reshape(4, 6), list('abcd'), col) df </code></pre> <p><a href="http://i.stack.imgur.com/Hf34p.png" rel="nofollow"><img src="http://i.stack.imgur.com/Hf34p.png" alt="enter image description here"></a></p> <p>Should look like:</p> <p><a href="http://i.stack.imgur.com/337MC.png" rel="nofollow"><img src="http://i.stack.imgur.com/337MC.png" alt="enter image description here"></a></p> <hr> <p>I've tried:</p> <pre><code>c = np.array(col.values.tolist()) c_ = pd.MultiIndex.from_tuples(np.sort(c).tolist()) pd.DataFrame(df.values, df.index, c_) </code></pre> <p><a href="http://i.stack.imgur.com/PSbx0.png" rel="nofollow"><img src="http://i.stack.imgur.com/PSbx0.png" alt="enter image description here"></a></p> <p>This isn't correct as some of the columns got sorted in ways that I didn't want.</p> <hr> <h3>Timing</h3> <p>So far, @root has the timing prize. I don't think I care too much about much larger indices. This is mainly for reporting.</p> <p><strong>code</strong></p> <pre><code>def pir(df): base = df.columns.to_series().apply(pd.Series).reset_index(drop=True) rplc = pd.DataFrame(np.where(base == '', None, base)) data = {k:v.dropna()[::-1].reset_index(drop=True) for k, v in rplc.iterrows()} new_col = pd.MultiIndex.from_tuples(pd.DataFrame(data)[::-1].fillna('').T.values.tolist()) return pd.DataFrame(df.values, df.index, new_col) def kartik(df): new_cols = [] for col in df.columns: col = list(col) if col[2] == '': col[2] = col[0] col[0] = '' new_cols.append(col) return pd.DataFrame(df.values, df.index, list(map(list, zip(*new_cols)))) def so44(df): tuple_list = df.columns.values new_tuple_list = [] for t in tuple_list: if t[2] == '': if t[1] == '': t = (t[1], t[2], t[0]) else: t = (t[2], t[0], t[1]) elif t[1] == '' and t[0] != '': t = (t[1], t[0], t[2]) new_tuple_list.append(t) return pd.DataFrame(df.values, df.index, pd.MultiIndex.from_tuples(new_tuple_list)) def root(df): new_cols = [['']*col.count('')+[x for x in col if x] for col in df.columns.values] return pd.DataFrame(df.values, df.index, pd.MultiIndex.from_tuples(new_cols)) return pd.DataFrame(df.values, df.index, pd.MultiIndex.from_tuples(new_tuple_list)) </code></pre> <p><a href="http://i.stack.imgur.com/dk77e.png" rel="nofollow"><img src="http://i.stack.imgur.com/dk77e.png" alt="enter image description here"></a></p>
3
2016-08-10T20:06:52Z
38,883,320
<p><strong><em>I will filter the answers based on aesthetics and run timing to choose</em></strong></p> <p>I will not choose my answer!</p> <p>What I came up with:</p> <pre><code>base = df.columns.to_series().apply(pd.Series).reset_index(drop=True) rplc = pd.DataFrame(np.where(base == '', None, base)) data = {k:v.dropna()[::-1].reset_index(drop=True) for k, v in rplc.iterrows()} new_col = pd.MultiIndex.from_tuples(pd.DataFrame(data)[::-1].fillna('').T.values.tolist()) df.columns = new_col df </code></pre> <p><a href="http://i.stack.imgur.com/nAco0.png" rel="nofollow"><img src="http://i.stack.imgur.com/nAco0.png" alt="enter image description here"></a></p>
4
2016-08-10T20:52:11Z
[ "python", "pandas", "multi-index" ]
shift pandas multiindex values such that they don't have blanks below non blanks
38,882,595
<p>consider the following <code>df</code> with <code>pd.MultiIndex</code></p> <pre><code>col = pd.MultiIndex.from_tuples([('stat1', '', ''), ('stat2', '', ''), ('A', 'mean', 'blue'), ('A', 'mean', 'red'), ('B', 'var', 'blue'), ('B', 'var', 'red')]) df = pd.DataFrame(np.arange(24).reshape(4, 6), list('abcd'), col) df </code></pre> <p><a href="http://i.stack.imgur.com/zdk0a.png" rel="nofollow"><img src="http://i.stack.imgur.com/zdk0a.png" alt="enter image description here"></a></p> <p>I don't want <code>stat1</code> and <code>stat2</code> up on top. I want them at the bottom like this:</p> <p><a href="http://i.stack.imgur.com/QaDWe.png" rel="nofollow"><img src="http://i.stack.imgur.com/QaDWe.png" alt="enter image description here"></a></p> <hr> <p>An exaggerated example to get more to the point</p> <pre><code>col = pd.MultiIndex.from_tuples([('a', '', ''), ('', 'b', ''), ('c', 'd', ''), ('e', '', 'f'), ('g', 'h', 'i'), ('', 'j', 'k')]) df = pd.DataFrame(np.arange(24).reshape(4, 6), list('abcd'), col) df </code></pre> <p><a href="http://i.stack.imgur.com/Hf34p.png" rel="nofollow"><img src="http://i.stack.imgur.com/Hf34p.png" alt="enter image description here"></a></p> <p>Should look like:</p> <p><a href="http://i.stack.imgur.com/337MC.png" rel="nofollow"><img src="http://i.stack.imgur.com/337MC.png" alt="enter image description here"></a></p> <hr> <p>I've tried:</p> <pre><code>c = np.array(col.values.tolist()) c_ = pd.MultiIndex.from_tuples(np.sort(c).tolist()) pd.DataFrame(df.values, df.index, c_) </code></pre> <p><a href="http://i.stack.imgur.com/PSbx0.png" rel="nofollow"><img src="http://i.stack.imgur.com/PSbx0.png" alt="enter image description here"></a></p> <p>This isn't correct as some of the columns got sorted in ways that I didn't want.</p> <hr> <h3>Timing</h3> <p>So far, @root has the timing prize. I don't think I care too much about much larger indices. This is mainly for reporting.</p> <p><strong>code</strong></p> <pre><code>def pir(df): base = df.columns.to_series().apply(pd.Series).reset_index(drop=True) rplc = pd.DataFrame(np.where(base == '', None, base)) data = {k:v.dropna()[::-1].reset_index(drop=True) for k, v in rplc.iterrows()} new_col = pd.MultiIndex.from_tuples(pd.DataFrame(data)[::-1].fillna('').T.values.tolist()) return pd.DataFrame(df.values, df.index, new_col) def kartik(df): new_cols = [] for col in df.columns: col = list(col) if col[2] == '': col[2] = col[0] col[0] = '' new_cols.append(col) return pd.DataFrame(df.values, df.index, list(map(list, zip(*new_cols)))) def so44(df): tuple_list = df.columns.values new_tuple_list = [] for t in tuple_list: if t[2] == '': if t[1] == '': t = (t[1], t[2], t[0]) else: t = (t[2], t[0], t[1]) elif t[1] == '' and t[0] != '': t = (t[1], t[0], t[2]) new_tuple_list.append(t) return pd.DataFrame(df.values, df.index, pd.MultiIndex.from_tuples(new_tuple_list)) def root(df): new_cols = [['']*col.count('')+[x for x in col if x] for col in df.columns.values] return pd.DataFrame(df.values, df.index, pd.MultiIndex.from_tuples(new_cols)) return pd.DataFrame(df.values, df.index, pd.MultiIndex.from_tuples(new_tuple_list)) </code></pre> <p><a href="http://i.stack.imgur.com/dk77e.png" rel="nofollow"><img src="http://i.stack.imgur.com/dk77e.png" alt="enter image description here"></a></p>
3
2016-08-10T20:06:52Z
38,883,602
<p>Generalized approach to rearranging each column tuple:</p> <pre><code>new_cols = [['']*col.count('')+[x for x in col if x != ''] for col in df.columns.values] df.columns = pd.MultiIndex.from_tuples(new_cols) </code></pre> <p>It might not be as fast as other methods that were tuned for a specific number of levels, but it's concise and should work for an arbitrary number of levels.</p>
5
2016-08-10T21:10:24Z
[ "python", "pandas", "multi-index" ]
how to split String with a "pattern" from list
38,882,641
<p>I've got a small problem with finding part of string in a list with python. </p> <p>I load the string from a file and the value is one of the following: <code>(none, 1 from list, 2 from list, 3 from list or more...)</code> </p> <p>I need to perform different actions depending on whether the String equals <code>""</code>, the String equals <code>1 element from list</code>, or if the String is for 2 or more elements. For Example:</p> <pre><code>List = [ 'Aaron', 'Albert', 'Arcady', 'Leo', 'John' ... ] String = "" #this is just example String = "Aaron" #this is just example String = "AaronAlbert" #this is just example String = "LeoJohnAaron" #this is just example </code></pre> <p>I created something like this:</p> <pre><code>if String == "": #this works well on Strings with 0 values print "something" elif String in List: #this works well on Strings with 1 value print "something else" elif ... #dont know what now </code></pre> <p>The best way would be to split this String with a pattern from a list. I was trying:</p> <pre><code>String.Find(x) #failed. </code></pre> <p>I tried to find similar posts but couldn't.</p>
0
2016-08-10T20:09:47Z
38,882,705
<pre><code>if String == "": #this works well on Strings with 0 values print "something" elif String in List: #this works well on Strings with 1 value print "something else" elif len([1 for x in List if x in String]) == 2 ... </code></pre> <p>This is called a list comprehension, it will go through the list and find all of the list elements that have a substring in common with the string at hand, then return the length of that.</p> <p>Note that there may be some issues if you have a name like "Ann" and "Anna", the name "Anna" in the string will get counted twice. If you need a solution that accounts for that, I would suggest splitting on capital letters to explicitly separate the list into separate names by splitting on capital letters (If you want I can update this solution to show how to do that with regex)</p>
0
2016-08-10T20:14:32Z
[ "python", "string", "list", "python-2.7" ]
how to split String with a "pattern" from list
38,882,641
<p>I've got a small problem with finding part of string in a list with python. </p> <p>I load the string from a file and the value is one of the following: <code>(none, 1 from list, 2 from list, 3 from list or more...)</code> </p> <p>I need to perform different actions depending on whether the String equals <code>""</code>, the String equals <code>1 element from list</code>, or if the String is for 2 or more elements. For Example:</p> <pre><code>List = [ 'Aaron', 'Albert', 'Arcady', 'Leo', 'John' ... ] String = "" #this is just example String = "Aaron" #this is just example String = "AaronAlbert" #this is just example String = "LeoJohnAaron" #this is just example </code></pre> <p>I created something like this:</p> <pre><code>if String == "": #this works well on Strings with 0 values print "something" elif String in List: #this works well on Strings with 1 value print "something else" elif ... #dont know what now </code></pre> <p>The best way would be to split this String with a pattern from a list. I was trying:</p> <pre><code>String.Find(x) #failed. </code></pre> <p>I tried to find similar posts but couldn't.</p>
0
2016-08-10T20:09:47Z
38,882,710
<p>I think the most straightforward approach would be to loop over the list of names and for each of them check if its in your string.</p> <pre><code>for name in List: if name in String: print("do something here") </code></pre>
0
2016-08-10T20:14:42Z
[ "python", "string", "list", "python-2.7" ]
how to split String with a "pattern" from list
38,882,641
<p>I've got a small problem with finding part of string in a list with python. </p> <p>I load the string from a file and the value is one of the following: <code>(none, 1 from list, 2 from list, 3 from list or more...)</code> </p> <p>I need to perform different actions depending on whether the String equals <code>""</code>, the String equals <code>1 element from list</code>, or if the String is for 2 or more elements. For Example:</p> <pre><code>List = [ 'Aaron', 'Albert', 'Arcady', 'Leo', 'John' ... ] String = "" #this is just example String = "Aaron" #this is just example String = "AaronAlbert" #this is just example String = "LeoJohnAaron" #this is just example </code></pre> <p>I created something like this:</p> <pre><code>if String == "": #this works well on Strings with 0 values print "something" elif String in List: #this works well on Strings with 1 value print "something else" elif ... #dont know what now </code></pre> <p>The best way would be to split this String with a pattern from a list. I was trying:</p> <pre><code>String.Find(x) #failed. </code></pre> <p>I tried to find similar posts but couldn't.</p>
0
2016-08-10T20:09:47Z
38,882,713
<p>So, you want to find whether some string contains any members of the given list.</p> <p>Iterate over the list and check whether the string contains the current item:</p> <pre><code>for data in List: if data in String: print("Found it!") </code></pre>
0
2016-08-10T20:14:49Z
[ "python", "string", "list", "python-2.7" ]
How to return a value from a recursive Python function?
38,882,826
<p>This question seems a bit specific, and for that I'm sorry, but it has me stumped. I'm writing myself a password generator, one that takes a string (aka the URL of a website) and processes it into a secure password that can't be backtracked based on the name of the website. </p> <p>In part of the code, I created a recursive function that looks like this:</p> <pre><code>def get_number(n = 0, nums = ''): for i in range(0, len(url)): #both n and nums are changed if len(nums) &lt; num_length: get_number(n, nums) else: print(nums) return(nums) </code></pre> <p>...</p> <pre><code>print(get_number()) </code></pre> <p>I would expect 'nums' to output twice, since I print it in the else block and print the return later on. But, if it does go through a recursive loop, 'nums' is printed from the else block and the function returns 'None'. If <code>if len(nums) &lt; num_length</code> is false the first time, then it returns the proper value.</p> <p>Why would it return 'None', if I verified that the object it is returning is not in fact 'None' the line before?</p> <p>I'm a little new to Python, do they handle recursions differently?</p> <p>Thank you for your time</p> <p><strong>Edit:</strong></p> <p>Problem fixed. Forgot a return statement on the recursive call. Thanks :D</p>
0
2016-08-10T20:21:02Z
38,882,877
<p>I think you're missing a <code>return</code> before the nested <code>get_number</code>. So, it's executing and returning, but you aren't doing anything with the recursed value.</p> <pre><code>def get_number(n = 0, nums = ''): for i in range(0, len(url)): #both n and nums are changed if len(nums) &lt; num_length: return get_number(n, nums) print(nums) return nums </code></pre>
1
2016-08-10T20:23:50Z
[ "python", "function", "recursion", "return" ]
Multiplying each element in two list of lists in python
38,882,866
<p>I have an assignment to generate the following lists using only basic python functions (no numpy). Here is all of my code:</p> <pre><code>#1.Create a list which contains i^2 with i = 1 through 5 squares = [pow(i,2) for i in range(1,6)] #print squares #2. Create a list which contains log[j] with j = 1 through 5 logs = map(math.log10,range(1,6)) #print logs #3. Create a list which contains [i_1*j_1, i_2*j_2, i_3,j_3...] def mult(x,y): return x*y lmultl = map(mult,squares,logs) #print lmultl #4 Create a list which contains [[i_1*j_1, i_1*j_2, i_1*j_3...][i_2*j_1, i_2*j_2, i_2*j_3...]etc] logslol = [[logs]*5] #Returns a list of lists with 5 copies of list "logs" def lrep(x): return [x,x,x,x,x] #Returns a list w/ 5 copies of each integer squareslol= map(lrep,squares) #Returns list of lists "for squares" print map(mult,logslol,squareslol) #Attempt 1 to create goal list print [logslol*item for item in squareslol] #Attempt 2 to create goal list </code></pre> <p>My Question is for the final print statements in list #4: I am getting a TypeError: "can't multiply sequence by non-int of type 'list'" for both methods. Is there a more efficient way to multiply each element in two "list of lists"? </p>
0
2016-08-10T20:23:16Z
38,882,999
<p>Try this approach:</p> <pre><code>results = [] for i,j in zip(squares,logs) x = i*j results.append(x) </code></pre>
0
2016-08-10T20:31:25Z
[ "python", "math" ]
Multiplying each element in two list of lists in python
38,882,866
<p>I have an assignment to generate the following lists using only basic python functions (no numpy). Here is all of my code:</p> <pre><code>#1.Create a list which contains i^2 with i = 1 through 5 squares = [pow(i,2) for i in range(1,6)] #print squares #2. Create a list which contains log[j] with j = 1 through 5 logs = map(math.log10,range(1,6)) #print logs #3. Create a list which contains [i_1*j_1, i_2*j_2, i_3,j_3...] def mult(x,y): return x*y lmultl = map(mult,squares,logs) #print lmultl #4 Create a list which contains [[i_1*j_1, i_1*j_2, i_1*j_3...][i_2*j_1, i_2*j_2, i_2*j_3...]etc] logslol = [[logs]*5] #Returns a list of lists with 5 copies of list "logs" def lrep(x): return [x,x,x,x,x] #Returns a list w/ 5 copies of each integer squareslol= map(lrep,squares) #Returns list of lists "for squares" print map(mult,logslol,squareslol) #Attempt 1 to create goal list print [logslol*item for item in squareslol] #Attempt 2 to create goal list </code></pre> <p>My Question is for the final print statements in list #4: I am getting a TypeError: "can't multiply sequence by non-int of type 'list'" for both methods. Is there a more efficient way to multiply each element in two "list of lists"? </p>
0
2016-08-10T20:23:16Z
39,151,246
<pre><code>import math squares = [pow(i,2) for i in range(1,6)] logs = map(math.log10,range(1,6)) mult = lambda x,y: x*y lmultl = map(mult,squares,logs) </code></pre> <p>I assume for you elements in <code>squares</code> are i_1, i_2, i_3... and elements in <code>logs</code> are j_1, j_2, j_3...</p> <p>And you want to create a list multiplying each element of <code>squares</code> with each element of <code>logs</code> which contains [[i_1*j_1, i_1*j_2, i_1*j_3...] [i_2*j_1, i_2*j_2, i_2*j_3...] etc], then use the below code :-</p> <pre><code>sqr_mul_log = [[m*n for m in logs ] for n in squares] </code></pre> <p>For the reverse sequence i.e. multiplying each element of <code>logs</code> with each element of <code>squares</code> which contains [[j_1*i_1, j_1*i_2, j_1*i_3...] [j_2*i_1, j_2*i_2, j_2*i_3...] etc], then use the below code :-</p> <pre><code>log_mul_sqr = [[m*n for m in squares] for n in logs] </code></pre> <p>Also, this will remove the overhead of creating <code>squareslol</code> and <code>logslol</code> that you are creating at #4</p>
0
2016-08-25T17:21:12Z
[ "python", "math" ]
Python 2.7 mock relative import
38,882,882
<p>Background: Wanna build a documenation for a package, which imports a C-extension relatively, eg. in an __ init__.py. Lets assume this package is called mypkg.sub. So c_ext resides in sub.</p> <p>init.py of sub:</p> <pre><code>from __future__ import absolute_import from . import c_ext </code></pre> <p>When I mock this extension I do the following in my Sphinx conf.py:</p> <pre><code>from mock import Mock sys.modules['mypkg.sub.c_ext'] = Mock() </code></pre> <p>However I still get an import error:</p> <blockquote> <p>ImportError: cannot import name c_ext</p> </blockquote> <p>The funny thing is, that the same thing works on Python3 (which has a slightly different import behaviour).</p> <p>Any hints appreciated!</p>
1
2016-08-10T20:24:09Z
39,001,253
<p>It turns out that one can not mock c-extensions under Python-2.7, if they are relatively imported. I worked around that by using a meta_path hook to patch only these extensions.</p>
0
2016-08-17T15:54:44Z
[ "python", "python-2.7", "mocking", "python-sphinx", "python-import" ]
apply a function to a list and multiple single arguments
38,882,891
<p>I have this definition that applies a function over a list of elements and a single additional argument that is needed for a function to execute. How can I modify it to apply arbitrary number of single arguments? Example:</p> <p>Current method: </p> <pre><code>def ProcessListArg(_func, _list, _arg): return map( lambda x: ProcessListArg(_func, x, _arg) if type(x)==list else _func(x, _arg), _list ) </code></pre> <p>for that to work i need a function that takes two arguments. Ex:</p> <pre><code>def SomeFunction(arg1, arg2): return something </code></pre> <p>I would apply it like so: </p> <pre><code>output = ProcessListArg(SomeFunction, inputArg1List, inputArg2) </code></pre> <p>I want to modify ProcessListArg to take advantage of multiple single arguments like so: </p> <pre><code>def SomeFunction2(arg1, arg2, arg3): return something </code></pre> <p>Then I would apply it like so: </p> <pre><code>output = ProcessListArgs(SomeFunction2, inputArg1List, inputArg2, inputArg3) </code></pre> <p>I tried this:</p> <pre><code>def ProcessListArgs(_func, _list, *args): return map( lambda *xs: ProcessListArgs(_func *xs) if all(type(x) is list for x in xs) else _func(*xs), *args) </code></pre> <p>That throws an error that argument is not iterable. </p> <p>Thanks! </p>
0
2016-08-10T20:24:41Z
38,883,048
<p>I believe this does what you want. </p> <pre><code>def SomeFunction(arg1, arg2): print "SomeFunction", arg1, arg2 def SomeFunction2(arg1, arg2, arg3): print "SomeFunction", arg1, arg2, arg3 def ProcessListArg(_func, _list, *_arg): return map(lambda x: ProcessListArg(_func, x, *_arg) if type(x) == list else _func(x, *_arg), _list) ProcessListArg(SomeFunction, [1, 2, [2.1, 2.2, 2.3], 3], 4) ProcessListArg(SomeFunction2, [1, 2, [2.1, 2.2, 2.3], 3], 4, 5) </code></pre>
1
2016-08-10T20:33:47Z
[ "python" ]
Python Convert all csv files in folder to txt
38,882,913
<p>I have this code that converts my csv file into a txt version of an xml file.. How can I edit this to convert all files in a folder?</p> <pre><code>import csv csvFile = 'path\to\input\123.csv' xmlFile = 'path\to\output\123.txt' csvData = csv.reader(open(csvFile)) xmlData = open(xmlFile, 'w') rowNum = 0 for row in csvData: if rowNum == 0: tags = row # replace spaces w/ underscores in tag names for i in range(len(tags)): tags[i] = tags[i].replace(' ', '_') else: xmlData.write('&lt;products_joined&gt;' + "\n") for i in range(len(tags)): xmlData.write(' ' + '&lt;' + tags[i] + '&gt;&lt;![CDATA[' \ + row[i] + ']]&gt;&lt;/' + tags[i] + '&gt;' + "\n") xmlData.write('&lt;/products_joined&gt;' + "\n") rowNum +=1 xmlData.close() </code></pre>
0
2016-08-10T20:26:10Z
38,883,029
<p>You can use <code>glob</code>:</p> <pre><code>import glob, os os.chdir("/mydir") for file in glob.glob("*.txt"): print(file) </code></pre> <p>Found here : <a href="http://stackoverflow.com/questions/3964681/find-all-files-in-directory-with-extension-txt-in-python">Find all files in directory with extension .txt in Python</a></p>
1
2016-08-10T20:33:01Z
[ "python", "python-2.7", "python-3.4" ]
Python Convert all csv files in folder to txt
38,882,913
<p>I have this code that converts my csv file into a txt version of an xml file.. How can I edit this to convert all files in a folder?</p> <pre><code>import csv csvFile = 'path\to\input\123.csv' xmlFile = 'path\to\output\123.txt' csvData = csv.reader(open(csvFile)) xmlData = open(xmlFile, 'w') rowNum = 0 for row in csvData: if rowNum == 0: tags = row # replace spaces w/ underscores in tag names for i in range(len(tags)): tags[i] = tags[i].replace(' ', '_') else: xmlData.write('&lt;products_joined&gt;' + "\n") for i in range(len(tags)): xmlData.write(' ' + '&lt;' + tags[i] + '&gt;&lt;![CDATA[' \ + row[i] + ']]&gt;&lt;/' + tags[i] + '&gt;' + "\n") xmlData.write('&lt;/products_joined&gt;' + "\n") rowNum +=1 xmlData.close() </code></pre>
0
2016-08-10T20:26:10Z
38,883,031
<p>You could use glob to get all of the files in the folder then iterate over each of the files. You can make what you have a method then run the loop over the method and pass in the filename. <a href="https://docs.python.org/2/library/glob.html" rel="nofollow">https://docs.python.org/2/library/glob.html</a> This gives an explanation of the glob function. </p> <pre><code>for file_path in Path('src').glob('**/*.c'): make_xml(file_path) </code></pre>
1
2016-08-10T20:33:06Z
[ "python", "python-2.7", "python-3.4" ]
Convert recursive tree walking function to iterative
38,882,928
<p>How can the following recursive function <code>walk()</code> be converted to an iterative function?</p> <p>Walking the nodes in the same order iteratively is easy using a stack, but I'm unable to figure out how to write an iterative function that will print both the opening and closing tags of each node like the recursive version does.</p> <p><strong>Code:</strong></p> <pre><code>class Node(object): def __init__(self, name, children=[]): self.name = name self.children = children def walk(node): print('&lt;', node.name, '&gt;', sep='') for n in node.children: walk(n) print('&lt;/', node.name, '&gt;', sep='') root = \ Node('html', [ Node('head'), Node('body', [ Node('div'), Node('p', [ Node('a'), ]) ]), ]) walk(root) </code></pre> <p><strong>Output:</strong></p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;/head&gt; &lt;body&gt; &lt;div&gt; &lt;/div&gt; &lt;p&gt; &lt;a&gt; &lt;/a&gt; &lt;/p&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p><strong>Code that traverses the tree iteratively:</strong></p> <p>The function visits the nodes in the correct order, but obviously does not print the closing tags.</p> <pre><code>def walk(node): stack = [] stack.append(node) while len(stack) &gt; 0: node = stack.pop() for child in reversed(node.children): stack.append(child) print(node.name) </code></pre>
0
2016-08-10T20:26:33Z
38,883,351
<p>The problem is that for this to work you also need to record on the stack where the node ends. A possible solution would be:</p> <pre><code>def walk(root): stack = [] stack.append(root) indent = 0 while stack: node = stack.pop() if isinstance(node, Node): print(' ' * indent, "&lt;", node.name, "&gt;", sep="") indent += 1 stack.append(node.name) stack.extend(reversed(node.children)) else: indent -= 1 print(' ' * indent, "&lt;/", node, "&gt;", sep="") </code></pre> <p>I've added indenting so the output is nicer:</p> <pre class="lang-none prettyprint-override"><code>&lt;html&gt; &lt;head&gt; &lt;/head&gt; &lt;body&gt; &lt;div&gt; &lt;/div&gt; &lt;p&gt; &lt;a&gt; &lt;/a&gt; &lt;/p&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
0
2016-08-10T20:54:12Z
[ "python", "recursion", "tree", "iteration" ]
Convert recursive tree walking function to iterative
38,882,928
<p>How can the following recursive function <code>walk()</code> be converted to an iterative function?</p> <p>Walking the nodes in the same order iteratively is easy using a stack, but I'm unable to figure out how to write an iterative function that will print both the opening and closing tags of each node like the recursive version does.</p> <p><strong>Code:</strong></p> <pre><code>class Node(object): def __init__(self, name, children=[]): self.name = name self.children = children def walk(node): print('&lt;', node.name, '&gt;', sep='') for n in node.children: walk(n) print('&lt;/', node.name, '&gt;', sep='') root = \ Node('html', [ Node('head'), Node('body', [ Node('div'), Node('p', [ Node('a'), ]) ]), ]) walk(root) </code></pre> <p><strong>Output:</strong></p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;/head&gt; &lt;body&gt; &lt;div&gt; &lt;/div&gt; &lt;p&gt; &lt;a&gt; &lt;/a&gt; &lt;/p&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p><strong>Code that traverses the tree iteratively:</strong></p> <p>The function visits the nodes in the correct order, but obviously does not print the closing tags.</p> <pre><code>def walk(node): stack = [] stack.append(node) while len(stack) &gt; 0: node = stack.pop() for child in reversed(node.children): stack.append(child) print(node.name) </code></pre>
0
2016-08-10T20:26:33Z
38,883,423
<p>It is kind of <a href="https://en.wikipedia.org/wiki/Tree_traversal" rel="nofollow">post-order tree treversal </a> as you have to visit the parent node after visiting children.</p> <p>I modified a few lines of your existing code:</p> <pre><code>class Node(object): def __init__(self, name, children=[]): self.name = name self.children = children # def walk(node): # print('&lt;', node.name, '&gt;', sep='') # for n in node.children: # walk(n) # print('&lt;/', node.name, '&gt;', sep='') def walk(node): stack = [] stack.append((node, 'start')) while len(stack) &gt; 0: node, status = stack.pop() if status == 'start': stack.append((node, 'end')) for child in reversed(node.children): stack.append((child, 'start')) print('&lt;', node.name, '&gt;', sep='') else: # status == 'end' print('&lt;/', node.name, '&gt;', sep='') root = \ Node('html', [ Node('head'), Node('body', [ Node('div'), Node('p', [ Node('a'), ]) ]), ]) walk(root) </code></pre>
0
2016-08-10T20:58:59Z
[ "python", "recursion", "tree", "iteration" ]
Python progress bar GUI
38,883,022
<p>I wonder if you can help me. I have seen code for creating a progress bar GUI and am trying to modify it slightly so that I can send the progress bar the value I want it to be. Below is my code</p> <pre><code>import tkinter as tk from tkinter import ttk import time class progress_bar(tk.Tk): def __init__(self, *args, **kwargs): tk.Tk.__init__(self, *args, **kwargs) self.progress = ttk.Progressbar(self, orient="horizontal", length=200, mode="determinate") self.progress.pack() self.val = 0 self.maxval = 1 self.progress["maximum"] = 1 def updating(self, val): self.val = val self.progress["value"] = self.val print(self.val) if self.val == self.maxval: self.destroy() def test(): for i in range(0, 101): time.sleep(0.1) app.updating(i/100) app = progress_bar() app.after(1, test) app.mainloop() </code></pre> <p>When I run the code the print message progresively increases from 0 - 1 as expected, however while the GUI is created it remains empty until the program has finished and it closes as required. Can you tell me what I need to modify so the GUI updates please. Thanks in advance for any help provided.</p>
0
2016-08-10T20:32:36Z
38,884,235
<p>The issue you're having is that your <code>test</code> function blocks the <code>tkinter</code> event loop. That means that even though the progress bar's <code>value</code> gets updated, the progress never appears on the screen (since nothing gets redrawn until <code>test</code> ends).</p> <p>To fix this, you need to get rid of the loop in <code>test</code> and instead use <code>tkinter</code> code to do the repeated updates.</p> <p>Here's a modified version of <code>test</code> that should work:</p> <pre><code>def test(i=0): app.updating(i/100) if i &lt; 100: app.after(100, test, i+1) </code></pre> <p>Rather than explicitly looping, it reschedules itself every 100 milliseconds. Rather than <code>i</code> being a loop variable, it is now an argument, and each scheduled call gets a larger <code>i</code> value than the one before it.</p>
0
2016-08-10T21:57:35Z
[ "python", "tkinter", "progress-bar" ]
SQL (Impala) query syntax error for timestamp range
38,883,050
<p>I am using the following query to find the data given the timestamp constraint:</p> <pre><code>query = 'select my_id, my_ts from my_table limit 100 where my_ts &gt; "2016-05-13 00:00:00"' cursor = impala_con.cursor() cursor.execute('USE my_database') cursor.execute(query) </code></pre> <p>But get the following error:</p> <pre><code>HiveServer2Error: AnalysisException: Syntax error in line 1: ...my_ts from my_table limit 100 where my_ts &gt; "201... ^ Encountered: WHERE Expected: AND, BETWEEN, DIV, ILIKE, IN, IREGEXP, IS, LIKE, LIMIT, NOT, OFFSET, OR, ORDER, REGEXP, RLIKE, UNION CAUSED BY: Exception: Syntax error </code></pre> <hr> <p>Does anyone know what I did wrong? Thanks!</p>
0
2016-08-10T20:33:55Z
38,883,079
<p>According to <a href="http://www.cloudera.com/documentation/enterprise/5-6-x/topics/impala_limit.html#limit" rel="nofollow">the documentation</a> you need to specify <code>limit 100</code> <em>after</em> the where clause.</p> <pre><code>query = 'select my_id, my_ts from my_table where my_ts &gt; "2016-05-13 00:00:00" limit 100' </code></pre>
1
2016-08-10T20:36:00Z
[ "python", "sql", "impala" ]
Multiprocessing Pool PicklingError
38,883,113
<p>I'm working on a class that can take in a list of Request type objects and execute the requests (using the object's .execute() API) and return the result of the request. I'm running into an issue when trying to make this multi-processed. I have used Pool in the past, and I am having a tough time getting it to work here. When attempting to run the staticmethod in the Executor class from a Pool, I receive a PicklingError. But when running directly from a new Process object, it seems to work as expected. What is the cause of this behavior? Is there something obvious that I am doing incorrectly here ? Running this on Python 2.6 btw</p> <p>Thanks! </p> <p>Executor class:</p> <pre><code>class Executor(object): def __init__(self, max_threads): self.max_threads = max_threads @staticmethod def execute_request_partition(requests): return [request.execute() for request in requests] def execute_requests(self, list_of_requests): partitions = split_list(list_of_requests, self.max_threads) # Seems to execute as expected process = Process(target=self.execute_request_partition, args=(partitions[0],)) process.run() # PicklingError: Can't pickle &lt;type 'function'&gt;: attribute lookup __builtin__.function failed p = Pool(1) p.apply_async(self.execute_request_partition, args=(partitions[0],)) p.close() p.join() </code></pre>
0
2016-08-10T20:38:47Z
38,883,227
<p>This should explain the issue your having: <a href="http://stackoverflow.com/questions/21111106/cant-pickle-static-method-multiprocessing-python">Can&#39;t pickle static method - Multiprocessing - Python</a></p> <p>On a side note: I wouldn't use multiprocessing if I'm going to be spending most of my time waiting for IO. Try threading or even coroutines (<a href="http://www.gevent.org/" rel="nofollow">http://www.gevent.org/</a>). You'll get the same performance and there's less fuss with pickling</p>
1
2016-08-10T20:46:03Z
[ "python", "multiprocessing" ]
With SQLAlchemy metdata reflect() how do you get an actual table object?
38,883,256
<p>I'm just doing a bunch of selects on an existing DB.</p> <ul> <li>Don't to use raw SQL as I may want to jump between mysql and sqlite for testing</li> <li>Want to stick to SQLAlchemy's SQL Expression language.</li> </ul> <p>I need to get a Table object so I do something like </p> <pre><code> s = select([some_table_object]) </code></pre> <p>I've figured how to explicitly reflect a single table to get a table object:</p> <pre><code>from sqlalchemy import * conn = create_engine('mysql://....') metadata = MetaData(conn) mytable = Table('mytable', meta, autoload=True) s = select([mytable]) result = conn.execute(s) # HAPPY!!!! </code></pre> <p>However, this gets tedious as you have to do it for each table (I go lots of tables). I know I can somehow use the <code>MetaData</code> class to reflect the existing DB I'm connecting to, but I'm unsure of how to get the actual corresponding Table from the metadata.</p> <pre><code>from sqlalchemy import * conn = create_engine('mysql://....') metadata = MetaData(conn) metadata.reflect() # How would do I get a Table instance corresponding to the # mytable table in the DB so I move on to HAPPY!! mytable = metadata.no_clue_how_to_get_tables() s = select([some_table_object]) result = conn.execute(s) </code></pre> <p>What's needed to replace the line <code>mytable = metadata.no_clue_how_to_get_tables()</code> to get a <code>Table</code> instance?</p>
0
2016-08-10T20:48:39Z
38,883,606
<p>It is as simple as looking up the tables from the metadata object's dictionary of tables:</p> <pre><code>mytable = metadata.tables['mytable'] </code></pre> <p>See <a href="http://docs.sqlalchemy.org/en/latest/core/reflection.html#reflecting-all-tables-at-once" rel="nofollow">"Reflecting All Tables At Once"</a> for further info.</p>
1
2016-08-10T21:10:27Z
[ "python", "sqlalchemy" ]
How to compare value in list without using loop in python?
38,883,281
<p>I have a list l with sorted number, for example,</p> <pre><code>[1, 5, 6, 9, 14, 19] </code></pre> <p>And I'm trying to find if a given number is between two numbers in the list.</p> <p>For example, if a number 12 is given, then I want to get 9 and 14 since 12 is between them.</p> <p>I wrote this using a for loop,</p> <pre><code>l = [1, 5, 6, 9, 14, 19] n = 12 for i in range(len(l) - 1): if n &gt;= l[i] and n &lt; l[i + 1]: print(str(n) + " between " + str(l[i]) + " and " + str(l[i + 1])) </code></pre> <p>However, if this loop is inside another loop and has a very big list, this could be slow. Is there any way to do this without using a loop? For example, using numpy because I know it's strong dealing with array.</p>
2
2016-08-10T20:50:01Z
38,883,328
<p>You can use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.searchsorted.html" rel="nofollow"><code>np.searchsorted</code></a> -</p> <pre><code>idx = np.searchsorted(l,n) out = np.take(l,[idx-1,idx]) </code></pre>
4
2016-08-10T20:52:43Z
[ "python", "performance", "numpy", "vectorization" ]
How to compare value in list without using loop in python?
38,883,281
<p>I have a list l with sorted number, for example,</p> <pre><code>[1, 5, 6, 9, 14, 19] </code></pre> <p>And I'm trying to find if a given number is between two numbers in the list.</p> <p>For example, if a number 12 is given, then I want to get 9 and 14 since 12 is between them.</p> <p>I wrote this using a for loop,</p> <pre><code>l = [1, 5, 6, 9, 14, 19] n = 12 for i in range(len(l) - 1): if n &gt;= l[i] and n &lt; l[i + 1]: print(str(n) + " between " + str(l[i]) + " and " + str(l[i + 1])) </code></pre> <p>However, if this loop is inside another loop and has a very big list, this could be slow. Is there any way to do this without using a loop? For example, using numpy because I know it's strong dealing with array.</p>
2
2016-08-10T20:50:01Z
38,883,430
<p>You can use <code>bisect</code> native python module.</p> <p>It uses dichotomic algorithm to find insertion index in the list so it is very fast (<code>log(n)</code> instead of n). Beside, on popular platforms (linux, windows, ...) it has a native implementation: unbeatable.</p> <p>Then report the value at this index and the next, to say which numbers it was between. </p> <p>Small example with various in and out of range values. I used such a method to solve a knapsack problem and it was very efficient.</p> <pre><code># use bisect because the list is known to be sorted from bisect import bisect def test(value, l): idx = bisect(l, value) # if idx is inside the list, we have a definite find if 0 &lt; idx &lt; len(l): return (l[idx-1], l[idx]) # check for boundary condition error elif len(l) == idx and value == l[-1]: return (l[-2], l[-1]) else: return None def print_formatted_result(value, result): if result is None: print (str(value) + " was not found") else: print (str(value) + " between " + str(result[0])+ " and " + str(result[1])) z = [1, 5, 6, 9, 14, 19] for searched in [0, 1, 9, 12, 19, 50]: result = test(searched, z) print_formatted_result(searched, result) </code></pre> <p>output:</p> <pre><code>0 was not found 1 between 1 and 5 9 between 9 and 14 12 between 9 and 14 19 between 14 and 19 50 was not found </code></pre> <p>Note that the original code did not find 19, but this code reports it as a special case. All other cases match the same as the original code.</p>
2
2016-08-10T20:59:38Z
[ "python", "performance", "numpy", "vectorization" ]
How to compare value in list without using loop in python?
38,883,281
<p>I have a list l with sorted number, for example,</p> <pre><code>[1, 5, 6, 9, 14, 19] </code></pre> <p>And I'm trying to find if a given number is between two numbers in the list.</p> <p>For example, if a number 12 is given, then I want to get 9 and 14 since 12 is between them.</p> <p>I wrote this using a for loop,</p> <pre><code>l = [1, 5, 6, 9, 14, 19] n = 12 for i in range(len(l) - 1): if n &gt;= l[i] and n &lt; l[i + 1]: print(str(n) + " between " + str(l[i]) + " and " + str(l[i + 1])) </code></pre> <p>However, if this loop is inside another loop and has a very big list, this could be slow. Is there any way to do this without using a loop? For example, using numpy because I know it's strong dealing with array.</p>
2
2016-08-10T20:50:01Z
38,883,632
<p>The following solution is based on built-in list functions:</p> <pre><code>l = [1, 5, 6, 9, 14, 19] n = 12 l.append(n) l.sort() index=l.index(n) if index==0: print(str(n) + " before " + str(l[index+1])) elif index==len(l)-1: print(str(n) + " after " + str(l[index-1])) else: print(str(n) + " between " + str(l[index-1]) + " and " + str(l[index+1])) </code></pre>
-2
2016-08-10T21:12:07Z
[ "python", "performance", "numpy", "vectorization" ]
Python multiprocessing using a lock or manager list for Pool workers accessing a global list variable
38,883,288
<p>I am trying to distribute jobs over several CUDA devices where the total number of running jobs at any time should be less than or equal to the number of cpu cores available. To do this, I determine the number of available 'slots' on each device and create a list that holds the available slots. If I have 6 cpu cores, and two cuda devices (0 and 1), then AVAILABLE_SLOTS = [0, 1, 0, 1, 0, 1]. In my worker function I pop the list and save it to a variable, set CUDA_VISIBLE_DEVICES env var in the subprocess call, and then append it back to the list. This has been working so far but I want to avoid race conditions. </p> <p>Current code is as follows:</p> <pre><code>def work(cmd): slot = AVAILABLE_GPU_SLOTS.pop() exit_code = subprocess.call(cmd, shell=False, env=dict(os.environ, CUDA_VISIBLE_DEVICES=str(slot))) AVAILABLE_GPU_SLOTS.append(slot) return exit_code if __name__ == '__main__': pool_size = multiprocessing.cpu_count() mols_to_be_run = [name for name in os.listdir(YANK_FILES) if os.path.isdir(os.path.join(YANK_FILES, name))] cmds = build_cmd(mols_to_be_run) cuda = get_cuda_devices() AVAILABLE_GPU_SLOTS = build_available_gpu_slots(pool_size, cuda) pool = multiprocessing.Pool(processes=pool_size, maxtasksperchild=2, ) pool.map(work, cmds) </code></pre> <p>Can I simply declare lock = multiprocessing.Lock() at the same level as AVAILABLE_GPU_SLOTS, put it in cmds, and then inside work() do</p> <pre><code>with lock: slot = AVAILABLE_GPU_SLOTS.pop() # subprocess stuff with lock: AVAILABLE_GPU_SLOTS.append(slot) </code></pre> <p>or do I need a manager list. Alternatively maybe there's a better solution to what I'm doing.</p>
0
2016-08-10T20:50:21Z
38,907,066
<p>Basing off of what I found in the following SO answer <a href="http://stackoverflow.com/questions/25557686/python-sharing-a-lock-between-processes">Python sharing a lock between processes</a>:</p> <p>Using a regular list leads to each process having its own copy, as is expected. Using a manager list seems to be sufficient enough to get around that. Example code:</p> <pre><code>def doing_work(honk): proc = multiprocessing.current_process() # with lock: # print proc, 'about to pop SLOTS_LIST', SLOTS_LIST # slot = SLOTS_LIST.pop() # print multiprocessing.current_process(), ' just popped', slot, 'from', SLOTS_LIST print proc, 'about to pop SLOTS_LIST', SLOTS_LIST slot = SLOTS_LIST.pop() print multiprocessing.current_process(), ' just popped', slot, 'from SLOTS_LIST' time.sleep(10) def init(l): global lock lock = l if __name__ == '__main__': man = multiprocessing.Manager() SLOTS_LIST = [1,34,3465,456,4675,6,4] SLOTS_LIST = man.list(SLOTS_LIST) l = multiprocessing.Lock() pool = multiprocessing.Pool(processes=2, initializer=init, initargs=(l,)) inputs = range(len(SLOTS_LIST)) pool.map(doing_work, inputs) </code></pre> <p>which outputs</p> <pre><code>&lt;Process(PoolWorker-3, started daemon)&gt; about to pop SLOTS_LIST [1, 34, 3465, 456, 4675, 6, 4] &lt;Process(PoolWorker-3, started daemon)&gt; just popped 4 from SLOTS_LIST &lt;Process(PoolWorker-2, started daemon)&gt; about to pop SLOTS_LIST [1, 34, 3465, 456, 4675, 6] &lt;Process(PoolWorker-2, started daemon)&gt; just popped 6 from SLOTS_LIST &lt;Process(PoolWorker-3, started daemon)&gt; about to pop SLOTS_LIST [1, 34, 3465, 456, 4675] &lt;Process(PoolWorker-3, started daemon)&gt; just popped 4675 from SLOTS_LIST &lt;Process(PoolWorker-2, started daemon)&gt; about to pop SLOTS_LIST [1, 34, 3465, 456] &lt;Process(PoolWorker-2, started daemon)&gt; just popped 456 from SLOTS_LIST &lt;Process(PoolWorker-3, started daemon)&gt; about to pop SLOTS_LIST [1, 34, 3465] &lt;Process(PoolWorker-3, started daemon)&gt; just popped 3465 from SLOTS_LIST &lt;Process(PoolWorker-2, started daemon)&gt; about to pop SLOTS_LIST [1, 34] &lt;Process(PoolWorker-2, started daemon)&gt; just popped 34 from SLOTS_LIST &lt;Process(PoolWorker-3, started daemon)&gt; about to pop SLOTS_LIST [1] &lt;Process(PoolWorker-3, started daemon)&gt; just popped 1 from SLOTS_LIST </code></pre> <p>which is desired behavior. I'm not sure if it completely eliminates race conditions but it seems to be good enough. That and using a lock on top of it is simple enough.</p>
0
2016-08-11T22:28:23Z
[ "python", "locking", "multiprocessing" ]
How to save a file to a specific directory and choose the file's name in python?
38,883,317
<p>As the title says, how can I save a file (in this case a previously selected photo) into a specific directory and also name the saved file (I want to name it with today's date - eg: 01-01-2016.jpg)?</p> <p>Here's some of my code:</p> <pre><code>import os.path import datetime todays_date = datetime.date.today () def add_pic (pic): if not os.path.exists ("Pictures"): os.makedirs ("Pictures") photo_name = todays_date + ".jpg" pic.save ("Pictures/"photo_name) </code></pre> <p>I get this error:</p> <pre><code>TypeError: unsupported operand type(s) for +: 'datetime.date' and 'str' </code></pre> <p>for this line:</p> <pre><code>photo_name = todays_date + ".jpg" </code></pre> <p>Plus, I'm not sure about the last line either, so pls help! </p>
0
2016-08-10T20:52:05Z
38,883,359
<p>Use <a href="https://docs.python.org/2/library/time.html#time.strftime" rel="nofollow"><code>.strftime()</code></a> to "convert a tuple or struct_time representing a time as returned by gmtime() or localtime() to a string as specified by the format argument.":</p> <pre><code>photo_name = todays_date.strftime('%m-%d-%Y') + ".jpg" pic.save(os.path.join("Pictures",photo_name)) </code></pre> <p>Also use <a href="https://docs.python.org/2/library/os.path.html?highlight=os.path.join#os.path.join" rel="nofollow"><code>os.path.join()</code></a> for a cross-platform method of joining directory to filename.</p> <p>As @Blckknght says in a comment: please note that <code>'%m-%d-%Y'</code> is something for which you can change order, e.g. <code>'%Y-%m-%d'</code> is a common variant.</p>
1
2016-08-10T20:54:45Z
[ "python", "image", "file", "save" ]
How to save a file to a specific directory and choose the file's name in python?
38,883,317
<p>As the title says, how can I save a file (in this case a previously selected photo) into a specific directory and also name the saved file (I want to name it with today's date - eg: 01-01-2016.jpg)?</p> <p>Here's some of my code:</p> <pre><code>import os.path import datetime todays_date = datetime.date.today () def add_pic (pic): if not os.path.exists ("Pictures"): os.makedirs ("Pictures") photo_name = todays_date + ".jpg" pic.save ("Pictures/"photo_name) </code></pre> <p>I get this error:</p> <pre><code>TypeError: unsupported operand type(s) for +: 'datetime.date' and 'str' </code></pre> <p>for this line:</p> <pre><code>photo_name = todays_date + ".jpg" </code></pre> <p>Plus, I'm not sure about the last line either, so pls help! </p>
0
2016-08-10T20:52:05Z
38,883,404
<p>Yes.above solution should work.Mistake what your were doing was adding time value with string.</p>
0
2016-08-10T20:57:40Z
[ "python", "image", "file", "save" ]
How to save a file to a specific directory and choose the file's name in python?
38,883,317
<p>As the title says, how can I save a file (in this case a previously selected photo) into a specific directory and also name the saved file (I want to name it with today's date - eg: 01-01-2016.jpg)?</p> <p>Here's some of my code:</p> <pre><code>import os.path import datetime todays_date = datetime.date.today () def add_pic (pic): if not os.path.exists ("Pictures"): os.makedirs ("Pictures") photo_name = todays_date + ".jpg" pic.save ("Pictures/"photo_name) </code></pre> <p>I get this error:</p> <pre><code>TypeError: unsupported operand type(s) for +: 'datetime.date' and 'str' </code></pre> <p>for this line:</p> <pre><code>photo_name = todays_date + ".jpg" </code></pre> <p>Plus, I'm not sure about the last line either, so pls help! </p>
0
2016-08-10T20:52:05Z
38,883,415
<p>This won't work because <code>datetime.date.today()</code> returns a date object. Try converting to string by calling the <code>.__str__()</code> method, the <code>.ctime()</code> method, or the <code>.strftime()</code> method.<br> See <a href="https://docs.python.org/2/library/datetime.html#date-objects" rel="nofollow">https://docs.python.org/2/library/datetime.html#date-objects</a>.</p>
0
2016-08-10T20:58:31Z
[ "python", "image", "file", "save" ]
Spyder (python 2.7) - why do scripts run if I hit run button, but not if I type script name in command line?
38,883,327
<p>New to python/spyder. I am having trouble running scripts the way I want to. Quck example using the following script:</p> <pre><code># Demo file for Spyder Tutorial # Hans Fangohr, University of Southampton, UK def hello(): """Print "Hello World" and return None""" print("Hello World") # main program starts here hello() </code></pre> <p>I have saved this as hello.py. When I type hello() into my command line, I get the following error:</p> <pre><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; NameError: name 'hello' is not defined </code></pre> <p>However, if I hit the run button with this script open in the Editor, it runs just fine, and prints Hello World. I can <em>then</em> type hello() into my command line and it runs just fine. </p> <p>Could someone please explain to me why this is? </p> <p>My general goal is to save a startup.py script that I can run from the default cwd, which changes my cwd to where I want to save all of my code. </p>
-1
2016-08-10T20:52:41Z
38,883,361
<p><code>hello</code> isn't defined until you execute the <code>def hello</code> statement. You haven't run the script yet so that line hasn't been executed. After you have run the script, <code>hello</code> has been defined.</p>
2
2016-08-10T20:54:49Z
[ "python", "spyder", "cwd" ]
Spyder (python 2.7) - why do scripts run if I hit run button, but not if I type script name in command line?
38,883,327
<p>New to python/spyder. I am having trouble running scripts the way I want to. Quck example using the following script:</p> <pre><code># Demo file for Spyder Tutorial # Hans Fangohr, University of Southampton, UK def hello(): """Print "Hello World" and return None""" print("Hello World") # main program starts here hello() </code></pre> <p>I have saved this as hello.py. When I type hello() into my command line, I get the following error:</p> <pre><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; NameError: name 'hello' is not defined </code></pre> <p>However, if I hit the run button with this script open in the Editor, it runs just fine, and prints Hello World. I can <em>then</em> type hello() into my command line and it runs just fine. </p> <p>Could someone please explain to me why this is? </p> <p>My general goal is to save a startup.py script that I can run from the default cwd, which changes my cwd to where I want to save all of my code. </p>
-1
2016-08-10T20:52:41Z
38,884,215
<p>You have to actually run the script. There are 3 (probably more) ways you can do this: <code>python hello.py</code> in cmd or powershell if it is in your cwd, the run button in your IDE, or by double clicking on the .py file with the python interpreter set as the default program for .py files. BTW this is windows specific. </p>
0
2016-08-10T21:56:14Z
[ "python", "spyder", "cwd" ]
python 3.x - "TypeError: 'int' object is not callable"
38,883,396
<p>Upon running this code,</p> <pre><code> #Silent Auction class Auction: def __init__(self): self.reserve_price = 30 self.highest_bid = 0 self.highest_bidder = "" self.namelist = [] self.bidlist = [] def reserve_price(self): print("Hello. The reserve price is ${}".format(self.reserve_price)) def new_bidder(self): LOOP = 0 while LOOP == 0: name = input("What is your name? 'F' for FINISH ") if name.upper() == "F": LOOP = 1 else: bid = int(input("Hello {}. What is your bid? ".format(name))) if bid &gt; self.highest_bid: self.highest_bid = bid self.highest_bidder = name self.namelist.append(name) self.bidlist.append(bid) else: print("Sorry {}. You'll need to make another higher bid.".format(name)) print("Highest bid so far is ${:.2f}".format(self.highest_bid)) def auction_end(self): if self.highest_bid &gt;= self.reserve_price: print("The auction met the reserve price and the highest bidder was {} with ${:.2f}".format(self.highest_bidder, self.highest_bid)) else: print("The auction did not meet the reserve price") n = len(self.namelist) for i in range (0, n): print("{} bid ${:.2f}".format(self.namelist[n], self.bidlist[n])) if __name__ == "__main__": auction1 = Auction() auction1.reserve_price() auction1.new_bidder() auction1.auction_end() </code></pre> <p>I receive the error</p> <pre><code>Traceback (most recent call last): File "F:\Work\Year 13\13DIP\91637 Programming\Silent Auction.py", line 46, in &lt;module&gt; auction1.reserve_price() TypeError: 'int' object is not callable &gt;&gt;&gt; </code></pre>
-4
2016-08-10T20:57:09Z
38,883,417
<p>Don't name your function and your instance variable the same thing.</p> <p>Change</p> <pre><code>def reserve_price(self): </code></pre> <p>to</p> <pre><code>def print_reserve_price(self): </code></pre> <p>I know if you come from java you can do things like this and it knows the difference, but in python functions are first class citizens and you can refer to them directly. i.e.:</p> <pre><code>In [2]: x = lambda i : i * i In [3]: x Out[3]: &lt;function __main__.&lt;lambda&gt;&gt; In [5]: x(2) Out[5]: 4 </code></pre> <p>However I can also overwrite it</p> <pre><code>In [6]: x = 5 In [7]: x Out[7]: 5 </code></pre> <p>Which is what happens above when you set <code>self.reserve_price</code> in your init method.</p>
1
2016-08-10T20:58:38Z
[ "python", "python-3.x" ]
python 3.x - "TypeError: 'int' object is not callable"
38,883,396
<p>Upon running this code,</p> <pre><code> #Silent Auction class Auction: def __init__(self): self.reserve_price = 30 self.highest_bid = 0 self.highest_bidder = "" self.namelist = [] self.bidlist = [] def reserve_price(self): print("Hello. The reserve price is ${}".format(self.reserve_price)) def new_bidder(self): LOOP = 0 while LOOP == 0: name = input("What is your name? 'F' for FINISH ") if name.upper() == "F": LOOP = 1 else: bid = int(input("Hello {}. What is your bid? ".format(name))) if bid &gt; self.highest_bid: self.highest_bid = bid self.highest_bidder = name self.namelist.append(name) self.bidlist.append(bid) else: print("Sorry {}. You'll need to make another higher bid.".format(name)) print("Highest bid so far is ${:.2f}".format(self.highest_bid)) def auction_end(self): if self.highest_bid &gt;= self.reserve_price: print("The auction met the reserve price and the highest bidder was {} with ${:.2f}".format(self.highest_bidder, self.highest_bid)) else: print("The auction did not meet the reserve price") n = len(self.namelist) for i in range (0, n): print("{} bid ${:.2f}".format(self.namelist[n], self.bidlist[n])) if __name__ == "__main__": auction1 = Auction() auction1.reserve_price() auction1.new_bidder() auction1.auction_end() </code></pre> <p>I receive the error</p> <pre><code>Traceback (most recent call last): File "F:\Work\Year 13\13DIP\91637 Programming\Silent Auction.py", line 46, in &lt;module&gt; auction1.reserve_price() TypeError: 'int' object is not callable &gt;&gt;&gt; </code></pre>
-4
2016-08-10T20:57:09Z
38,883,684
<p>the problem is that you overwrite your <code>reserve_price</code> method in the <code>__init__</code> method</p> <p>check this illustrative example</p> <pre><code>&gt;&gt;&gt; class A: def __init__(self): self.fun = 42 def fun(self): print( "funny" ) &gt;&gt;&gt; a = A() &gt;&gt;&gt; a.fun 42 &gt;&gt;&gt; </code></pre> <p>the solution is simple, change the name of one of them. </p>
0
2016-08-10T21:15:03Z
[ "python", "python-3.x" ]
How to check for empty JSON field in flask reqparse for a post request?
38,883,403
<p>I need to check for empty string in JSON field for a post request in flask using reqparse. Can I achieve it with flask reqparse module?</p> <p>I have tried :</p> <pre><code>self.parser.add_argument('name', type=str, required=True, trim=True, location='json' ) self.parser.parse_args() </code></pre> <p>It is checking if the name field in <code>{"name":"xyz"}</code> is present, However I also want to check for empty values <code>{"name":""}</code> , so that I can throw error to user that name can not be empty. Is it possible to do that using reqparse ?</p>
0
2016-08-10T20:57:33Z
38,883,908
<p>From looking at the <a href="http://flask-restful-cn.readthedocs.io/en/0.3.4/reqparse.html" rel="nofollow">reqparse documentation</a> and <a href="http://stackoverflow.com/questions/9573244/most-elegant-way-to-check-if-the-string-is-empty-in-python">how to check for empty strings in python</a> You could do something like... </p> <pre><code>args = self.parser.parse_args() name = args['name'] if not name: # do your foo here if name is not truthy </code></pre> <p>Since <code>args['name']</code> can return an array, I'd be careful about the following edge cases.</p> <pre><code>[] == false ['foo'] == true [' ', ' '] == true </code></pre> <p>So it might be better do something along the lines of </p> <pre><code>args = self.parser.parse_args() names = args['name'] for name in names: if not name: # if not truthy </code></pre>
0
2016-08-10T21:31:27Z
[ "python", "json", "flask", "flask-restful" ]
Grabbing one column in poorly-formed table using BeautifulSoup and Python
38,883,414
<p>I'm iterating through a .csv of contracts, trying to extract a single column from a website. </p> <p>Here's an example of the website: <a href="https://www.austintexas.gov/financeonline/contract_catalog/OCCViewMA.cfm?cd=CT&amp;dd=6100&amp;id=13060600641" rel="nofollow">https://www.austintexas.gov/financeonline/contract_catalog/OCCViewMA.cfm?cd=CT&amp;dd=6100&amp;id=13060600641</a></p> <p>I want to grab the column labeled "Commodity Description" from table at the end of the webpage. However, I cannot figure out how to grab columns -- just rows. </p> <p>Here is the code I'm currently working with</p> <pre><code>def scraper(first, second, third): url = "https://www.austintexas.gov/financeonline/contract_catalog/OCCViewMA.cfm?cd=%s&amp;dd=%d&amp;id=%s" % (first, second, third) soup = BeautifulSoup(urllib2.urlopen(url).read()) foundtext = soup.find('td',text="Commodity Description") table = foundtext.findPrevious('table') rows = table.findAll('tr') second_column = [] for row in rows: print row.contents </code></pre> <p>I want the final output return to be the text from all the rows in that column with return carriages between the rows. </p> <p>Any thoughts? </p>
2
2016-08-10T20:58:29Z
38,883,478
<p>For every row found, find all <code>td</code> elements and get the desired one by index:</p> <pre><code>table = soup.find('td', text="Commodity Description").find_parent("table") for row in table.select("tr")[2:]: # skipping the header rows cell = row.find_all("td")[1] print(cell.get_text()) print("----") </code></pre> <p>Prints:</p> <pre><code>WATERLINE REPLACEMENTCONSTRUCTION, PIPELINEPER YUEJIAO LIU, ADD THE REMAINING FUNDS BACK INTO THIS FUNDING LINE // PEMBERTON HEIGHTS PHASE III PROJECT ++ ENC. $53,209.97 ---- WATERLINE REPLACEMENTCONSTRUCTION, PIPELINEPEMBERTON HEIGHTS PHASE III PROJECT ---- WATERLINE REPLACEMENTCONSTRUCTION, PIPELINEPEMBERTON HEIGHTS PHASE III PROJECT ---- </code></pre>
2
2016-08-10T21:02:43Z
[ "python", "beautifulsoup" ]
Can not print updatedAT column from Postgres
38,883,437
<p>I have a table in postgres, and I want to get only the <code>updatedAt</code> column. If I print the table columns, the updatedAt exists: </p> <pre><code>#!/usr/bin/python # -*- coding: utf-8 -*- import psycopg2 import sys import datetime con = None try: con = psycopg2.connect(database='db', user='dbuser', password='1111') cur = con.cursor() cur.execute('SELECT * from incidents') column_names = [row[0] for row in cur.description] print("Column names: %s\n" % column_names) except psycopg2.DatabaseError as e: print('Error %s' % e) sys.exit(1) finally: if con: con.close() </code></pre> <p>the result is</p> <pre><code>Column names: ['id', 'deviceId', 'latitude', 'longitude', 'city', 'area', 'address', 'state', 'postalCode', 'country', 'canceled', 'createdAt', 'updatedAt', 'patientId'] </code></pre> <p>But when I try to select all the rows from that table and get only the updatedAt info, it says that this column does not exist.</p> <pre><code>#!/usr/bin/python # -*- coding: utf-8 -*- import psycopg2 import sys import datetime con = None try: con = psycopg2.connect(database='db', user='dbuser', password='1111') cur = con.cursor() cur.execute('SELECT updatedAt from incidents') rows = cur.fetchall() for row in rows: print(row) except psycopg2.DatabaseError as e: print('Error %s' % e) sys.exit(1) finally: if con: con.close() </code></pre> <p>The error message is:</p> <pre><code>Error column "updatedat" does not exist LINE 1: SELECT updatedAt from incidents ^ HINT: Perhaps you meant to reference the column "incidents.updatedAt". </code></pre> <p>I also tried with <code>incidents.updatedAt</code>, but with no luck.</p> <p><strong>EDIT</strong></p> <p>Forgot to mention that this table has been created from Node.js with Sequelize.</p>
0
2016-08-10T21:00:07Z
38,883,698
<p>Postgres column names default to lower-case. Since that column name has an upper-case letter in it, it must be quoted in order to be referenced. The same would be true if the column had a space or a special character in it. This query should work:</p> <pre><code>SELECT "updatedAt" FROM incidents </code></pre>
2
2016-08-10T21:15:46Z
[ "python", "postgresql", "python-3.5" ]
Extracting items from a tuple in dataframe in pyspark
38,883,450
<p>I am just a beginner to pyspark and data frames my dtaframe is <code>df([('one',1),('two',2),('three',3)],[('four',4)])</code> so i want to concatenate x to each of the first elements in the tuple . ex <code>onex, twox,threex,fourx</code>. any help is appreciated . <code>df.select()</code> is only giving the items in the first list . mk</p>
0
2016-08-10T21:01:01Z
38,919,037
<pre><code>from pyspark.sql.functions import udf, col from pyspark.sql.types import StringType def append_x(val): return val + 'x' df = df.withColumn( 'appended', udf(append_x, StringType())(col(colInput)) ) </code></pre> <p>Note that <code>colInput</code> is the name of column you want to append <code>x</code> to.</p>
0
2016-08-12T13:20:50Z
[ "python", "pyspark" ]
groupby with overlapping intervals timeseries
38,883,465
<p>I have a time series in python pandas dataframe object and I want to create a group based on index but I want overlapping groups i.e groups are not distinct. The header_sec is the index column. Each groups consists of a 2 second window. Input dataFrame</p> <pre><code> header_sec 1 17004 days 22:17:13 2 17004 days 22:17:13 3 17004 days 22:17:13 4 17004 days 22:17:13 5 17004 days 22:17:14 6 17004 days 22:17:14 7 17004 days 22:17:14 8 17004 days 22:17:14 9 17004 days 22:17:15 10 17004 days 22:17:15 11 17004 days 22:17:15 12 17004 days 22:17:15 13 17004 days 22:17:16 14 17004 days 22:17:16 15 17004 days 22:17:16 16 17004 days 22:17:16 17 17004 days 22:17:17 18 17004 days 22:17:17 19 17004 days 22:17:17 20 17004 days 22:17:17 </code></pre> <p>My first group should have</p> <pre><code>1 17004 days 22:17:13 2 17004 days 22:17:13 3 17004 days 22:17:13 4 17004 days 22:17:13 5 17004 days 22:17:14 6 17004 days 22:17:14 7 17004 days 22:17:14 8 17004 days 22:17:14 </code></pre> <p>The second group starts from the previous index and takes 1/2 of the records in previous second.</p> <pre><code>7 17004 days 22:17:14 8 17004 days 22:17:14 9 17004 days 22:17:15 10 17004 days 22:17:15 11 17004 days 22:17:15 12 17004 days 22:17:15 13 17004 days 22:17:16 14 17004 days 22:17:16 </code></pre> <p>Third group .....</p> <pre><code>13 17004 days 22:17:16 14 17004 days 22:17:16 15 17004 days 22:17:16 16 17004 days 22:17:16 17 17004 days 22:17:17 18 17004 days 22:17:17 19 17004 days 22:17:17 20 17004 days 22:17:17 </code></pre> <p>If I do groupby on index, </p> <pre><code> dfgroup=df.groupby(df.index) </code></pre> <p>this gives one group per second. What would be the best way to merge these groups?</p>
0
2016-08-10T21:01:49Z
38,884,195
<p>Here is a technique:</p> <pre><code>import numpy as np # if you have not already done this grouped = df.groupby(df.index) for name, group in grouped: try: prev_sec = df.loc[(name - pd.to_timedelta(1, unit='s')), :] except KeyError: prev_sec = pd.DataFrame(columns=group.columns) try: next_sec = df.loc[(name + pd.to_timedelta(1, unit='s')), :] except KeyError: next_sec = pd.DataFrame(columns=group.columns) Pn = 2 # replace this with int(len(prev_sec)/2) to get half rows from previous second Nn = 2 # replace this with int(len(next_sec)/2) to get half rows from next second group = pd.concat([prev_sec.iloc[-Pn:,:], group, next_sec.iloc[:Nn,:]]) # Replace the below lines with your operations print(name, group) </code></pre>
1
2016-08-10T21:55:08Z
[ "python", "pandas", "dataframe", "group-by", "time-series" ]
Python one-liner if else statement
38,883,470
<p>This problem is taken from codingbat. Given two int values, return their sum. Unless the two values are the same, then return double their sum.</p> <p>I'm trying to solve it in one line:</p> <pre><code>def sum_double(a, b): return 2*(a+b) if (a == b) else return a+b </code></pre> <p>But I'm getting an error and I'm not sure why. Would appreciate any help.</p>
1
2016-08-10T21:02:01Z
38,883,484
<p>You can't have a return in the else clause. It should be:</p> <pre><code>def sum_double(a, b): return 2*(a+b) if (a == b) else a+b </code></pre>
9
2016-08-10T21:02:54Z
[ "python" ]
Python one-liner if else statement
38,883,470
<p>This problem is taken from codingbat. Given two int values, return their sum. Unless the two values are the same, then return double their sum.</p> <p>I'm trying to solve it in one line:</p> <pre><code>def sum_double(a, b): return 2*(a+b) if (a == b) else return a+b </code></pre> <p>But I'm getting an error and I'm not sure why. Would appreciate any help.</p>
1
2016-08-10T21:02:01Z
38,883,494
<p>You should delete the second <code>return</code>.</p> <pre><code>def sum_double(a, b): return 2*(a+b) if a == b else a+b </code></pre> <p>The value of the <code>2*(a+b) if a == b else a+b</code> expression is what you actually want to return.</p>
4
2016-08-10T21:03:19Z
[ "python" ]
Python one-liner if else statement
38,883,470
<p>This problem is taken from codingbat. Given two int values, return their sum. Unless the two values are the same, then return double their sum.</p> <p>I'm trying to solve it in one line:</p> <pre><code>def sum_double(a, b): return 2*(a+b) if (a == b) else return a+b </code></pre> <p>But I'm getting an error and I'm not sure why. Would appreciate any help.</p>
1
2016-08-10T21:02:01Z
38,883,580
<p>You have 2 options:</p> <ol> <li><p>Use the <code>if/else</code> <a class='doc-link' href="http://stackoverflow.com/documentation/python/1111/conditionals/3564/else-statement#t=2016081021114628832">statement</a>:</p> <pre><code>def sum_double(a, b): if (a == b): #if/else statement return 2*(a+b) # &lt;--- return statement #^ else: #^ return a+b # &lt;--- return statement #^ </code></pre></li> <li><p>Use the <code>if/else</code> <a class='doc-link' href="http://stackoverflow.com/documentation/python/1111/conditionals/3226/conditional-expression-or-the-ternary-operator#t=2016081021114628832">conditional expression</a>:</p> <pre><code>def sum_double(a, b): return 2*(a+b) if (a == b) else a+b # (^ ^) &lt;--- conditional expression # (^ ^) &lt;--- return statement </code></pre></li> </ol> <p>each has different syntax and meaning</p>
8
2016-08-10T21:08:33Z
[ "python" ]
Python one-liner if else statement
38,883,470
<p>This problem is taken from codingbat. Given two int values, return their sum. Unless the two values are the same, then return double their sum.</p> <p>I'm trying to solve it in one line:</p> <pre><code>def sum_double(a, b): return 2*(a+b) if (a == b) else return a+b </code></pre> <p>But I'm getting an error and I'm not sure why. Would appreciate any help.</p>
1
2016-08-10T21:02:01Z
38,884,160
<p>In Python, True, False are the same as 1, 0:</p> <pre><code>def sum_double(a, b): return ((a==b) + 1) * (a+b) </code></pre> <p>Or using lambda,</p> <pre><code>sum_double = lambda a, b: ((a==b) + 1) * (a+b) </code></pre>
0
2016-08-10T21:51:54Z
[ "python" ]
How to remove those "\x00\x00"
38,883,476
<p>How to remove those "\x00\x00" in a string ? I have many of those strings (example shown below). I can use re.sub to replace those "\x00". But I am wondering whether there is a better way to do that ? Converting between unicode, bytes and string is always confusing.</p> <p><code>'Hello\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'.</code></p>
1
2016-08-10T21:02:42Z
38,883,513
<p>Use <code>rstrip</code></p> <pre><code>&gt;&gt;&gt; text = 'Hello\x00\x00\x00\x00' &gt;&gt;&gt; text.rstrip('\x00') 'Hello' </code></pre> <p>It removes all <code>\x00</code> characters at the end of the string.</p>
4
2016-08-10T21:04:33Z
[ "python", "string", "byte" ]
How to remove those "\x00\x00"
38,883,476
<p>How to remove those "\x00\x00" in a string ? I have many of those strings (example shown below). I can use re.sub to replace those "\x00". But I am wondering whether there is a better way to do that ? Converting between unicode, bytes and string is always confusing.</p> <p><code>'Hello\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'.</code></p>
1
2016-08-10T21:02:42Z
38,883,536
<pre><code>a = 'Hello\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' a.replace('\x00','') 'Hello' </code></pre>
4
2016-08-10T21:05:56Z
[ "python", "string", "byte" ]
Creating archive with shutil.make_archive() while excluding some path(s)
38,883,595
<p>Is there a way to have <code>shutil.make_archive</code> exclude some child directories, or alternatively, is there a way to append directories to a single archive through <code>shutil</code>?</p> <p><strong>Examples are fun</strong>:</p> <pre><code>/root /workingDir /dir1 /dir2 /dirA /dirB /dir3 </code></pre> <p>Suppose I wanted to create an archive from within <code>workingDir</code> that included everything <em>except</em> for <code>dirA</code> -- how could I do this? Is it possible without writing a method to loop through the entire tree?</p>
1
2016-08-10T21:09:42Z
38,883,728
<p>I don't think this is possible with directly with shutil. It is possible to do it with tarfile (which is used by shutil internally anyway)</p> <p><a href="https://docs.python.org/2/library/tarfile.html#tarfile.TarFile.add" rel="nofollow">Tarfile.add</a> has a filter argument that you can use precisely for this purpose.</p> <p>See also this answer: <a href="http://stackoverflow.com/questions/16000794/python-tarfile-and-excludes">Python tarfile and excludes</a></p> <pre><code>EXCLUDE_FILES = ['dir2/dirA'] tar = tarfile.open("sample.tar.gz", "w:gz") tar.add("workingDir", filter=lambda x: None if x.name in EXCLUDE_FILES else x) tar.close() </code></pre>
0
2016-08-10T21:17:08Z
[ "python", "python-2.7", "archive", "shutil" ]
Is there a good way to send data from python context to C++ without too much copy involved
38,883,660
<p>The title could be confusing. Here I will state my question more clearly.</p> <p>I want to create a website based on python (a lot of existing framework like Flask and cherryPy) and along with a C++ computation engine for the sake of processing speed. So I need to create an interface for python to call C++ functions. Fortunately the boost.python can do the job. However, every time I send a data from python, say a matrix, to C++, I have to use python list, which means I have to transform the matrix data into list and in C++ context transform the list into an internal matrix object. As a result, a lot of data copy occur, which could not be an intelligent or efficient approach. So my questions is that if, considering the complexity, we don't map C++ matrix class to a python class through boost.python, is there a better way to do the similar work without or only with small number of copy?</p>
0
2016-08-10T21:13:35Z
38,884,078
<p>There's a project called ndarray with this as their exact aim: <a href="https://github.com/ndarray/ndarray" rel="nofollow">https://github.com/ndarray/ndarray</a> see also <a href="https://github.com/ndarray/Boost.NumPy" rel="nofollow">https://github.com/ndarray/Boost.NumPy</a> .</p> <p>There is some compatibility with other C++ matrix libraries (eg. Eigen) which should help with the computations.</p>
0
2016-08-10T21:44:40Z
[ "python", "c++", "boost-python", "web-site-project" ]
Is there a good way to send data from python context to C++ without too much copy involved
38,883,660
<p>The title could be confusing. Here I will state my question more clearly.</p> <p>I want to create a website based on python (a lot of existing framework like Flask and cherryPy) and along with a C++ computation engine for the sake of processing speed. So I need to create an interface for python to call C++ functions. Fortunately the boost.python can do the job. However, every time I send a data from python, say a matrix, to C++, I have to use python list, which means I have to transform the matrix data into list and in C++ context transform the list into an internal matrix object. As a result, a lot of data copy occur, which could not be an intelligent or efficient approach. So my questions is that if, considering the complexity, we don't map C++ matrix class to a python class through boost.python, is there a better way to do the similar work without or only with small number of copy?</p>
0
2016-08-10T21:13:35Z
38,886,567
<blockquote> <p>However, every time I send a data from python, say a matrix, to C++, I have to use python list, which means I have to transform the matrix data into list and in C++ context transform the list into an internal matrix object.</p> </blockquote> <p>No, you don't have to use the python list. You can use numpy array which allocates data as a C contiguous segment which can be passed down to C++ without copying and viewed as a matrix using a matrix wrapper class.</p> <p>In python allocate 2d array using numpy:</p> <pre><code>&gt;&gt;&gt; y=np.empty((2,5), dtype=np.int16) &gt;&gt;&gt; y array([[ 12, 27750, 26465, 2675, 0], [ 0, 0, 0, 2601, 0]], dtype=int16) &gt;&gt;&gt; y.flags['C_CONTIGUOUS'] True &gt;&gt;&gt; foo(y,2,5) </code></pre> <p>Pass matrix data to C++ using below function exposed to python:</p> <pre><code>void foo(python::object obj, size_t size1, size_t size2) { PyObject* pobj = obj.ptr(); Py_buffer pybuf; PyObject_GetBuffer(pobj, &amp;pybuf, PyBUF_SIMPLE); void *buf = pybuf.buf; int16_t *p = (int16_t*)buf; Py_XDECREF(pobj); MyMatrixWrapper matrix(p, size1, size2); // .... } </code></pre>
2
2016-08-11T03:00:17Z
[ "python", "c++", "boost-python", "web-site-project" ]
User Input Not Responding With If/Else Statements Correctly
38,883,704
<p>I'm working through Learning Python the Hard Way and I'm currently creating a game. For some reason my if/else statements are not properly working. Here is the related part in my current script: </p> <pre><code>if door_choice == '1': room_one() else: print "I don't recognize that choice, try again!" if door_choice == '2': room_two() else: print "I don't recognize that choice, try again!" if door_choice == '3': room_three() else: print "I don't recognize that choice, try again!" </code></pre> <p>Whatever number I use to type in my input, I still receive the other answers' else statement, for example:</p> <pre><code>You see 3 doors. You must choose either 1, 2 or 3. &gt; 2 I don't recognize that choice, try again! The second room is dark and smelly but you see a gold chest! Do you open the chest or just give up? I don't recognize that choice, try again! </code></pre> <p>The print statement for "I don't recognize that choice, try again!" should not show up if I input the designated number. I tried adding integer to my input and having my door choice variable not as a string and still no luck.</p>
-1
2016-08-10T21:16:05Z
38,883,760
<p>You should chain those separate <code>if-else</code> blocks into one <code>if-elif-else</code> block:</p> <pre><code>if door_choice == '1': room_one() elif door_choice == '2': room_two() elif door_choice == '3': room_three() else: print "I don't recognize that choice, try again!" </code></pre>
1
2016-08-10T21:19:26Z
[ "python" ]
User Input Not Responding With If/Else Statements Correctly
38,883,704
<p>I'm working through Learning Python the Hard Way and I'm currently creating a game. For some reason my if/else statements are not properly working. Here is the related part in my current script: </p> <pre><code>if door_choice == '1': room_one() else: print "I don't recognize that choice, try again!" if door_choice == '2': room_two() else: print "I don't recognize that choice, try again!" if door_choice == '3': room_three() else: print "I don't recognize that choice, try again!" </code></pre> <p>Whatever number I use to type in my input, I still receive the other answers' else statement, for example:</p> <pre><code>You see 3 doors. You must choose either 1, 2 or 3. &gt; 2 I don't recognize that choice, try again! The second room is dark and smelly but you see a gold chest! Do you open the chest or just give up? I don't recognize that choice, try again! </code></pre> <p>The print statement for "I don't recognize that choice, try again!" should not show up if I input the designated number. I tried adding integer to my input and having my door choice variable not as a string and still no luck.</p>
-1
2016-08-10T21:16:05Z
38,883,779
<p>The problem is in your if statements. Your program encounters <code>if door_choice == '1'</code> which is false, so it jumps to the next else statement and prints <code>"I don't recognize that choice, try again!"</code></p> <p>Instead if first is not true, then check second, if not true check third, if not true, invalid choice.</p> <pre><code>if door_choice == '1': room_one() elif door_choice == '2': room_two() elif door_choice == '3': room_three() else: print "I don't recognize that choice, try again!" </code></pre>
1
2016-08-10T21:21:05Z
[ "python" ]
User Input Not Responding With If/Else Statements Correctly
38,883,704
<p>I'm working through Learning Python the Hard Way and I'm currently creating a game. For some reason my if/else statements are not properly working. Here is the related part in my current script: </p> <pre><code>if door_choice == '1': room_one() else: print "I don't recognize that choice, try again!" if door_choice == '2': room_two() else: print "I don't recognize that choice, try again!" if door_choice == '3': room_three() else: print "I don't recognize that choice, try again!" </code></pre> <p>Whatever number I use to type in my input, I still receive the other answers' else statement, for example:</p> <pre><code>You see 3 doors. You must choose either 1, 2 or 3. &gt; 2 I don't recognize that choice, try again! The second room is dark and smelly but you see a gold chest! Do you open the chest or just give up? I don't recognize that choice, try again! </code></pre> <p>The print statement for "I don't recognize that choice, try again!" should not show up if I input the designated number. I tried adding integer to my input and having my door choice variable not as a string and still no luck.</p>
-1
2016-08-10T21:16:05Z
38,883,805
<p>Besides the obvious "pass in else everytime" effect, you can use a table and function pointers to save the if/elif constructions if you have a lot of cases.</p> <pre><code>room_funcs = [room_one,room_two,room_three] idx = int(door_choice)-1 if 0 &lt;= idx &lt; len(room_funcs): room_funcs[idx]() else: print("I don't recognize that choice, try again!") </code></pre>
1
2016-08-10T21:24:10Z
[ "python" ]
User Input Not Responding With If/Else Statements Correctly
38,883,704
<p>I'm working through Learning Python the Hard Way and I'm currently creating a game. For some reason my if/else statements are not properly working. Here is the related part in my current script: </p> <pre><code>if door_choice == '1': room_one() else: print "I don't recognize that choice, try again!" if door_choice == '2': room_two() else: print "I don't recognize that choice, try again!" if door_choice == '3': room_three() else: print "I don't recognize that choice, try again!" </code></pre> <p>Whatever number I use to type in my input, I still receive the other answers' else statement, for example:</p> <pre><code>You see 3 doors. You must choose either 1, 2 or 3. &gt; 2 I don't recognize that choice, try again! The second room is dark and smelly but you see a gold chest! Do you open the chest or just give up? I don't recognize that choice, try again! </code></pre> <p>The print statement for "I don't recognize that choice, try again!" should not show up if I input the designated number. I tried adding integer to my input and having my door choice variable not as a string and still no luck.</p>
-1
2016-08-10T21:16:05Z
38,883,997
<pre><code>If door_choice == '1' Room_one() elif door_choice == '2' Room_two() elif door_choice == '3' Room_three() else Print "please input a value between 1 and 3 </code></pre> <p>You had some bad logics. If you input 1, then that's correct otherwise error appears, however you check again for input 2 and get the wished result and then check again for input 3 but error appears again.</p> <p>Using else if or elif in python is one of the way to get to the result. There are also switches if you need to do more cases</p>
0
2016-08-10T21:37:44Z
[ "python" ]
User Input Not Responding With If/Else Statements Correctly
38,883,704
<p>I'm working through Learning Python the Hard Way and I'm currently creating a game. For some reason my if/else statements are not properly working. Here is the related part in my current script: </p> <pre><code>if door_choice == '1': room_one() else: print "I don't recognize that choice, try again!" if door_choice == '2': room_two() else: print "I don't recognize that choice, try again!" if door_choice == '3': room_three() else: print "I don't recognize that choice, try again!" </code></pre> <p>Whatever number I use to type in my input, I still receive the other answers' else statement, for example:</p> <pre><code>You see 3 doors. You must choose either 1, 2 or 3. &gt; 2 I don't recognize that choice, try again! The second room is dark and smelly but you see a gold chest! Do you open the chest or just give up? I don't recognize that choice, try again! </code></pre> <p>The print statement for "I don't recognize that choice, try again!" should not show up if I input the designated number. I tried adding integer to my input and having my door choice variable not as a string and still no luck.</p>
-1
2016-08-10T21:16:05Z
38,885,115
<p>EDIT: As for maximums there is one <code>if</code> statement, chained by any amount of <code>elif</code> statements. However, there can only be 1 <code>else</code> statements per <code>if</code>.</p> <p>TutorialsPoint has a great page regarding if/elif/else: <a href="http://www.tutorialspoint.com/python/python_if_else.htm" rel="nofollow">http://www.tutorialspoint.com/python/python_if_else.htm</a></p> <p>"The else statement is an optional statement and there could be at most only one else statement following if ."</p> <p>I don't think your indentation is right. Indent all of the else statements by 4 spaces additionally after the <code>if</code> statements, and change them to <code>if</code>. Also take away the last <code>else</code> statement.</p> <p>I'll show you what I mean.</p> <pre><code>if door_choice == '1': room_one() if door_choice != 1 or 2 or 3: print "I don't recognize that choice, try again!" if door_choice == '2': room_two() if door_choice != 1 or 2 or 3: print "I don't recognize that choice, try again!" if door_choice == '3': room_three() if door_choice != 1 or 2 or 3: print "I don't recognize that choice, try again!" </code></pre> <p>Also, your not giving the user input after you say "I don't recognize that choice, try again!"</p>
0
2016-08-10T23:29:23Z
[ "python" ]
Ways to make a function with dynamic bound checking in TicTacToe Game
38,883,803
<p>First off thanks for trying to help out.</p> <p>I have a TicTacToe game completed in python which you can check out here: <a href="https://github.com/Weffe/TicTacToe" rel="nofollow">https://github.com/Weffe/TicTacToe</a></p> <p>Currently, everything runs perfectly fine for a 3x3 playing field. I wanted to make the game dynamic in the sense that it can easily scale up to 9x9 with no problems. However, I'm a bit brain dead and can't figure out the cleanest way to make this possible. The main issues lies in Player.py's function get_player_loc_input(). </p> <p>The way it is right now, it's only configured for a 3x3 playing field. However, I want to make it dynamic.</p> <p>Original code:</p> <pre><code>def get_player_loc_input(self): player_input = input('Enter in location for your move: ') # player input is with respect to field index location translated_input = int(player_input) if 7 &lt;= translated_input &lt;= 9: translated_input = [0, (translated_input - 7)] # row, col elif 4 &lt;= translated_input &lt;= 6: translated_input = [1, (translated_input - 4)] # row, col elif 1 &lt;= translated_input &lt;= 3: translated_input = [2, (translated_input - 1)] # row, col else: raise ValueError('Input is not an index on the playing field. Try again\n') return translated_input </code></pre> <p>My current dynamic attempt:</p> <pre><code>def get_player_loc_input(self, num_rows, num_cols): value = num_rows*num_cols num_rows = num_rows - 1 #adjust from n+1 to n for x in range(value, 0, 3): lower_bound = x-2 upper_bound = x if lower_bound &lt;= translated_input &lt;= upper_bound: translated_input = [num_rows, (translated_input - lower_bound)] num_rows = num_rows - 1 #move down to the next row we're on return translated_input </code></pre> <p>A picture of the playing field</p> <pre><code>------------- | 7 | 8 | 9 | #row 0 ------------- | 4 | 5 | 6 | #row 1 ------------- | 1 | 2 | 3 | #row 2 ------------- </code></pre> <p>The way it works is by inputting the number of the index you want to replace. Then the function converts that number to a [row,col] "value". </p> <p>So for example, 4 => [1,0] OR 3 => [2,2]</p> <p>Any ideas? Gonna go do something else for a bit to clear my head.</p>
0
2016-08-10T21:23:47Z
38,884,045
<p>a little more complex than divide &amp; modulo since rows are not in the correct order</p> <p>Here's a generic function which works for all values </p> <pre><code>def get_player_loc_input( nb_rows, nb_cols, pinput): pinput -= 1 rval = (nb_rows-(pinput//nb_cols)-1,pinput%nb_cols) return rval print(get_player_loc_input(3,3,3)) print(get_player_loc_input(3,3,4)) print(get_player_loc_input(3,3,7)) </code></pre> <p>output:</p> <pre><code>(2, 2) (1, 0) (0, 0) </code></pre> <p>Note that there must be a problem with your code, as you have a method, a <code>self</code> and still passing <code>nb_rows</code> &amp; <code>nb_cols</code> as a parameter. Should be class members (and <code>translated_input</code> is not defined)</p>
0
2016-08-10T21:41:47Z
[ "python" ]
Correct way to configure connection between Teradata and python on Linux RHEL
38,883,830
<p>I installed teradata module for python2.7, the teradata client 15.00, also set the environment variables ODBCINI, ODBCINST and LD_LIBRARY_PATH correctly. But when I create my connection in my py script:</p> <pre><code>odbclib="/opt/teradata/client/15.00/odbc_64/lib/libodbc.so" udaExec = teradata.UdaExec (appName="terapp", version="1.0", logConsole=True, odbcLibPath=odbclib) session = udaExec.connect(method="odbc", system="XXX.XX.XX.XX",username=user, password=pass) </code></pre> <p>I got this: </p> <pre><code>File "build/bdist.linux-x86_64/egg/teradata/udaexec.py", line 183, in connect File "build/bdist.linux-x86_64/egg/teradata/tdodbc.py", line 374, in __init__ File "build/bdist.linux-x86_64/egg/teradata/tdodbc.py", line 206, in checkStatus teradata.api.DatabaseError: (0, u'[IM003] [DataDirect][ODBC lib] Specified driver could not be loaded') </code></pre> <p>Please, any help clever people</p>
0
2016-08-10T21:25:50Z
38,954,036
<p>Which version of RHEL? This is only a guess, but if it's RHEL 6, Python 2.7 is not installed by default so install Python 2.7 via Software Collections (part of most subscription). See <a href="http://developers.redhat.com/products/softwarecollections/get-started-rhel6-python/" rel="nofollow">http://developers.redhat.com/products/softwarecollections/get-started-rhel6-python/</a> and install python27 version.</p>
0
2016-08-15T11:14:52Z
[ "python", "linux", "database", "teradata", "rhel" ]
SQLAlchemy - show creation statement with indexes
38,883,871
<p>I am working with a database system that will require me to run the <code>CREATE TABLE</code> manually on several nodes. This means I need to be able to obtain the <code>CREATE</code> statement, complete with indexes.</p> <p>The following works to get the base schema:</p> <pre><code>from calendars import models from app import db from sqlalchemy import CreateTable print(CreateTable(models.Calendar.__table__).compile(db.engine)) </code></pre> <p>However, it does NOT print constraints or indexes.</p> <p>How do I also obtain those?</p>
0
2016-08-10T21:29:03Z
38,884,932
<p>if you set sqlalchemy logging to debug, you can read statements from logs.</p> <pre><code>import logging logging.basicConfig() logging.getLogger('sqlalchemy.engine').setLevel(logging.DEBUG) </code></pre>
0
2016-08-10T23:06:22Z
[ "python", "sqlalchemy" ]
Sockets Python 3.5: Socket server hangs forever on file recieve
38,883,887
<p>I'm trying to write a Python program that can browse directories and grab files w/ sockets if the client connects to the server. The browsing part works fine, it prints out all directories of the client. Here's a part of the code:</p> <pre><code>with clientsocket: print('Connected to: ', addr) while True: m = input("Command &gt; ") clientsocket.send(m.encode('utf-8')) data = clientsocket.recv(10000) if m == "exit": clientsocket.close() if m.split()[0] == 'get': inp = input("Filename &gt; ") while True: rbuf = clientsocket.recv(8192) if not rbuf: break d = open(inp, "ab") d.write(rbuf) d.close() elif data.decode('utf-8').split()[0] == "LIST": print(data.decode('utf-8')) if not data: break </code></pre> <p>However, the problem lies in here:</p> <pre><code>if m.split()[0] == 'get': inp = input("Filename &gt; ") while True: rbuf = clientsocket.recv(8192) if not rbuf: break </code></pre> <p>It seems to be stuck in an infinite loop. What's more interesting is that the file I'm trying to recieve is 88.3kb, but what the file returns is 87kb while it's in the loop, which is very close...</p> <p>I tried receiving a python script at one time as well (without the loop) and it works fine.</p> <p>Here's some of the client code:</p> <pre><code>while True: msg = s.recv(1024).decode('utf-8') if msg.split()[0] == "list": dirs = os.listdir(msg.split()[1]) string = '' for dira in dirs: string += "LIST " + dira + "\n" s.send(string.encode('utf-8')) elif msg == "exit": break else: #bit that sends the file with open(msg.split()[1], 'rb') as r: s.sendall(r.read()) </code></pre> <p>So my question is, why is it getting stuck in an infinite loop if I have it set up to close when there is no data, and how can I fix this?</p> <p>I'm sort of new to network programming in general, so forgive me if I miss something obvious.</p> <p>Thanks!</p>
2
2016-08-10T21:30:15Z
38,884,290
<p>I think I know what's the problem, but I may be wrong. It happened to me several times, that the entire message is not received in one <code>recv</code> call, even if I specify the correct length. However, you don't reach the end of stream, so your program keeps waiting for remaining of 8192 bytes which never arrives.</p> <p>Try this:<br> Sending file:</p> <pre><code>#bit that sends the file with open(msg.split()[1], 'rb') as r: data = r.read() # check data length in bytes and send it to client data_length = len(data) s.send(data_length.to_bytes(4, 'big')) s.send(data) s.shutdown(socket.SHUT_RDWR) s.close() </code></pre> <p>Receiving the file:</p> <pre><code># check expected message length remaining = int.from_bytes(clientsocket.recv(4), 'big') d = open(inp, "wb") while remaining: # until there are bytes left... # fetch remaining bytes or 4094 (whatever smaller) rbuf = clientsocket.recv(min(remaining, 4096)) remaining -= len(rbuf) # write to file d.write(rbuf) d.close() </code></pre>
0
2016-08-10T22:01:53Z
[ "python", "sockets" ]
Sockets Python 3.5: Socket server hangs forever on file recieve
38,883,887
<p>I'm trying to write a Python program that can browse directories and grab files w/ sockets if the client connects to the server. The browsing part works fine, it prints out all directories of the client. Here's a part of the code:</p> <pre><code>with clientsocket: print('Connected to: ', addr) while True: m = input("Command &gt; ") clientsocket.send(m.encode('utf-8')) data = clientsocket.recv(10000) if m == "exit": clientsocket.close() if m.split()[0] == 'get': inp = input("Filename &gt; ") while True: rbuf = clientsocket.recv(8192) if not rbuf: break d = open(inp, "ab") d.write(rbuf) d.close() elif data.decode('utf-8').split()[0] == "LIST": print(data.decode('utf-8')) if not data: break </code></pre> <p>However, the problem lies in here:</p> <pre><code>if m.split()[0] == 'get': inp = input("Filename &gt; ") while True: rbuf = clientsocket.recv(8192) if not rbuf: break </code></pre> <p>It seems to be stuck in an infinite loop. What's more interesting is that the file I'm trying to recieve is 88.3kb, but what the file returns is 87kb while it's in the loop, which is very close...</p> <p>I tried receiving a python script at one time as well (without the loop) and it works fine.</p> <p>Here's some of the client code:</p> <pre><code>while True: msg = s.recv(1024).decode('utf-8') if msg.split()[0] == "list": dirs = os.listdir(msg.split()[1]) string = '' for dira in dirs: string += "LIST " + dira + "\n" s.send(string.encode('utf-8')) elif msg == "exit": break else: #bit that sends the file with open(msg.split()[1], 'rb') as r: s.sendall(r.read()) </code></pre> <p>So my question is, why is it getting stuck in an infinite loop if I have it set up to close when there is no data, and how can I fix this?</p> <p>I'm sort of new to network programming in general, so forgive me if I miss something obvious.</p> <p>Thanks!</p>
2
2016-08-10T21:30:15Z
38,884,446
<p>There are several issues with your code.</p> <p>First:</p> <pre><code>clientsocket.send(m.encode('utf-8')) data = clientsocket.recv(10000) </code></pre> <p>This causes the file to be partially loaded to <code>data</code> variable when you issue <code>get</code> statement. That's why you don't get full file.</p> <p>Now this:</p> <pre><code>while True: rbuf = clientsocket.recv(8192) if not rbuf: break ... </code></pre> <p>You indeed load full file but the client never closes the connection (it goes to <code>s.recv()</code> after sending the file) so <code>if</code> statement is never satisfied. Thus this loop gets blocked on the <code>clientsocket.recv(8192)</code> part after downloading the file.</p> <p>So the problem is that you have to somehow notify the downloader that you've sent all the data even though the connection is still open. There are several ways to do that:</p> <ol> <li><p>You calculate the size of the file and send it as a first few bytes. For example, say the content of the file is <code>ala ma kota</code>. These are 11 bytes and thus you send <code>\x11ala ma kota</code>. Now receiver knows that first byte is size and it will interpret it as such. Of course one byte header isn't much (you would only be able to send max 256 byte files) so normally you go for for example 4 bytes. So now your protocol between client and server is: first 4 bytes is the size of the file. Thus our initial file would be sent as <code>\x0\x0\x0\x11ala ma kota</code>. The drawback of this solution is that you have to know the size of the content before sending it.</p></li> <li><p>You mark the end of the stream. So you pick a particular character, say <code>X</code> and you read the straem until you find <code>X</code>. If you do then you know that the other side sent everything it has. The drawback is that if <code>X</code> is in the content then you have to escape it, i.e. additional content processing (and interpretation on the other side) is needed.</p></li> </ol>
0
2016-08-10T22:16:12Z
[ "python", "sockets" ]
How can I apply changes to source files with Python?
38,883,991
<p>I am refactoring C++ code using the Python bindings of the Clang compiler (<a href="https://github.com/llvm-mirror/clang/tree/master/bindings/python" rel="nofollow">cindex</a>). Using that, I analyze the AST and prepare changes. I end up with a list of operations similar to the following:</p> <pre><code>DELETE line 10 INSERT line 5 column 32: &lt;&lt; "tofu" REPLACE from line 31 colum 6 to line 33 column 82 with: std::cout &lt;&lt; "Thanks SO" ... </code></pre> <p><strong>My question is how to turn these into actual file changes.</strong></p> <p>Doing it directly with python seems tedious: patches need to be applied in the right order and checked for consistency. It looks quite hard and error-prone.</p> <p>I also can’t find a good library to help (clang does have something called a Rewriter, but it isn't wrapped in Python. I'd really like to avoid C++ for refactoring if possible).</p> <p>Maybe an idea could be to generate patches and apply them with git, maybe? But even that seems a bit tedious.</p> <p>Any ideas?</p>
2
2016-08-10T21:37:12Z
39,958,507
<p>So I rolled out my own. The code is almost certainly buggy and not very pretty, but I'm posting it in the hope it might help someone until a better solution is found.</p> <pre><code>class PatchRecord(object): """ Record patches, validate them, order them, and apply them """ def __init__(self): # output of readlines for each patched file self.lines = {} # list of patches for each patched file self.patches = {} class Patch(object): """ Abstract base class for editing operations """ def __init__(self, filename, start, end): self.filename = filename self.start = start self.end = end def __repr__(self): return "{op}: {filename} {start}/{end} {what}".format( op=self.__class__.__name__.upper(), filename=self.filename, start=format_place(self.start), end=format_place(self.end), what=getattr(self, "what", "")) def apply(self, lines): print "Warning: applying no-op patch" class Delete(Patch): def __init__(self, filename, extent): super(PatchRecord.Delete, self).__init__( filename, extent.start, extent.end) print "DELETE: {file} {extent}".format(file=self.filename, extent=format_extent(extent)) def apply(self, lines): lines[self.start.line - 1:self.end.line] = [ lines[self.start.line - 1][:self.start.column - 1] + lines[self.end.line - 1][self.end.column:]] class Insert(Patch): def __init__(self, filename, start, what): super(PatchRecord.Insert, self).__init__(filename, start, start) self.what = what print "INSERT {where} {what}".format(what=what, where=format_place(self.start)) def apply(self, lines): line = lines[self.start.line - 1] lines[self.start.line - 1] = "%s%s%s" % ( line[:self.start.column], self.what, line[self.start.column:]) class Replace(Patch): def __init__(self, filename, extent, what): super(PatchRecord.Replace, self).__init__( filename, extent.start, extent.end) self.what = what print "REPLACE: {where} {what}".format(what=what, where=format_extent(extent)) def apply(self, lines): lines[self.start.line - 1:self.end.line] = [ lines[self.start.line - 1][:self.start.column - 1] + self.what + lines[self.end.line - 1][self.end.column - 1:]] # Convenience functions for creating patches def delete(self, filename, extent): self.patches[filename] = self.patches.get( filename, []) + [self.Delete(filename, extent)] def insert(self, filename, where, what): self.patches[filename] = self.patches.get( filename, []) + [self.Insert(filename, where, what)] def replace(self, filename, extent, what): self.patches[filename] = self.patches.get( filename, []) + [self.Replace(filename, extent, what)] def _pos_to_tuple(self, position): """ Convert a source location to a tuple for use as a sorting key """ return (position.line, position.column) def sort(self, filename): """ Sort patches by extent start """ self.patches[filename].sort(key=lambda p: self._pos_to_tuple(p.start)) def validate(self, filename): """Try to insure patches are consistent""" print "Checking patches for %s" % filename self.sort(filename) previous = self.patches[filename][0] for p in self.patches[filename][1:]: assert(self._pos_to_tuple(p.start) &gt; self._pos_to_tuple(previous.start)) def _apply(self, filename): self.sort(filename) lines = self._getlines(filename) for p in reversed(self.patches[filename]): print p p.apply(lines) def _getlines(self, filename): """ Get source file lines for editing """ if not filename in self.lines: with open(filename) as f: self.lines[filename] = f.readlines() return self.lines[filename] def apply(self): for filename in self.patches: self.validate(filename) self._apply(filename) # with open(filename+".patched","w") as output: with open(filename, "w") as output: output.write("".join(self._getlines(filename))) </code></pre> <p>Just create a <code>PatchRecord</code> object, add changes using the <code>create</code>, <code>replace</code> and <code>delete</code> methods, and apply them with <code>apply</code> when you're ready.</p>
0
2016-10-10T12:39:03Z
[ "python", "c++", "refactoring", "clang", "abstract-syntax-tree" ]
Python - Concatenate Python query
38,884,090
<p>I'm using the python-google-places script but I'm facing a problem when integrating the code into a function called with two parameters: "MyLocation" and "MyType".</p> <p>"MyLocation" works well but "MyType" doesn't work.</p> <p>Code that works (without a variable for "MyType")</p> <pre><code># Configuration de l'encodage (a mettre dans tous les scripts) # encoding: utf-8 #################################### ### CLASS #################################### def ExtractGoogleHotspots(Location,MyType): from googleplaces import GooglePlaces, types, lang YOUR_API_KEY = 'XXXXXXX' google_places = GooglePlaces(YOUR_API_KEY) # You may prefer to use the text_search API, instead. query_result = google_places.nearby_search( location=Location, #Location could be a name or coordinates in english format : 4.04827,9.70428 keyword='', radius=1000,#Radius in meters (max = 50 000) types=[types.TYPE_PHARMACY] #Specify the Type ) for place in query_result.places: # Returned places from a query are place summaries. Name = place.name Name = Name.encode('utf-8')#Encodage en UTF-8 obligatoire pour éviter les erreurs : "UnicodeEncodeError: 'ascii' codec can't encode character..." Latitude = place.geo_location['lat'] Longitude = place.geo_location['lng'] # The following method has to make a further API call. place.get_details() Details = place.details Address = place.formatted_address Address = Address.encode('utf-8') Phone_International = place.international_phone_number Website = place.website Result = str(MyType) + ";" + Name + ";" + Address + ";" + str(Phone_International) + ";" + str(Latitude) + ";" + str(Longitude) + ";" + str(Website) print Result #################################### ### Script #################################### Location = "4.04827,9.70428" MyType = "DOES_NOT_WORK" ExtractGoogleHotspots(Location, MyType) </code></pre> <p>Code that doesn't work:</p> <pre><code> # Configuration de l'encodage (a mettre dans tous les scripts) # encoding: utf-8 #################################### ### CLASS #################################### def ExtractGoogleHotspots(Location,Type): from googleplaces import GooglePlaces, types, lang YOUR_API_KEY = 'XXXXXXX' google_places = GooglePlaces(YOUR_API_KEY) MyType = "[types.TYPE_"+Type+"]" # You may prefer to use the text_search API, instead. query_result = google_places.nearby_search( location=Location, #Location could be a name or coordinates in english format : 4.04827,9.70428 keyword='', radius=1000,#Radius in meters (max = 50 000) types=MyType #Specify the Type ) for place in query_result.places: # Returned places from a query are place summaries. Name = place.name Name = Name.encode('utf-8')#Encodage en UTF-8 obligatoire pour éviter les erreurs : "UnicodeEncodeError: 'ascii' codec can't encode character..." Latitude = place.geo_location['lat'] Longitude = place.geo_location['lng'] # The following method has to make a further API call. place.get_details() Details = place.details Address = place.formatted_address Address = Address.encode('utf-8') Phone_International = place.international_phone_number Website = place.website Result = str(MyType) + ";" + Name + ";" + Address + ";" + str(Phone_International) + ";" + str(Latitude) + ";" + str(Longitude) + ";" + str(Website) print Result #################################### ### Script #################################### Location = "4.04827,9.70428" MyType = "PHARMACY" ExtractGoogleHotspots(Location, MyType) </code></pre> <p>How to resolve the problem to have a variable to define the Types part?</p>
0
2016-08-10T21:45:57Z
38,884,137
<p>To concatenate the type name with <code>TYPE_</code> in take it from <code>types</code> you can use <code>getattr</code></p> <pre class="lang-py prettyprint-override"><code>MyTypes = [ getattr(types, 'TYPE_' + Type.upper() ] </code></pre>
1
2016-08-10T21:49:19Z
[ "python" ]
YouTube Analytics API: Authentication request for a content owner
38,884,099
<p>I have a content owner account, and I used Google's API Explorer to figure out the query that I need to send. My problem now is that I can't figure out how to send that same query programmatically via Python. I have generated oauth credentials as well as an API key - for an installed application -, so I also have a <code>client_secrets.json</code> file. What I can't figure out is how do I use this information to get through and send my query. There's a lot of talk of "scope" in the other questions I've reviewed, but I'm confused about how I need to include that in my request.</p> <p>I tried passing the contents of the client secrets file as headers in my request, I also tried just appending the simple API key to the end of the request, no dice. Also looked at several questions on here, but they either aren't relevant to content owners, or are about getting the right query itself rather than the authentication portion. Any help would be appreciated. Thanks in advance!</p> <p>Examples:</p> <pre><code>yt_headers = {"client_id": CLIENT_ID, "client_secret":CLIENT_SECRET, "redirect_uris": REDIRECT_URIS, "auth_uri": "https://accounts.google.com/o/oauth2/auth", "token_uri": "https://accounts.google.com/o/oauth2/token"} query_string = 'https://www.googleapis.com/youtube/analytics/v1/reports?ids=contentOwner%3D%3DCONTENT_ID&amp;start-date=2015-09-28&amp;end-date=2015-11-05&amp;metrics=views&amp;dimensions=insightTrafficSourceType&amp;filters=video%3D%3DVIDEO_ID&amp;fields=rows' api_request = http.request('GET', query_string, headers=yt_headers) </code></pre>
0
2016-08-10T21:46:46Z
38,901,561
<p>As mentioned in <a href="https://developers.google.com/youtube/analytics/v1/content_owner_reports" rel="nofollow">YouTube Analytics API: Content Owner Reports</a>,</p> <blockquote> <p>To retrieve a content owner report, call the API's <code>reports.query</code> method and set the <code>ids</code> parameter value in the API request to <code>contentOwner==OWNER_NAME</code>, where <code>OWNER_NAME</code> specifies the content owner's ID.</p> </blockquote> <p>In <a href="https://developers.google.com/youtube/analytics/v1/reference/reports/query" rel="nofollow">Reports: Query</a>, you may send your HTTP request with the following format:</p> <pre><code>GET https://www.googleapis.com/youtube/analytics/v1/reports </code></pre> <p>Please note that YouTube Analytics API requests must be authorized. Aside from that, you can also add query parameters, such as dimensions, filters, and sorting instructions.</p> <p>This related SO post - <a href="http://stackoverflow.com/questions/19584489/youtube-analytics-api-content-owner-reports">YouTube Analytics API - Content owner reports</a> might also help.</p>
0
2016-08-11T16:19:20Z
[ "python", "oauth", "youtube-api", "google-oauth", "youtube-analytics-api" ]
How to return the first n items of an iterator that pass a test without running the test on the remainder
38,884,102
<p>I'm looking for something like:</p> <pre><code>foo = [ p for p in somelist if xxx(p)][0:10] </code></pre> <p>This works, but executes xxx on all of somelist, and xxx is expensive. </p> <p>I could write a subfunction such as </p> <pre><code>def blah (list, len): res=[]; i=0; while i&lt;len: if xxx(list[i]): res.append(i) return res </code></pre> <p>but this seems very unpythonic. </p> <p>An example that proves the first result does the wrong thing would be:</p> <pre><code>foo = [ p for p in (1,2,3,4,5,0,6) if 100/p ][0:3] </code></pre> <p>which "should" return [1,2,3] but in fact fails on the divide by zero. </p> <p>I've tried various tools from itertools but can't find a combination that stops execution of the iterator after the size is reached. </p>
0
2016-08-10T21:46:57Z
38,884,152
<p>Try <a href="https://docs.python.org/dev/library/itertools.html#itertools.islice" rel="nofollow">itertools.islice</a>:</p> <pre><code>from itertools import islice foo = list(islice((p for p in (1,2,3,4,5,0,6) if 100/p), 4)) </code></pre> <p>Notice the lack of brackets: this is a <a href="http://stackoverflow.com/questions/47789/generator-expressions-vs-list-comprehension">generator comprehension</a></p>
2
2016-08-10T21:51:10Z
[ "python", "listiterator" ]
How to return the first n items of an iterator that pass a test without running the test on the remainder
38,884,102
<p>I'm looking for something like:</p> <pre><code>foo = [ p for p in somelist if xxx(p)][0:10] </code></pre> <p>This works, but executes xxx on all of somelist, and xxx is expensive. </p> <p>I could write a subfunction such as </p> <pre><code>def blah (list, len): res=[]; i=0; while i&lt;len: if xxx(list[i]): res.append(i) return res </code></pre> <p>but this seems very unpythonic. </p> <p>An example that proves the first result does the wrong thing would be:</p> <pre><code>foo = [ p for p in (1,2,3,4,5,0,6) if 100/p ][0:3] </code></pre> <p>which "should" return [1,2,3] but in fact fails on the divide by zero. </p> <p>I've tried various tools from itertools but can't find a combination that stops execution of the iterator after the size is reached. </p>
0
2016-08-10T21:46:57Z
38,884,394
<p>That is impossible to do with list comprehensions but it is possible with generator comprehensions.</p> <p>What is the difference between the two? List comprehensions will iterate over the iterable all at once and return a list back to you according to your operations on items on the iterable. The key here is <em>all at once</em>.</p> <p>Your example uses list comprehensions and here's what happens: First the list comprehension is evaluated. In your case it will fail, but even if it didn't fail, it would have iterated over everything in the iterable <code>somelist</code> and would have returned a resulting list back. Then this list is sliced and a new resulting list is returned.</p> <p>Generator comprehensions and generators in general have different way of working. They are basically code blocks that are suspended until you request more data from them, which is what you really want to do. </p> <p>In effect, you create a generator as follows:</p> <pre><code>g = (p for p in (1,2,3,4,5,0,6) if 100/p ) </code></pre> <p>You now have a generator that will generate values for you when you <em>request</em> it to do so, according to the "rule" you gave it.</p> <p>As soon as you have a generator at hand, there are several ways you could get <code>n</code> items from it.</p> <p>You could write a simple for loop as follows:</p> <pre><code>results = [] for x in range(3): # n = 3 in your case results.append(next(g)) </code></pre> <p>Of course, that isn't Pythonic. Assuming you want a list back, you can now use a list comprehension:</p> <pre><code>results = [next(g) for x in range(3)] </code></pre> <p>This is the "manual" way of doing it. You could also use the <code>islice</code> function from the <code>itertools</code> module <a href="https://docs.python.org/dev/library/itertools.html#itertools.islice" rel="nofollow">(Documentation here)</a>:</p> <pre><code>import itertools results = list(itertools.islice(g, 4)) </code></pre> <p>And there it is. Generators are pretty useful. A code block that executes when requested to and remember its state is truly invaluable.</p>
1
2016-08-10T22:11:01Z
[ "python", "listiterator" ]
How to return the first n items of an iterator that pass a test without running the test on the remainder
38,884,102
<p>I'm looking for something like:</p> <pre><code>foo = [ p for p in somelist if xxx(p)][0:10] </code></pre> <p>This works, but executes xxx on all of somelist, and xxx is expensive. </p> <p>I could write a subfunction such as </p> <pre><code>def blah (list, len): res=[]; i=0; while i&lt;len: if xxx(list[i]): res.append(i) return res </code></pre> <p>but this seems very unpythonic. </p> <p>An example that proves the first result does the wrong thing would be:</p> <pre><code>foo = [ p for p in (1,2,3,4,5,0,6) if 100/p ][0:3] </code></pre> <p>which "should" return [1,2,3] but in fact fails on the divide by zero. </p> <p>I've tried various tools from itertools but can't find a combination that stops execution of the iterator after the size is reached. </p>
0
2016-08-10T21:46:57Z
38,885,057
<p>By using a combination of the builtin filter and <a href="https://docs.python.org/3/library/itertools.html#itertools.islice" rel="nofollow">islice</a> you can achieve what you want. eg.</p> <pre><code>length = 3 items_iter = islice(filter(None, [1, 2, 0, 4, 5]), length) # returns a lazy iterator items = list(items_iter) assert items == [1, 2, 5] </code></pre> <p>However, you may wish to write your own generator. Generator functions will, rather than returning a single result, will yield successive items. Sometimes it might yield no items, and sometimes they can yield an infinite number of items. Here is an example for your case:</p> <pre><code>def take_first_n_that_pass(test, length, iterator): i = 0 for item in iterator: if i &gt;= length: return # stops generator if test(item): yield item i += 1 # end of iterator -- generator stops here as well items_iter = take_first_n_that_pass(bool, 3, [0, 1, 2, 0, 4, 5]) items = list(items_iter) assert items == [1, 2, 4] </code></pre>
0
2016-08-10T23:22:03Z
[ "python", "listiterator" ]
Sorting df rows horizontally
38,884,131
<p>I have a dataframe like:</p> <pre><code>import pandas as pd df = pd.DataFrame({'source': {0: u'1:19374802:19380807', 1: u'2:4608900:4614600', 2: u'5:14175176:14182011', 3: u'2:4608900:4614600', 4: u'5:14171600:14173742'}, 'target': {0: u'2:4608900:4614600', 1: u'5:14175176:14182011', 2: u'2:4608900:4614600', 3: u'5:14171600:14173742', 4: u'2:4608900:4614600'}}) source target 0 1:19374802:19380807 2:4608900:4614600 1 2:4608900:4614600 5:14175176:14182011 2 5:14175176:14182011 2:4608900:4614600 3 2:4608900:4614600 5:14171600:14173742 4 5:14171600:14173742 2:4608900:4614600 </code></pre> <p>The data is originating from multiple iterations over many to many relationships. In the data, <code>Source:Target == Target:Source</code>. Thus relationships get duplicated (rows 1 and 2 for example).</p> <p>I'm looking to sort the rows horizontally:</p> <pre><code> source target 0 1:19374802:19380807 2:4608900:4614600 1 2:4608900:4614600 5:14175176:14182011 2 2:4608900:4614600 5:14175176:14182011 3 2:4608900:4614600 5:14171600:14173742 4 2:4608900:4614600 5:14171600:14173742 </code></pre> <p>So duplicates can be removed.</p>
0
2016-08-10T21:48:59Z
38,884,269
<p>Here:</p> <pre><code>df.apply(sorted, axis=1) </code></pre>
0
2016-08-10T21:59:48Z
[ "python", "pandas" ]
Sorting df rows horizontally
38,884,131
<p>I have a dataframe like:</p> <pre><code>import pandas as pd df = pd.DataFrame({'source': {0: u'1:19374802:19380807', 1: u'2:4608900:4614600', 2: u'5:14175176:14182011', 3: u'2:4608900:4614600', 4: u'5:14171600:14173742'}, 'target': {0: u'2:4608900:4614600', 1: u'5:14175176:14182011', 2: u'2:4608900:4614600', 3: u'5:14171600:14173742', 4: u'2:4608900:4614600'}}) source target 0 1:19374802:19380807 2:4608900:4614600 1 2:4608900:4614600 5:14175176:14182011 2 5:14175176:14182011 2:4608900:4614600 3 2:4608900:4614600 5:14171600:14173742 4 5:14171600:14173742 2:4608900:4614600 </code></pre> <p>The data is originating from multiple iterations over many to many relationships. In the data, <code>Source:Target == Target:Source</code>. Thus relationships get duplicated (rows 1 and 2 for example).</p> <p>I'm looking to sort the rows horizontally:</p> <pre><code> source target 0 1:19374802:19380807 2:4608900:4614600 1 2:4608900:4614600 5:14175176:14182011 2 2:4608900:4614600 5:14175176:14182011 3 2:4608900:4614600 5:14171600:14173742 4 2:4608900:4614600 5:14171600:14173742 </code></pre> <p>So duplicates can be removed.</p>
0
2016-08-10T21:48:59Z
38,884,322
<p>i'd do it using NumPy, as it might be faster:</p> <pre><code>In [40]: pd.DataFrame(np.sort(df.values, axis=1), columns=df.columns).drop_duplicates() Out[40]: source target 0 1:19374802:19380807 2:4608900:4614600 1 2:4608900:4614600 5:14175176:14182011 3 2:4608900:4614600 5:14171600:14173742 </code></pre>
1
2016-08-10T22:04:35Z
[ "python", "pandas" ]
write dataframe to excel file at given path
38,884,164
<pre><code>I have a dataframe df = pd.DataFrame({'Data': [10, 20, 30, 20, 15, 30, 45]}) This is working : writer = pd.ExcelWriter('pandas_simple.xlsx', engine='xlsxwriter') df.to_excel(writer, sheet_name='Sheet1') writer.save() but when I try out_path = "C:\Users\Bala\output\temp-excel.xlsx" writer = pd.ExcelWriter(out_path , engine='xlsxwriter') df.to_excel(writer, sheet_name='Sheet1') writer.save() </code></pre> <p>I'm getting error : IOError: [Errno 22] invalid mode ('wb') or filename: 'C:\Users\Bala Nadella\output\temp-excel.xlsx'. </p> <p>How to create file in given path. </p>
1
2016-08-10T21:52:36Z
38,884,287
<p>In a string the backslash is an escape character. It means that you're giving a special command, not a regular character. Eg. <code>"Hello\nWorld"</code> means, put a newline between <code>"Hello"</code> and <code>"World"</code>.</p> <p>If you actually want to use a backslash as a character, type it as <code>"\\"</code>.</p> <p>Or better yet, just use forward slashes!</p>
2
2016-08-10T22:01:41Z
[ "python", "excel", "pandas" ]
write dataframe to excel file at given path
38,884,164
<pre><code>I have a dataframe df = pd.DataFrame({'Data': [10, 20, 30, 20, 15, 30, 45]}) This is working : writer = pd.ExcelWriter('pandas_simple.xlsx', engine='xlsxwriter') df.to_excel(writer, sheet_name='Sheet1') writer.save() but when I try out_path = "C:\Users\Bala\output\temp-excel.xlsx" writer = pd.ExcelWriter(out_path , engine='xlsxwriter') df.to_excel(writer, sheet_name='Sheet1') writer.save() </code></pre> <p>I'm getting error : IOError: [Errno 22] invalid mode ('wb') or filename: 'C:\Users\Bala Nadella\output\temp-excel.xlsx'. </p> <p>How to create file in given path. </p>
1
2016-08-10T21:52:36Z
38,884,307
<p><a href="https://docs.python.org/3/reference/lexical_analysis.html#literals" rel="nofollow">String literals</a></p> <p>Study the table in that link. You need to escape your '\' with '\\'. Partly, DOS is responsible for this mess in the world.</p> <pre><code>out_path = "C:\\Users\\Bala\\output\\temp-excel.xlsx" </code></pre> <p>Or</p> <pre><code>out_path = r"C:\Users\Bala\output\temp-excel.xlsx" # the `r` prefix means raw string </code></pre> <p>But best alternative is this:</p> <pre><code>out_path = "C:/Users/Bala/output/temp-excel.xlsx" </code></pre> <p>It will work on any platform.</p> <hr> <p>Edited to remove the solution with <code>os.path.abspath</code>. After the comment below this answer, I read the documentation myself and realized that it has a different purpose. Although I have used it in the past to make my code dual OS friendly, because it neatly appends CWD to the path, and changes <code>/</code> to <code>\\</code> when moving from Debian to Windows and vice versa. </p>
2
2016-08-10T22:03:11Z
[ "python", "excel", "pandas" ]
One session across multiple instances of a class
38,884,200
<p>I have MyClass class with Session from <code>requests</code></p> <pre><code>import requests class MyClass(object): s = requests.Session() def test(self): print self.s </code></pre> <p>Then I tested </p> <pre><code>In[3]: a = mymodule.MyClass() In[4]: b = mymodule.MyClass() In[5]: print a &lt;mymodule.MyClass object at 0x10e074c50&gt; In[6]: print b &lt;mymodule.MyClass object at 0x10e074d10&gt; In[7]: a.test() &lt;requests.sessions.Session object at 0x10dbe5550&gt; In[8]: b.test() &lt;requests.sessions.Session object at 0x10dbe5550&gt; </code></pre> <p>how is the session object from a and b are the same one? I would expect to have two different sessions created one for a and the other one for b.</p> <p>I don't think <code>Session</code> is a singleton. As it shows, calling <code>requests.Sessions()</code> twice and two different Session instances created. So why the session in <code>a</code> and <code>b</code> are the same?</p> <pre><code>In[13]: s1 = requests.Session() In[14]: s2 = requests.Session() In[15]: print s1 &lt;requests.sessions.Session object at 0x10e089210&gt; In[16]: print s2 &lt;requests.sessions.Session object at 0x10e089650&gt; </code></pre>
1
2016-08-10T21:55:17Z
38,884,224
<p><code>s</code> is a class attribute in your case - it would be initialized once and shared across all class instances. Make the session an <em>instance variable</em> instead:</p> <pre><code>import requests class MyClass(object): def __init__(self): self.s = requests.Session() def test(self): print self.s </code></pre>
2
2016-08-10T21:57:00Z
[ "python", "session", "python-requests" ]
SQL/Impala Breaking the nested query into a more readable format
38,884,203
<p>I have the following work python code to do impala connection/query:</p> <hr> <pre><code>import pandas as pd query = 'select my_c_instance_id, count(my_c_instance_id) as my_ins_id_count from ' + \ '(select * from my_table where my_c_id like "%small%") as small_table' + \ ' group by(my_c_instance_id)' cursor = impala_con.cursor() cursor.execute('USE my_db') cursor.execute(query) df_result = as_pandas(cursor) df_result </code></pre> <hr> <p>The codes work fine, but I am wondering if it is possible to break it into two more readable pieces, something like:</p> <pre><code>small_table = 'select * from my_table where my_c_id like "%small%"' query = 'select my_c_instance_id, count(my_c_instance_id) as my_ins_id_count from small_table group by(my_c_instance_id)' cursor = impala_con.cursor() cursor.execute('USE my_db') cursor.execute(query) df_result = as_pandas(cursor) df_result </code></pre> <p>If possible, how do I make the above idea actually work? Thanks.</p>
0
2016-08-10T21:55:32Z
38,884,244
<p>Unless I'm misunderstanding something, there's no need for the subquery at all, just move the <code>where</code> criteria to the main query:</p> <pre><code>select my_c_instance_id, count(my_c_instance_id) as my_ins_id_count from my_table where my_c_id like '%small%' group by my_c_instance_id </code></pre>
1
2016-08-10T21:58:01Z
[ "python", "sql", "impala" ]
Accessing global variables from test file
38,884,230
<p>I have a file A with 2 global variables</p> <pre><code>root = "" crumbs = [] def read(line): global root, crumbs line = line.strip() open_tag = is_valid_open(line) kv = get_kv(line) if open_tag is not None: root += open_tag + "." print root &lt;---------- prints stuff elif kv is not None: crumbs.append(kv[0] + "=" + kv[1]) print crumbs &lt;---------- prints stuff </code></pre> <p>I have a test from which I </p> <pre><code>from A import read, root, crumbs </code></pre> <p>I feed it some data</p> <pre><code> read('&lt;a&gt;') read('&lt;b&gt;') read('&lt;d&gt;acceptor&lt;/d&gt;') </code></pre> <p>And print the results</p> <pre><code> print "." + root + "." &lt;---------- prints NOTHING print "." + str(crumbs) + "." &lt;---------- prints stuff </code></pre> <p>Why do I have access to the list but not String from my test file? Seems like if one works other one should work as well.</p>
0
2016-08-10T21:57:12Z
38,884,348
<p>In short, it's because <code>+=</code> does different things for lists and strings.</p> <ul> <li><p>Strings are immutable. Therefore, <code>root += ...</code> in your <em>A.py</em> creates a new string and assigns it to <code>root</code>. There were two references to <code>root</code>: one in <em>A.py</em> and one in your test script. The <code>root +=</code> line changes only <code>root</code> in <em>A.py</em> since that's the only one that a function in <em>A.py</em> has access to. The <code>root</code> in your test module is not changed.</p></li> <li><p>Lists are mutable. Therefore, <code>crumbs +=</code> modifies the <em>existing</em> list, and doesn't change what <code>crumbs</code> points to. Since <code>crumbs</code> still refers to the same list in both <em>A.py</em> and in your test module, you see the change in your test module.</p></li> </ul> <p>It becomes clearer if you write these statements without <code>+=</code>:</p> <ul> <li><code>root = root + ...</code> obviously makes a new string and changes <code>root</code> to point to it</li> <li><code>crumbs.extend(...)</code> obviously <em>does not</em> make a new list and does not change what <code>crumbs</code> points to</li> </ul> <p>This little bit of confusion can arise when you try to access variables between modules without using fully qualified names. You end up with multiple names that initially (following the <code>import</code>) refer to the same object, but later something changes this.</p> <p>The solution is just to <code>import A</code> and refer to <code>A.root</code> and <code>A.crumbs</code> in your test script. That way there is only one canonical name for those objects, and the names are "owned" by the module that changes them.</p>
5
2016-08-10T22:06:19Z
[ "python" ]
Concise way to filter data in xarray
38,884,283
<p>I need to apply a very simple 'match statement' to the values in an xarray array:</p> <ol> <li>Where the value > 0, make 2</li> <li>Where the value == 0, make 0</li> <li>Where the value is <code>NaN</code>, make <code>NaN</code></li> </ol> <p>Here's my current solution. I'm using <code>NaN</code>s, <code>.fillna</code>, &amp; type coercion in lieu of 2d indexing.</p> <pre><code>valid = date_by_items.notnull() positive = date_by_items &gt; 0 positive = positive * 2 result = positive.fillna(0.).where(valid) result </code></pre> <p>This changes this:</p> <pre><code>In [20]: date_by_items = xr.DataArray(np.asarray((list(range(3)) * 10)).reshape(6,5), dims=('date','item')) ...: date_by_items ...: Out[20]: &lt;xarray.DataArray (date: 6, item: 5)&gt; array([[0, 1, 2, 0, 1], [2, 0, 1, 2, 0], [1, 2, 0, 1, 2], [0, 1, 2, 0, 1], [2, 0, 1, 2, 0], [1, 2, 0, 1, 2]]) Coordinates: * date (date) int64 0 1 2 3 4 5 * item (item) int64 0 1 2 3 4 </code></pre> <p>... to this:</p> <pre><code>Out[22]: &lt;xarray.DataArray (date: 6, item: 5)&gt; array([[ 0., 2., 2., 0., 2.], [ 2., 0., 2., 2., 0.], [ 2., 2., 0., 2., 2.], [ 0., 2., 2., 0., 2.], [ 2., 0., 2., 2., 0.], [ 2., 2., 0., 2., 2.]]) Coordinates: * date (date) int64 0 1 2 3 4 5 * item (item) int64 0 1 2 3 4 </code></pre> <p>While in pandas <code>df[df&gt;0] = 2</code> would be enough. Surely I'm doing something pedestrian and there's an terser way?</p>
2
2016-08-10T22:01:23Z
38,884,577
<p>If you are happy to load your data in-memory as a NumPy array, you can modify the DataArray values in place with NumPy:</p> <pre><code>date_by_items.values[date_by_items.values &gt; 0] = 2 </code></pre> <p>The cleanest way to handle this would be if xarray supported the <code>other</code> argument to <code>where</code>, but we haven't implemented that yet (hopefully soon -- the groundwork has been laid!). When that works, you'll be able to write <code>date_by_items.where(date_by_items &gt; 0, 2)</code>.</p> <p>Either way, you'll need to do this twice to apply both your criteria.</p>
3
2016-08-10T22:30:16Z
[ "python", "python-xarray" ]
Non multi part post using pycurl
38,884,321
<p>I am unable to post data to a rest server because the server doesn't know how to handle a multi part post requests,and it throws an error when it encounters a boundary. Is there a way to make a non multi part post in pycurl? Why does a post request need to be multi part?</p>
0
2016-08-10T22:04:22Z
38,884,682
<p>A POST certainly doesn't have to be multipart, see <a href="http://pycurl.io/docs/latest/quickstart.html#sending-form-data" rel="nofollow">this example</a> from the pycurl docs that I also paste here:</p> <pre><code>c = pycurl.Curl() c.setopt(c.URL, 'http://pycurl.io/tests/testpostvars.php') post_data = {'field': 'value'} # Form data must be provided already urlencoded. postfields = urlencode(post_data) # Sets request method to POST, # Content-Type header to application/x-www-form-urlencoded # and data to send in request body. c.setopt(c.POSTFIELDS, postfields) c.perform() c.close() </code></pre>
1
2016-08-10T22:38:05Z
[ "python", "http", "post", "curl", "pycurl" ]
TypeError: argument of type 'file' is not iterable 2.7 python
38,884,380
<p>I'm trying to create and write an existing dictionary to a csv file but I keep getting this error which I can't figure out:</p> <pre><code>Traceback (most recent call last): File "/Users/Danny/Desktop/Inventaris.py", line 52, in &lt;module&gt; Toevoeging_methode_plus(toevoegproduct, aantaltoevoeging) File "/Users/Danny/Desktop/Inventaris.py", line 9, in Toevoeging_methode_plus writecolumbs() File "/Users/Danny/Desktop/Inventaris.py", line 21, in writecolumbs with open("variabelen.csv", "wb") in csvfile: TypeError: argument of type 'file' is not iterable &gt;&gt;&gt; </code></pre> <p>And this is the code that gives me the error:</p> <pre><code>import csv import os def Toevoeging_methode_plus(key_to_find, definition): if key_to_find in a: current = a[key_to_find] newval = int(current) + aantaltoevoeging a[key_to_find] = int(current) + aantaltoevoeging writecolumbs() def Toevoeging_methode_minus(key_to_find, definition): if key_to_find in a: current = a[key_to_find] newval = int(current) - aantaltoevoeging a[key_to_find] = int(current) - aantaltoevoeging writecolumbs() def writecolumbs(): os.remove("variabelen.csv") with open("variabelen.csv", "wb") in csvfile: spamwriter = csv.writer(csvfile, delimiter=' ', quotechar='|', quoting=csv.QUOTE_MINIMAL) spamwriter.writerow("Product", "Aantal") spamwriter.writerows(a) a = {} with open("variabelen.csv") as csvfile: reader = csv.DictReader(csvfile) for row in reader: a[row['Product']] = row['Aantal'] print a print(""" 1. Toevoegen 2. Aftrek 3. Check """) askmenu = int(raw_input("Menu Nummer? ")) if askmenu is 1: toevoegproduct = raw_input("Productnummer &gt; ") aantaltoevoeging = int(raw_input("Hoeveel &gt; ")) Toevoeging_methode_plus(toevoegproduct, aantaltoevoeging) print a elif askmenu is 2: toevoegproduct = raw_input("Productnummer &gt; ") aantaltoevoeging = int(raw_input("Hoeveel &gt; ")) Toevoeging_methode_minus(toevoegproduct, aantaltoevoeging) writecolumbs(toevoegproduct, newval) print a elif askmenu is 3: checknummer = raw_input("Productnummer &gt; ") if checknummer in a: print a[checknummer] else: print "oops" </code></pre> <p>The csv file contains this information currently: Product Aantal 233 60 2234 1</p>
1
2016-08-10T22:10:02Z
38,884,403
<p>Write <code>as csvfile</code> not <code>in csvfile</code> on line 21.</p> <p>The <code>in</code> keyword in python is followed by an iterable, that's why you're getting that error message.</p>
3
2016-08-10T22:11:49Z
[ "python", "python-2.7", "csv" ]
How to change marker fillstyle in seaborn lmplot?
38,884,400
<p>Is it possible to change the fillstyle of a scatterplot marker in a seaborn lmplot?</p> <p>I tried: `</p> <pre><code>sns.lmplot(x=x, y=y, hue=hue, hue_order = hue_order, markers=markers, scatter_kws = {'fillstyle':'none'}) </code></pre> <p>But I get the error:</p> <pre><code>AttributeError: Unknown property fillstyle </code></pre> <p>Is fillstyle really not supported for an lmplot <code>scatter_kws</code> argument, or am I just doing something wrong?</p>
0
2016-08-10T22:11:30Z
38,902,583
<p>You can't use <code>'fillstyle':'none'</code> as a <code>scatter_kw</code> argument, but you can accomplish what you're trying to do with <code>'facecolors'</code>.</p> <pre><code>sns.lmplot(x=x, y=y, hue=hue, hue_order = hue_order, markers=markers, scatter_kws = {'facecolors':'none'}) </code></pre> <p>See the <a href="http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.scatter" rel="nofollow">matplotlib.pyplot.scatter</a> docs for more info.</p>
0
2016-08-11T17:23:26Z
[ "python", "matplotlib", "plot", "seaborn" ]
HAPI FHIR Patient Bundle Request
38,884,465
<p>I am working with a HAPI FHIR Server and am somewhat new to the java client. What I am hoping to accomplish is to create FHIR Patient Bundles that include a single identifying patient resource and all of their other resources in one complete bundle and to save it as a json file. </p> <pre><code>Patient Resource 1 Observation Resource 1 Condition Resource 1 Lab Resource 1 Observation Resource 2 ... </code></pre> <p>I come from a python background so if it would be more simple to do as request or curl to iterate through the right endpoint for the patients that would be welcome as well. This is a one-time process. If their are alternatives that are more transactional that would be great as well. Any advice is sincerely appreciated!</p>
1
2016-08-10T22:17:45Z
38,926,588
<p>it sounds like you want Patient/$everything (see <a href="http://hl7.org/fhir/patient-operations.html#everything" rel="nofollow">http://hl7.org/fhir/patient-operations.html#everything</a>) (though not all servers support that operation)</p>
2
2016-08-12T21:17:30Z
[ "python", "scala", "hl7-fhir", "hapi-fhir" ]
How to select a range of values in a pandas dataframe column?
38,884,466
<pre><code>import pandas as pd import numpy as np data = 'filename.csv' df = pd.DataFrame(data) df one two three four five a 0.469112 -0.282863 -1.509059 bar True b 0.932424 1.224234 7.823421 bar False c -1.135632 1.212112 -0.173215 bar False d 0.232424 2.342112 0.982342 unbar True e 0.119209 -1.044236 -0.861849 bar True f -2.104569 -0.494929 1.071804 bar False </code></pre> <p>I would like to select a range for a certain column, let's say column <code>two</code>. I would like to select all values between -0.5 and +0.5. How does one do this? </p> <p>I expected to use </p> <pre><code>-0.5 &lt; df["two"] &lt; 0.5 </code></pre> <p>But this (naturally) gives a ValueError: </p> <pre><code>ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). </code></pre> <p>I tried </p> <pre><code>-0.5 (&lt; df["two"] &lt; 0.5) </code></pre> <p>But this outputs all <code>True</code>. </p> <p>The correct output should be </p> <pre><code>0 True 1 False 2 False 3 False 4 False 5 True </code></pre> <p>What is the correct way to find a range of values in a pandas dataframe column?</p> <p>EDIT: Question</p> <p>Using <code>.between()</code> with </p> <pre><code>df['two'].between(-0.5, 0.5, inclusive=False) </code></pre> <p>would would be the difference between </p> <pre><code> -0.5 &lt; df['two'] &lt; 0.5 </code></pre> <p>and inequalities like </p> <pre><code> -0.5 =&lt; df['two'] &lt; 0.5 </code></pre> <p>?</p>
0
2016-08-10T22:17:45Z
38,884,502
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.between.html" rel="nofollow"><code>between</code></a> with <code>inclusive=False</code> for strict inequalities:</p> <pre><code>df['two'].between(-0.5, 0.5, inclusive=False) </code></pre> <p>The <code>inclusive</code> parameter determines if the endpoints are included or not (<code>True</code>: <code>&lt;=</code>, <code>False</code>: <code>&lt;</code>). This applies to both signs. If you want mixed inequalities, you'll need to code them explicitly:</p> <pre><code>(df['two'] &gt;= -0.5) &amp; (df['two'] &lt; 0.5) </code></pre>
3
2016-08-10T22:21:34Z
[ "python", "python-3.x", "pandas", "dataframe", "range" ]
How to select a range of values in a pandas dataframe column?
38,884,466
<pre><code>import pandas as pd import numpy as np data = 'filename.csv' df = pd.DataFrame(data) df one two three four five a 0.469112 -0.282863 -1.509059 bar True b 0.932424 1.224234 7.823421 bar False c -1.135632 1.212112 -0.173215 bar False d 0.232424 2.342112 0.982342 unbar True e 0.119209 -1.044236 -0.861849 bar True f -2.104569 -0.494929 1.071804 bar False </code></pre> <p>I would like to select a range for a certain column, let's say column <code>two</code>. I would like to select all values between -0.5 and +0.5. How does one do this? </p> <p>I expected to use </p> <pre><code>-0.5 &lt; df["two"] &lt; 0.5 </code></pre> <p>But this (naturally) gives a ValueError: </p> <pre><code>ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). </code></pre> <p>I tried </p> <pre><code>-0.5 (&lt; df["two"] &lt; 0.5) </code></pre> <p>But this outputs all <code>True</code>. </p> <p>The correct output should be </p> <pre><code>0 True 1 False 2 False 3 False 4 False 5 True </code></pre> <p>What is the correct way to find a range of values in a pandas dataframe column?</p> <p>EDIT: Question</p> <p>Using <code>.between()</code> with </p> <pre><code>df['two'].between(-0.5, 0.5, inclusive=False) </code></pre> <p>would would be the difference between </p> <pre><code> -0.5 &lt; df['two'] &lt; 0.5 </code></pre> <p>and inequalities like </p> <pre><code> -0.5 =&lt; df['two'] &lt; 0.5 </code></pre> <p>?</p>
0
2016-08-10T22:17:45Z
38,885,028
<p><code>.between</code> is a good solution, but if you want finer control use this:</p> <pre><code>(0.5 &lt;= df['two']) &amp; (df['two'] &lt; 0.5) </code></pre> <p>The operator <code>&amp;</code> is different from <code>and</code>. The other operators are <code>|</code> for <code>or</code>, <code>~</code> for <code>not</code>. See <a href="http://stackoverflow.com/questions/21415661/logic-operator-for-boolean-indexing-in-pandas">this discussion</a> for more info.</p> <p>Your statement was the same as this:</p> <pre><code>(0.5 &lt;= df['two']) and (df['two'] &lt; 0.5) </code></pre> <p>Hence it raised the error.</p>
1
2016-08-10T23:18:33Z
[ "python", "python-3.x", "pandas", "dataframe", "range" ]
Python argparse : How can I get Namespace objects for argument groups separately?
38,884,513
<p>I have some command line arguments categorized in groups as follows:</p> <pre><code>cmdParser = argparse.ArgumentParser() cmdParser.add_argument('mainArg') groupOne = cmdParser.add_argument_group('group one') groupOne.add_argument('-optA') groupOne.add_argument('-optB') groupTwo = cmdParser.add_argument_group('group two') groupTwo.add_argument('-optC') groupTwo.add_argument('-optD') </code></pre> <p>How can I parse the above, such that I end up with three different Namespace objects?</p> <pre><code>global_args - containing all the arguments not part of any group groupOne_args - containing all the arguments in groupOne groupTwo_args - containing all the arguments in groupTwo </code></pre> <p>Thank you!</p>
3
2016-08-10T22:23:04Z
38,884,659
<p>Nothing in <code>argparse</code> is designed to do that. </p> <p>For what it's worth, the <code>parser</code> starts off with two argument groups, one that displays as <code>positionals</code> and the other as <code>optionals</code> (I forget the exact titles). So in your example there will actually be 4 groups.</p> <p>The parser only uses argument groups when formatting the help. For parsing all arguments are put in a master <code>parser._actions</code> list. And during parsing the parser only passes around one namespace object.</p> <p>You could define separate parsers, with different sets of arguments, and call each with <code>parse_known_args</code>. That works better with <code>optionals</code> (flagged) arguments than with <code>positionals</code>. And it fragments your help.</p> <p>I have explored in other SO questions a novel <code>Namespace</code> class that could nest values based on some sort of dotted <code>dest</code> (names like <code>group1.optA</code>, <code>group2.optC</code>, etc). I don't recall whether I had to customize the <code>Action</code> classes or not. </p> <p>The basic point is that when saving a value to the namespace, a parser, or actually a <code>Action</code> (argument) object does:</p> <pre><code>setattr(namespace, dest, value) </code></pre> <p>That (and getattr/hasattr) is all that the parser expects of the <code>namespace</code>. The default <code>Namespace</code> class is simple, little more than a plain <code>object</code> subclass. But it could be more elaborate. </p>
2
2016-08-10T22:36:25Z
[ "python", "argparse" ]
Virtualenv (python) in Ubuntu 14.04 LTS on external hard drive
38,884,536
<p>I am trying to create a virtualenv on my external hard drive that I use for both my Ubuntu and my Windows installation (I have a SSD and use 2TB external hard drive for anything but PC games).</p> <p>When I navigate to the place and try to create it with the commands that work on the standard Ubuntu home drive, I get the following:</p> <pre><code>nebelhom@nebelhom-desktop:/media/extHDD/virt_folder$ virtualenv MyFolder New python executable in /media/nebelhom/extHDD/virt_folder/MyFolder/bin/python ERROR: The executable /media/nebelhom/extHDD/virt_folder/MyFolder/bin/python could not be run: [Errno 13] Permission denied </code></pre> <p>Running the same with "sudo" did not help either and gave the same error as above.</p> <p>What I tried next is indicating the python version</p> <pre><code>nebelhom@nebelhom-desktop:/media/nebelhom/extHDD/virt_folder$ sudo virtualenv -p python2.7 MyFolder Running virtualenv with interpreter /usr/bin/python2.7 New python executable in /media/nebelhom/extHDD/virt_folder/MyFolder/bin/python2.7 Not overwriting existing python script /media/nebelhom/extHDD/virt_folder/MyFolder/bin/python (you must use /media/nebelhom/extHDD/virt_folder/MyFolder/bin/python2.7) Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/virtualenv.py", line 2332, in &lt;module&gt; main() File "/usr/local/lib/python2.7/dist-packages/virtualenv.py", line 711, in main symlink=options.symlink) File "/usr/local/lib/python2.7/dist-packages/virtualenv.py", line 924, in create_environment site_packages=site_packages, clear=clear, symlink=symlink)) File "/usr/local/lib/python2.7/dist-packages/virtualenv.py", line 1369, in install_python os.symlink(py_executable_base, full_pth) OSError: [Errno 17] File exists </code></pre> <p>And now I am stuck :/ . Has anyone of you tried something like this before and succeeded? I am really out of ideas here...</p> <p>I tried to search for a solution previously, but for this particular problem I did not find anything useful. I will carry on looking and post any link that I can find that might be remotely related.</p> <p>Thanks in advance for any help you can offer. It is much appreciated.</p>
1
2016-08-10T22:27:03Z
38,885,487
<p>Seems like Python is having trouble with permission on that folder.</p> <p>Try giving root permission on the folder using this command:</p> <pre><code>sudo chown root:root -R /media/nebelhom/extHDD/virt_folder/MyFolder </code></pre> <p>Then run this command to create the virtualenv:</p> <pre><code>sudo virtualenv /media/nebelhom/extHDD/virt_folder/MyFolder </code></pre>
0
2016-08-11T00:21:53Z
[ "python", "ubuntu", "virtualenv" ]
Virtualenv (python) in Ubuntu 14.04 LTS on external hard drive
38,884,536
<p>I am trying to create a virtualenv on my external hard drive that I use for both my Ubuntu and my Windows installation (I have a SSD and use 2TB external hard drive for anything but PC games).</p> <p>When I navigate to the place and try to create it with the commands that work on the standard Ubuntu home drive, I get the following:</p> <pre><code>nebelhom@nebelhom-desktop:/media/extHDD/virt_folder$ virtualenv MyFolder New python executable in /media/nebelhom/extHDD/virt_folder/MyFolder/bin/python ERROR: The executable /media/nebelhom/extHDD/virt_folder/MyFolder/bin/python could not be run: [Errno 13] Permission denied </code></pre> <p>Running the same with "sudo" did not help either and gave the same error as above.</p> <p>What I tried next is indicating the python version</p> <pre><code>nebelhom@nebelhom-desktop:/media/nebelhom/extHDD/virt_folder$ sudo virtualenv -p python2.7 MyFolder Running virtualenv with interpreter /usr/bin/python2.7 New python executable in /media/nebelhom/extHDD/virt_folder/MyFolder/bin/python2.7 Not overwriting existing python script /media/nebelhom/extHDD/virt_folder/MyFolder/bin/python (you must use /media/nebelhom/extHDD/virt_folder/MyFolder/bin/python2.7) Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/virtualenv.py", line 2332, in &lt;module&gt; main() File "/usr/local/lib/python2.7/dist-packages/virtualenv.py", line 711, in main symlink=options.symlink) File "/usr/local/lib/python2.7/dist-packages/virtualenv.py", line 924, in create_environment site_packages=site_packages, clear=clear, symlink=symlink)) File "/usr/local/lib/python2.7/dist-packages/virtualenv.py", line 1369, in install_python os.symlink(py_executable_base, full_pth) OSError: [Errno 17] File exists </code></pre> <p>And now I am stuck :/ . Has anyone of you tried something like this before and succeeded? I am really out of ideas here...</p> <p>I tried to search for a solution previously, but for this particular problem I did not find anything useful. I will carry on looking and post any link that I can find that might be remotely related.</p> <p>Thanks in advance for any help you can offer. It is much appreciated.</p>
1
2016-08-10T22:27:03Z
38,901,490
<p>I think its happening because of filesystem on your external HDD. From your question I can guess that you use your external hard disk with both windows and linux, and its file system might be NTFS.</p> <p>File permissions don't exist on NTFS and all the usual linux things like chown and chmod, that can be the reason why you are having these problems. </p> <p>I would suggest, that you try to create a new partition on your ext HDD using a linux based filesystem like ext4. Then try to create a virtual environment.</p> <p>I have tried creating python virtual environment on a removable disk, worked like a charm, only the FS was ext4.</p>
1
2016-08-11T16:16:01Z
[ "python", "ubuntu", "virtualenv" ]
Python Pandas find all rows where all values are NaN
38,884,538
<p>So I have a dataframe with 5 columns. I would like to pull the indices where all of the columns are NaN. I was using this code:</p> <pre><code>nan = pd.isnull(df.all) </code></pre> <p>but that is just returning false because it is logically saying no not all values in the dataframe are null. There are thousands of entries so I would prefer to not have to loop through and check each entry. Thanks!</p>
1
2016-08-10T22:27:24Z
38,884,563
<p>It should just be:</p> <pre><code>df.isnull().all(1) </code></pre> <p>The <code>index</code> can be accessed like:</p> <pre><code>df.index[df.isnull().all(1)] </code></pre> <h3>Demonstration</h3> <pre><code>np.random.seed([3,1415]) df = pd.DataFrame(np.random.choice((1, np.nan), (10, 2))) df </code></pre> <p><a href="http://i.stack.imgur.com/0iX5A.png" rel="nofollow"><img src="http://i.stack.imgur.com/0iX5A.png" alt="enter image description here"></a></p> <pre><code>idx = df.index[df.isnull().all(1)] nans = df.ix[idx] nans </code></pre> <p><a href="http://i.stack.imgur.com/0R6tc.png" rel="nofollow"><img src="http://i.stack.imgur.com/0R6tc.png" alt="enter image description here"></a></p> <hr> <h3>Timing</h3> <p><strong>code</strong></p> <pre><code>np.random.seed([3,1415]) df = pd.DataFrame(np.random.choice((1, np.nan), (10000, 5))) </code></pre> <p><a href="http://i.stack.imgur.com/qD0tb.png" rel="nofollow"><img src="http://i.stack.imgur.com/qD0tb.png" alt="enter image description here"></a></p>
2
2016-08-10T22:29:15Z
[ "python", "python-2.7", "pandas" ]
Python Pandas find all rows where all values are NaN
38,884,538
<p>So I have a dataframe with 5 columns. I would like to pull the indices where all of the columns are NaN. I was using this code:</p> <pre><code>nan = pd.isnull(df.all) </code></pre> <p>but that is just returning false because it is logically saying no not all values in the dataframe are null. There are thousands of entries so I would prefer to not have to loop through and check each entry. Thanks!</p>
1
2016-08-10T22:27:24Z
38,884,567
<p>Assuming your dataframe is named <code>df</code>, you can use boolean indexing to check if all columns (<code>axis=1</code>) are null. Then take the index of the result.</p> <pre><code>np.random.seed(0) df = pd.DataFrame(np.random.randn(5, 3)) df.iloc[-2:, :] = np.nan &gt;&gt;&gt; df 0 1 2 0 1.764052 0.400157 0.978738 1 2.240893 1.867558 -0.977278 2 0.950088 -0.151357 -0.103219 3 NaN NaN NaN 4 NaN NaN NaN nan = df[df.isnull().all(axis=1)].index &gt;&gt;&gt; nan Int64Index([3, 4], dtype='int64') </code></pre>
1
2016-08-10T22:29:32Z
[ "python", "python-2.7", "pandas" ]
Python Pandas find all rows where all values are NaN
38,884,538
<p>So I have a dataframe with 5 columns. I would like to pull the indices where all of the columns are NaN. I was using this code:</p> <pre><code>nan = pd.isnull(df.all) </code></pre> <p>but that is just returning false because it is logically saying no not all values in the dataframe are null. There are thousands of entries so I would prefer to not have to loop through and check each entry. Thanks!</p>
1
2016-08-10T22:27:24Z
38,884,571
<p>From the master himself: <a href="http://stackoverflow.com/a/14033137/6664393">http://stackoverflow.com/a/14033137/6664393</a></p> <pre><code>nans = pd.isnull(df).all(1).nonzero()[0] </code></pre>
0
2016-08-10T22:30:01Z
[ "python", "python-2.7", "pandas" ]
How do I write version files for pyinstaller 3.2
38,884,579
<p>I'm trying to convert my python script to an exe and everything went well until I added a version file, it threw this error and I don't know what it means. I've seen different posts about version files and I've tried them all and I keep getting this error:</p> <pre><code>Traceback (most recent call last): File "C:\Users\Afro\AppData\Local\Programs\Python\Python35-32\Scripts\pyinstaller-script.py", line 9, in &lt;module&gt; load_entry_point('PyInstaller==3.2', 'console_scripts', 'pyinstaller')() File "c:\users\afro\appdata\local\programs\python\python35-32\lib\site-packages\PyInstaller\__main__.py", line 90, in run run_build(pyi_config, spec_file, **vars(args)) File "c:\users\afro\appdata\local\programs\python\python35-32\lib\site-packages\PyInstaller\__main__.py", line 46, in run_build PyInstaller.building.build_main.main(pyi_config, spec_file, **kwargs) File "c:\users\afro\appdata\local\programs\python\python35-32\lib\site-packages\PyInstaller\building\build_main.py", line 788, in main build(specfile, kw.get('distpath'), kw.get('workpath'), kw.get('clean_build')) File "c:\users\afro\appdata\local\programs\python\python35-32\lib\site-packages\PyInstaller\building\build_main.py", line 734, in build exec(text, spec_namespace) File "&lt;string&gt;", line 26, in &lt;module&gt; File "c:\users\afro\appdata\local\programs\python\python35-32\lib\site-packages\PyInstaller\building\api.py", line 407, in __init__ self.__postinit__() File "c:\users\afro\appdata\local\programs\python\python35-32\lib\site-packages\PyInstaller\building\datastruct.py", line 178, in __postinit__ self.assemble() File "c:\users\afro\appdata\local\programs\python\python35-32\lib\site-packages\PyInstaller\building\api.py", line 496, in assemble versioninfo.SetVersion(tmpnm, self.versrsrc) File "c:\users\afro\appdata\local\programs\python\python35-32\lib\site-packages\PyInstaller\utils\win32\versioninfo.py", line 557, in SetVersion win32api.UpdateResource(hdst, pefile.RESOURCE_TYPE['RT_VERSION'], 1, vs.toRaw()) File "c:\users\afro\appdata\local\programs\python\python35-32\lib\site-packages\PyInstaller\utils\win32\versioninfo.py", line 160, in toRaw nm = pywintypes.Unicode(u'VS_VERSION_INFO') TypeError: argument 1 (impossible&lt;bad format char&gt;) </code></pre> <p>and here's my version file:</p> <pre><code>VSVersionInfo( ffi=FixedFileInfo( filevers=(1, 0, 0, 0), prodvers=(1, 0, 0, 0), mask=0x3f, flags=0x0, OS=0x40004, fileType=0x1, subtype=0x0, date=(0, 0) ), kids=[ StringFileInfo( [ StringTable( u'040904B0', [StringStruct(u'CompanyName', u'getSERIES'), StringStruct(u'FileDescription', u'get it'), StringStruct(u'FileVersion', u'6.1.7601.17514 (win7sp1_rtm.101119-1850)'), StringStruct(u'InternalName', u'getSERIES'), StringStruct(u'LegalCopyright', u'HA corporation. All rights reserved.'), StringStruct(u'OriginalFilename', u'getSERIES.Exe'), StringStruct(u'ProductName', u'getSERIES'), StringStruct(u'ProductVersion', u'1, 0, 0, 0')]) ]), VarFileInfo([VarStruct(u'Translation', [1033, 1200])]) ] ) </code></pre>
0
2016-08-10T22:30:25Z
38,920,563
<p>Your version file should be good enough. The problem is in PyInstaller's versioninfo.py which is probably has no Python3 support at this time.<br> As a simple workaround, you can try to use a resource editor (e.g. <a href="http://www.codeproject.com/Articles/37133/Simple-Version-Resource-Tool-for-Windows" rel="nofollow">http://www.codeproject.com/Articles/37133/Simple-Version-Resource-Tool-for-Windows</a>) to add version info to your application.<br> Related pyinstaller issue for additional information: <a href="https://github.com/pyinstaller/pyinstaller/issues/1347" rel="nofollow">https://github.com/pyinstaller/pyinstaller/issues/1347</a>.</p>
0
2016-08-12T14:37:04Z
[ "python", "python-3.x", "version", "pyinstaller" ]
Multithreading frozen in Python Spyder but not command prompt Windows 10
38,884,587
<p>I am running a script inside Spyder that utilizes the multithreading library and the IPython console freezes with the output below. However, running the script using Windows command prompt via 'python quickstart11.py' works fine and generates the proper output.</p> <pre><code> runfile('C:/Python35/User/backtrader-master/docs/quickstart/quickstart11.py', wdir='C:/Python35/User/backtrader-master/docs/quickstart') Exception in thread Thread-8: Traceback (most recent call last): File "C:\Anaconda3\lib\threading.py", line 914, in _bootstrap_inner self.run() File "C:\Anaconda3\lib\threading.py", line 862, in run self._target(*self._args, **self._kwargs) File "C:\Anaconda3\lib\multiprocessing\pool.py", line 429, in _handle_results task = get() File "C:\Anaconda3\lib\multiprocessing\connection.py", line 251, in recv return ForkingPickler.loads(buf.getbuffer()) AttributeError: Can't get attribute 'TestStrategy' on &lt;module '__main__' (&lt;_frozen_importlib_external.SourceFileLoader object at 0x000002727C461438&gt;)&gt; </code></pre> <p>I've tried adding freeze_support() according to <a href="https://docs.python.org/2/library/multiprocessing.html#multiprocessing.freeze_support" rel="nofollow">Python doc</a>, which should alleviate the problem, but it still freezes. What is going on?</p> <p>Windows 10 64bit, Anaconda Python 35 64bit installer.</p>
0
2016-08-10T22:30:53Z
40,104,374
<p>The problem is in Spyder. The kernel is running in interpreted mode and the addition of "freeze_support" doesn't happend before other things even if that's the intention, because the kernel is already running.</p> <p>See here: <a href="https://github.com/mementum/backtrader/issues/118" rel="nofollow">https://github.com/mementum/backtrader/issues/118</a></p>
0
2016-10-18T09:24:14Z
[ "python", "windows", "multithreading", "spyder" ]