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 eithe... | 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 ... | 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 eithe... | 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(... | 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 ... | 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 <= high:
res = res + (n+i)
i = i + 1
print res
return res
def p(high):
i = 1
lumpSum = 0
while i <= high:
lumpSum... | 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 ... | 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 <= 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 P... | 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.li... | 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 receiv... | 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... | 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... | 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_... | 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(l... | 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... | 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(l... | 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>>>> sum([.1]*10)
0.9999999999999999 # 1.... | 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 spect... | 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... | 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, <cod... | 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)
la... | 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(se... | 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 i... | 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 ... | 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 ... | 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=10... | 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... | 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... | 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 so... | 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 ... | 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')])
... | 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 ... | 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 =... | 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 ... | 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.dr... | 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 ... | 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, ... | 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>""<... | 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 thr... | 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>""<... | 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>""<... | 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 ... | 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) <... | 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
log... | 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
log... | 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 ... | 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... | 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... | 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)
i... | 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 i... | 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 .tx... | 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 i... | 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... | 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 re... | 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(' ' * i... | 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 re... | 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.na... | 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,... | 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... | 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 > "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 er... | 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 > "2016-05-13 00:00:... | 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 h... | 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'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 fo... | 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_tabl... | 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... | 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 loo... | 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 loo... | 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 in... | 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 loo... | 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) + " betwe... | -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... | 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 suf... | 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 ()
d... | 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... | 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 ()
d... | 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 ()
d... | 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="nofo... | 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 star... | -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 star... | -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 sp... | 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):
... | -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 functio... | 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):
... | -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>>>> class A:
def __init__(self):
self.fun = 42
def fun(self):
print( "funny" )
>>> a = A()
&g... | 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,
l... | 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... | 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&dd=6100&id=13060600641" rel="nofollow">https://www.austintexas.gov/financeonline/con... | 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("---... | 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', ... | 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... | 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... | 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 170... | 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:
... | 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 a... | 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 a... | 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 a... | 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 stateme... | 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 a... | 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\x... | 1 | 2016-08-10T21:02:42Z | 38,883,513 | <p>Use <code>rstrip</code></p>
<pre><code>>>> text = 'Hello\x00\x00\x00\x00'
>>> 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\x... | 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
... | 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 purp... | 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++ function... | 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 w... | 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++ function... | 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... | 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 d... | -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 d... | -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, in... | 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 d... | -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 <= idx < len(room_funcs):
room_funcs[idx]()
else:
print("I... | 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 d... | -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... | 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 d... | -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_e... | 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... | 0 | 2016-08-10T21:23:47Z | 38,884,045 | <p>a little more complex than divide & 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... | 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="t... | 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.redh... | 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
f... | 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:
... | 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 arrive... | 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:
... | 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>
... | 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... | 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):
# ou... | 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... | 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 ... | 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 ... | 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<len:
if ... | 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/q... | 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<len:
if ... | 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>a... | 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<len:
if ... | 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_... | 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:... | 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:... | 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:... | 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... | 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>"\\"</... | 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... | 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"
</c... | 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
<mym... | 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):
... | 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_instanc... | 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 <----------... | 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 ... | 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</... | 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 > 0] = 2
</code></pre>
<p>The cleanest way to handle this would be if xarray supported the <code>other</code> argument to <code>where</... | 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': ... | 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 <module>
Toevoeging_methode_plus(toevoegproduct, aantaltoevoeging)
File "... | 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 er... | 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_... | 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... | 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 Tru... | 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 determ... | 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 Tru... | 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 <= df['two']) & (df['two'] < 0.5)
</code></pre>
<p>The operator <code>&</code> is different from <code>and</code>. The other operators are <code>|</code> for <code>or</code>, <code>~</code> for <code... | 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('gr... | 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.<... | 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 g... | 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 virtualen... | 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 g... | 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 reaso... | 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... | 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><... | 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... | 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
>>> df
0 1 ... | 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... | 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:\... | 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="nofol... | 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/backtrade... | 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... | 0 | 2016-10-18T09:24:14Z | [
"python",
"windows",
"multithreading",
"spyder"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.