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
sequencelengths 1
5
|
---|---|---|---|---|---|---|---|---|---|
Why is my Python script not running via command line? | 40,138,529 | <p>Thanks!</p>
<pre><code>def hello(a,b):
print "hello and that's your sum:"
sum=a+b
print sum
import sys
if __name__ == "__main__":
hello(sys.argv[2])
</code></pre>
<p>It does not work for me, I appreciate the help!!!
Thanks!</p>
| -1 | 2016-10-19T18:01:27Z | 40,138,672 | <ul>
<li>Import <code>sys</code> in <strong>global scope</strong>, not in the end of the function.</li>
<li>Send <strong>two arguments</strong> into <code>hello</code>, one is not enough. </li>
<li>Convert these arguments to <strong>floats</strong>, so they can be added as numbers.</li>
<li><strong>Indent</strong> properly. In python indentation <em>does</em> matter.</li>
</ul>
<p>That should result in:</p>
<pre><code>import sys
def hello(a, b):
sum = a + b
print "hello and that's your sum:", sum
if __name__ == "__main__":
hello(float(sys.argv[1]), float(sys.argv[2]))
</code></pre>
| 2 | 2016-10-19T18:10:07Z | [
"python"
] |
Python: How to develop a between_time similar method when on pandas 0.9.0? | 40,138,573 | <p>I am stick to pandas 0.9.0 as I'm working under python 2.5, hence I have no <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.between_time.html" rel="nofollow">between_time</a> method available. </p>
<p>I have a DataFrame of dates and would like to filter all the dates that are between certain hours, e.g. between <code>08:00</code> and <code>09:00</code> for all the dates within the DataFrame <code>df</code>.</p>
<pre><code>import pandas as pd
import numpy as np
import datetime
dates = pd.date_range(start="08/01/2009",end="08/01/2012",freq="10min")
df = pd.DataFrame(np.random.rand(len(dates), 1)*1500, index=dates, columns=['Power'])
</code></pre>
<p>How can I develop a method that provides same functionality as <code>between_time</code> method?</p>
<p>N.B.: The original problem I am trying to accomplish is under <a href="http://stackoverflow.com/questions/40117702/python-filter-dataframe-in-pandas-by-hour-day-and-month-grouped-by-year">Python: Filter DataFrame in Pandas by hour, day and month grouped by year</a></p>
| 1 | 2016-10-19T18:03:58Z | 40,138,627 | <p><strong>UPDATE:</strong></p>
<p>try to use:</p>
<pre><code>df.ix[df.index.indexer_between_time('08:00','09:50')]
</code></pre>
<p><strong>OLD answer:</strong></p>
<p>I'm not sure that it'll work on Pandas 0.9.0, but it's worth to try it:</p>
<pre><code>df[(df.index.hour >= 8) & (df.index.hour <= 9)]
</code></pre>
<p>PS please be aware - it's not the same as <code>between_time</code> as it checks only hours and <code>between_time</code> is able to check <strong>time</strong> like <code>df.between_time('08:01:15','09:13:28')</code></p>
<p><strong>Hint</strong>: download a source code for a newer version of Pandas and take a look at the definition of <code>indexer_between_time()</code> function in <code>pandas/tseries/index.py</code> - you can clone it for your needs</p>
| 2 | 2016-10-19T18:06:52Z | [
"python",
"pandas",
"python-2.5"
] |
Python: How to develop a between_time similar method when on pandas 0.9.0? | 40,138,573 | <p>I am stick to pandas 0.9.0 as I'm working under python 2.5, hence I have no <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.between_time.html" rel="nofollow">between_time</a> method available. </p>
<p>I have a DataFrame of dates and would like to filter all the dates that are between certain hours, e.g. between <code>08:00</code> and <code>09:00</code> for all the dates within the DataFrame <code>df</code>.</p>
<pre><code>import pandas as pd
import numpy as np
import datetime
dates = pd.date_range(start="08/01/2009",end="08/01/2012",freq="10min")
df = pd.DataFrame(np.random.rand(len(dates), 1)*1500, index=dates, columns=['Power'])
</code></pre>
<p>How can I develop a method that provides same functionality as <code>between_time</code> method?</p>
<p>N.B.: The original problem I am trying to accomplish is under <a href="http://stackoverflow.com/questions/40117702/python-filter-dataframe-in-pandas-by-hour-day-and-month-grouped-by-year">Python: Filter DataFrame in Pandas by hour, day and month grouped by year</a></p>
| 1 | 2016-10-19T18:03:58Z | 40,139,164 | <p>Here is a NumPy-based way of doing it:</p>
<pre><code>import pandas as pd
import numpy as np
import datetime
dates = pd.date_range(start="08/01/2009",end="08/01/2012",freq="10min")
df = pd.DataFrame(np.random.rand(len(dates), 1)*1500, index=dates, columns=['Power'])
epoch = np.datetime64('1970-01-01')
start = np.datetime64('1970-01-01 08:00:00')
end = np.datetime64('1970-01-01 09:00:00')
# convert the dates to a NumPy datetime64 array
date_array = df.index.asi8.astype('<M8[ns]')
# replace the year/month/day with 1970-01-01
truncated = (date_array - date_array.astype('M8[D]')) + epoch
# compare the hour/minute/seconds etc with `start` and `end`
mask = (start <= truncated) & (truncated <=end)
print(df[mask])
</code></pre>
<p>yields</p>
<pre><code> Power
2009-08-01 08:00:00 1007.289466
2009-08-01 08:10:00 770.732422
2009-08-01 08:20:00 617.388909
2009-08-01 08:30:00 1348.384210
...
2012-07-31 08:30:00 999.133350
2012-07-31 08:40:00 1451.500408
2012-07-31 08:50:00 1161.003167
2012-07-31 09:00:00 670.545371
</code></pre>
| 1 | 2016-10-19T18:37:35Z | [
"python",
"pandas",
"python-2.5"
] |
Python find and replace dialog from Rapid GUI Programming error | 40,138,639 | <p>When building the find and replace dialog from "Rapid GUI Programming with Python and Qt (Chapter 07), by Prentice Hall (Mark Sumerfield)", I get the following error:</p>
<pre><code> import ui_findandreplacedlg
ImportError: No module named ui_findandreplacedlg
</code></pre>
<p>Depending on which version of python I run, I also get:</p>
<pre><code>File "findandreplacedlg.py", line 7, in <module>
ui_findandreplacedlg.Ui_FindAndReplaceDlg):
AttributeError: 'module' object has no attribute 'Ui_FindAndReplaceDlg'
</code></pre>
<p>I got the source code from their website and it errors on the same line in the same way. I've searched the errata on their webpage with no mention whatsoever. Does anyone know what the solution is? </p>
| 1 | 2016-10-19T18:07:41Z | 40,138,698 | <p>The code in question can be found here - <a href="https://github.com/suzp1984/pyqt5-book-code/blob/master/chap07/ui_findandreplacedlg.py" rel="nofollow">https://github.com/suzp1984/pyqt5-book-code/blob/master/chap07/ui_findandreplacedlg.py</a>. If that file is in the same directory as the code you're trying to run, just do </p>
<pre><code>import ui_findandreplacedlg
</code></pre>
| 0 | 2016-10-19T18:12:02Z | [
"python",
"qt",
"pyqt",
"importerror"
] |
Theano's function() reports that my `givens` value is not needed for the graph | 40,138,656 | <p>Sorry for not posting entire snippets -- the code is very big and spread out, so hopefully this can illustrate my issue. I have these:</p>
<pre><code>train = theano.function([X], output, updates=update_G,
givens={train_mode=:np.cast['int32'](1)})
</code></pre>
<p>and </p>
<pre><code>test = theano.function([X], output, updates=update_G,
givens={train_mode=:np.cast['int32'](0)})
</code></pre>
<p>to my understanding, <code>givens</code> would input the value of <code>train_mode</code> (i.e. <code>1</code>/<code>0</code>) wherever it's needed to compute the output.</p>
<p>The <code>output</code> is computed in the lines of this:</p>
<pre><code> ...
network2 = Net2()
# This is sort of a dummy variable so I don't get a NameError when this
# is called before `theano.function()` is called. Not sure if this is the
# right way to do this.
train_mode = T.iscalar('train_mode')
output = loss(network1.get_outputs(network2.get_outputs(X, train_mode=train_mode)),something).mean()
....
class Net2():
def get_outputs(self, x, train_mode):
from theano.ifelse import ifelse
import theano.tensor as T
my_flag = ifelse(T.eq(train_mode, 1), 1, 0)
return something if my_flag else something_else
</code></pre>
<p>So <code>train_mode</code> is used as an argument in one of the nested functions, and I use it to tell between <code>train</code> and <code>test</code> as I'd like to handle them slightly differently.</p>
<p>However, when I try to run this, I get this error:</p>
<pre><code>theano.compile.function_module.UnusedInputError: theano.function was
asked to create a function computing outputs given certain inputs, but
the provided input variable at index 1 is not part of the computational
graph needed to compute the outputs: <TensorType(int32, scalar)>.To make
this error into a warning, you can pass the parameter
on_unused_input='warn' to theano.function. To disable it completely, use
on_unused_input='ignore'.
</code></pre>
<p>If I delete the <code>givens</code> parameter, the error disappears, so to my understanding Theano believes that my <code>train_mode</code> is not necessary for compute the <code>function()</code>. I can use <code>on_unusued_input='ignore'</code> as per their suggestion, but that would just ignore my <code>train_mode</code> if they think it's unused. Am I going around this the wrong way? I basically just want to train a neural network with dropout, but not use dropout when evaluating.</p>
| 0 | 2016-10-19T18:09:13Z | 40,139,049 | <p>why you use "=" sign? I think, it made train_mode not readable, my code works well by writing:
<code>givens = {train_mode:1}</code></p>
| 0 | 2016-10-19T18:31:37Z | [
"python",
"neural-network",
"deep-learning",
"theano",
"conv-neural-network"
] |
Concatenate string using .format | 40,138,709 | <p>I have some code similar to the following:</p>
<pre><code>test_1 = 'bob'
test_2 = 'jeff'
test_1 += "-" + test_2 + "\n"
</code></pre>
<p>Output:</p>
<pre><code>bob- jeff\n
</code></pre>
<p>I'd like to have the same functionality but using the <code>.format</code> method.</p>
<p>This is what I have so far:</p>
<pre><code>test_1 = "{}{} {}\n".format(test_1, "-", test_2)
</code></pre>
<p>Which produces the same output, but is there a better/more efficient way of using <code>.format.</code> in this case?</p>
| 0 | 2016-10-19T18:12:23Z | 40,139,006 | <p><code>''.join</code> is probably fast enough and efficient.</p>
<pre><code>'-'.join((test_1,test_2))
</code></pre>
<p>You can measure different methods using the <code>timeit</code> module. That can tell you which is fastest </p>
<p>This is an example of how <code>timeit</code> can be used:-</p>
<pre><code>>>> import timeit
>>> timeit.timeit('"-".join(str(n) for n in range(100))', number=10000)
0.8187260627746582
</code></pre>
| 1 | 2016-10-19T18:29:01Z | [
"python",
"string",
"python-2.7",
"string-formatting",
"string-concatenation"
] |
Python - Return integer value for list enumeration | 40,138,958 | <p>Is there a cleaner way to get an integer value of the position of a list item in this code:</p>
<pre><code>a = ['m', 'rt', 'paaq', 'panc']
loc = [i for i, x in enumerate(a) if x == 'rt']
loc_str = str(loc).strip('[]')
loc_int = int(loc_str)
id_list = a[loc_int + 1:]
print id_list
</code></pre>
<p>Returns all items after 'rt' as a list ['paaq', 'panc']</p>
| 0 | 2016-10-19T18:26:48Z | 40,138,998 | <p>Yes, use <code>list.index()</code>.</p>
<pre><code>a = ['m', 'rt', 'paaq', 'panc']
id_list = a[a.index('rt')+1:]
assert id_list == ['paaq', 'panc']
</code></pre>
<p>Or, to minimally change your program:</p>
<pre><code>a = ['m', 'rt', 'paaq', 'panc']
loc_int = a.index('rt')
id_list = a[loc_int + 1:]
print id_list
</code></pre>
<p>References:</p>
<ul>
<li><a href="https://docs.python.org/2/library/stdtypes.html#sequence-types-str-unicode-list-tuple-bytearray-buffer-xrange" rel="nofollow">https://docs.python.org/2/library/stdtypes.html#sequence-types-str-unicode-list-tuple-bytearray-buffer-xrange</a></li>
<li><a href="https://docs.python.org/2/tutorial/datastructures.html#more-on-lists" rel="nofollow">https://docs.python.org/2/tutorial/datastructures.html#more-on-lists</a></li>
</ul>
| 5 | 2016-10-19T18:28:22Z | [
"python",
"enumerate"
] |
Python - Return integer value for list enumeration | 40,138,958 | <p>Is there a cleaner way to get an integer value of the position of a list item in this code:</p>
<pre><code>a = ['m', 'rt', 'paaq', 'panc']
loc = [i for i, x in enumerate(a) if x == 'rt']
loc_str = str(loc).strip('[]')
loc_int = int(loc_str)
id_list = a[loc_int + 1:]
print id_list
</code></pre>
<p>Returns all items after 'rt' as a list ['paaq', 'panc']</p>
| 0 | 2016-10-19T18:26:48Z | 40,139,042 | <pre><code>a[a.index('rt') + 1:]
</code></pre>
<p>What this is doing is <a href="https://docs.python.org/2.3/whatsnew/section-slices.html" rel="nofollow">slicing</a> the array, starting at where <code>a.index('rt')</code>. not specifying an end <code>:]</code> means we want until the end of the list.</p>
| 0 | 2016-10-19T18:31:08Z | [
"python",
"enumerate"
] |
Python - dividing a user input to display a range of answers | 40,139,135 | <p>I'm having problems with a Python question. The question is to write a function that shows all integers that are cleanly divisble by 13 in the range of (1:x) where x is a user input.
I'm new to Python and am struggling with this question. I need to have a user input which Python then divides by 13 and displays the answer(s). So, if a user inputs '27', the answers would be '13' and '26'. </p>
<p>My code so far is: </p>
<pre><code> x = int(raw_input('Enter your Number Here: '))
def divide(x):
cond = True
while cond:
x % 13 == 0
print x
else:
cond = False
print 'Your number us not divisble by 13'
divide(x)
</code></pre>
| 0 | 2016-10-19T18:36:31Z | 40,139,252 | <p><code>x % 13 == 0</code> by itself does nothing; it evaluates to True or False, but you then ignore that result. If you want to do something with it, you need to use it in an if condition.</p>
<p>Note also that indentation is important - the else needs to be lined up with the if. There's no need for <code>while</code> at all because nothing can change within the loop.</p>
<pre><code>if x % 13 == 0:
print x
else:
print 'Your number us not divisible by 13'
</code></pre>
| 0 | 2016-10-19T18:44:26Z | [
"python",
"python-2.7",
"python-3.x"
] |
Python - dividing a user input to display a range of answers | 40,139,135 | <p>I'm having problems with a Python question. The question is to write a function that shows all integers that are cleanly divisble by 13 in the range of (1:x) where x is a user input.
I'm new to Python and am struggling with this question. I need to have a user input which Python then divides by 13 and displays the answer(s). So, if a user inputs '27', the answers would be '13' and '26'. </p>
<p>My code so far is: </p>
<pre><code> x = int(raw_input('Enter your Number Here: '))
def divide(x):
cond = True
while cond:
x % 13 == 0
print x
else:
cond = False
print 'Your number us not divisble by 13'
divide(x)
</code></pre>
| 0 | 2016-10-19T18:36:31Z | 40,139,287 | <p>Can do this:</p>
<pre><code>x = int(input("Enter your number here: "))
def divide(x):
for i in range(1,x):
if i % 13 == 0:
print (i)
divide(x)
</code></pre>
| 0 | 2016-10-19T18:46:33Z | [
"python",
"python-2.7",
"python-3.x"
] |
Python - dividing a user input to display a range of answers | 40,139,135 | <p>I'm having problems with a Python question. The question is to write a function that shows all integers that are cleanly divisble by 13 in the range of (1:x) where x is a user input.
I'm new to Python and am struggling with this question. I need to have a user input which Python then divides by 13 and displays the answer(s). So, if a user inputs '27', the answers would be '13' and '26'. </p>
<p>My code so far is: </p>
<pre><code> x = int(raw_input('Enter your Number Here: '))
def divide(x):
cond = True
while cond:
x % 13 == 0
print x
else:
cond = False
print 'Your number us not divisble by 13'
divide(x)
</code></pre>
| 0 | 2016-10-19T18:36:31Z | 40,139,338 | <p>Instead you can do something like:</p>
<pre><code>x = 27 / 13
print [13 * i for i in range(1,x+1)]
</code></pre>
| 0 | 2016-10-19T18:49:44Z | [
"python",
"python-2.7",
"python-3.x"
] |
Python - dividing a user input to display a range of answers | 40,139,135 | <p>I'm having problems with a Python question. The question is to write a function that shows all integers that are cleanly divisble by 13 in the range of (1:x) where x is a user input.
I'm new to Python and am struggling with this question. I need to have a user input which Python then divides by 13 and displays the answer(s). So, if a user inputs '27', the answers would be '13' and '26'. </p>
<p>My code so far is: </p>
<pre><code> x = int(raw_input('Enter your Number Here: '))
def divide(x):
cond = True
while cond:
x % 13 == 0
print x
else:
cond = False
print 'Your number us not divisble by 13'
divide(x)
</code></pre>
| 0 | 2016-10-19T18:36:31Z | 40,139,408 | <p>Borrow the back-ported print function Python 3:</p>
<pre><code>from __future__ import print_function
</code></pre>
<p>The following will print all numbers in the range [1..x] inclusive</p>
<pre><code>print([y for y in range(1,x+1,1) if y%13==0])
</code></pre>
| 0 | 2016-10-19T18:54:25Z | [
"python",
"python-2.7",
"python-3.x"
] |
Python - dividing a user input to display a range of answers | 40,139,135 | <p>I'm having problems with a Python question. The question is to write a function that shows all integers that are cleanly divisble by 13 in the range of (1:x) where x is a user input.
I'm new to Python and am struggling with this question. I need to have a user input which Python then divides by 13 and displays the answer(s). So, if a user inputs '27', the answers would be '13' and '26'. </p>
<p>My code so far is: </p>
<pre><code> x = int(raw_input('Enter your Number Here: '))
def divide(x):
cond = True
while cond:
x % 13 == 0
print x
else:
cond = False
print 'Your number us not divisble by 13'
divide(x)
</code></pre>
| 0 | 2016-10-19T18:36:31Z | 40,139,422 | <p>I'd just show all multiples of 13 until x, dropping 0:</p>
<pre><code>def divide(x):
print range(0, x, 13)[1:]
</code></pre>
<p>Demo:</p>
<pre><code>>>> divide(27)
[13, 26]
</code></pre>
| 0 | 2016-10-19T18:55:15Z | [
"python",
"python-2.7",
"python-3.x"
] |
insert element in the start of the numpy array | 40,139,167 | <p>I have array </p>
<pre><code>x=[ 0.30153836 0.30376881 0.29115761 0.29074261 0.28676876 ]
</code></pre>
<p>I want to insert -1 to the start of the array to be like </p>
<pre><code> x= [-1 0.30153836 0.30376881 0.29115761 0.29074261 0.28676876]
</code></pre>
<p>I tried :</p>
<pre><code>np.insert(x,0,-1,axis=0)
</code></pre>
<p>but it didn't do any change, any idea how to do that ?</p>
| 0 | 2016-10-19T18:37:42Z | 40,139,221 | <p>You can do the insert by ommiting the axis param:</p>
<pre><code>x = np.array([0,0,0,0])
x = np.insert(x, 0, -1)
x
</code></pre>
<p>That will give:</p>
<pre><code>array([-1, 0, 0, 0, 0])
</code></pre>
| 2 | 2016-10-19T18:42:09Z | [
"python",
"arrays",
"numpy"
] |
insert element in the start of the numpy array | 40,139,167 | <p>I have array </p>
<pre><code>x=[ 0.30153836 0.30376881 0.29115761 0.29074261 0.28676876 ]
</code></pre>
<p>I want to insert -1 to the start of the array to be like </p>
<pre><code> x= [-1 0.30153836 0.30376881 0.29115761 0.29074261 0.28676876]
</code></pre>
<p>I tried :</p>
<pre><code>np.insert(x,0,-1,axis=0)
</code></pre>
<p>but it didn't do any change, any idea how to do that ?</p>
| 0 | 2016-10-19T18:37:42Z | 40,139,294 | <p>I'm not fully familiar with numpy, but it seems that the insert function does not affect the array you pass to it, but rather it returns a new array with the inserted value(s). You'll have to reassign to x if you really want x to change. </p>
<pre><code>>>> x= [-1, 0.30153836, 0.30376881, 0.29115761, 0.29074261, 0.28676876]
>>> np.insert(x,0,-1,axis=0)
array([-1. , -1. , 0.30153836, 0.30376881, 0.29115761,
0.29074261, 0.28676876])
>>> x
[-1, 0.30153836, 0.30376881, 0.29115761, 0.29074261, 0.28676876]
>>> x = np.insert(x,0,-1,axis=0)
>>> x
array([-1. , -1. , 0.30153836, 0.30376881, 0.29115761,
0.29074261, 0.28676876])
</code></pre>
| 2 | 2016-10-19T18:47:07Z | [
"python",
"arrays",
"numpy"
] |
insert element in the start of the numpy array | 40,139,167 | <p>I have array </p>
<pre><code>x=[ 0.30153836 0.30376881 0.29115761 0.29074261 0.28676876 ]
</code></pre>
<p>I want to insert -1 to the start of the array to be like </p>
<pre><code> x= [-1 0.30153836 0.30376881 0.29115761 0.29074261 0.28676876]
</code></pre>
<p>I tried :</p>
<pre><code>np.insert(x,0,-1,axis=0)
</code></pre>
<p>but it didn't do any change, any idea how to do that ?</p>
| 0 | 2016-10-19T18:37:42Z | 40,139,686 | <p>From the <code>np.insert</code> documentation:</p>
<pre><code>Returns
out : ndarray
A copy of `arr` with `values` inserted. Note that `insert`
does not occur in-place: a new array is returned.
</code></pre>
<p>You can do the same with <code>concatenate</code>, joining the new value to the main value. <code>hstack</code>, <code>append</code> etc use <code>concatenate</code>; insert is more general, allowing insertion in the middle (for any axis), so it does its own indexing and new array creation.</p>
<p>In any case, the key point is that it does not operate in-place. You can't change the size of an array.</p>
<pre><code>In [788]: x= np.array([0.30153836, 0.30376881, 0.29115761, 0.29074261, 0.28
...: 676876])
In [789]: y=np.insert(x,0,-1,axis=0)
In [790]: y
Out[790]:
array([-1. , 0.30153836, 0.30376881, 0.29115761, 0.29074261,
0.28676876])
In [791]: x
Out[791]: array([ 0.30153836, 0.30376881, 0.29115761, 0.29074261, 0.28676876])
</code></pre>
<p>Same action with concatenate; note that I had to add <code>[]</code>, short for <code>np.array([-1])</code>, so both inputs are 1d arrays. Expanding the scalar to array is all that <code>insert</code> is doing special.</p>
<pre><code>In [793]: np.concatenate([[-1],x])
Out[793]:
array([-1. , 0.30153836, 0.30376881, 0.29115761, 0.29074261,
0.28676876])
</code></pre>
| 0 | 2016-10-19T19:11:41Z | [
"python",
"arrays",
"numpy"
] |
Keeping 'key' column when using groupby with transform in pandas | 40,139,184 | <p>Finding a normalized dataframe removes the column being used to group by, so that it can't be used in subsequent groupby operations. for example (edit: updated):</p>
<pre><code> df = pd.DataFrame({'a':[1, 1 , 2, 3, 2, 3], 'b':[0, 1, 2, 3, 4, 5]})
a b
0 1 0
1 1 1
2 2 2
3 3 3
4 2 4
5 3 5
df.groupby('a').transform(lambda x: x)
b
0 0
1 1
2 2
3 3
4 4
5 5
</code></pre>
<p>Now, with most operations on groups the 'missing' column becomes a new index (which can then be adjusted using <code>reset_index</code>, or set <code>as_index=False</code>), but when using transform it just disappears, leaving the original index and a new dataset without the key. </p>
<p>Edit: here's a one liner of what I would like to be able to do</p>
<pre><code> df.groupby('a').transform(lambda x: x+1).groupby('a').mean()
KeyError 'a'
</code></pre>
<p>In the example from the <a href="http://pandas.pydata.org/pandas-docs/stable/groupby.html" rel="nofollow">pandas docs</a> a function is used to split based on the index, which appears to avoid this issue entirely. Alternatively, it would always be possible just to add the column after the groupby/transform, but surely there's a better way?</p>
<p>Update:
It looks like reset_index/as_index are intended only for functions that reduce each group to a single row. There seem to be a couple options, from answers</p>
| 2 | 2016-10-19T18:39:08Z | 40,139,517 | <p>that is bizzare!</p>
<p>I tricked it like this</p>
<pre><code>df.groupby(df.a.values).transform(lambda x: x)
</code></pre>
<p><a href="https://i.stack.imgur.com/XcYxq.png" rel="nofollow"><img src="https://i.stack.imgur.com/XcYxq.png" alt="enter image description here"></a></p>
| 2 | 2016-10-19T19:01:01Z | [
"python",
"pandas"
] |
Is it possible to pass a single user input (an int) into an argument to match 2 ints in python? | 40,139,187 | <p>Basically I'm trying to write a tic tac toe game in python and I'm new to the language. At the moment I'm trying to get the user to input an int which I will then pass into an argument which requires two ints of the same number (as the grid will be a square), to make a grid for the game. If you look in the code below I have hard coded in the arguments (grid_maker(6,6)), but is there a way I can assign the user input into h and w so the grid will be the size the user requests? (The user can input any number they wish e.g. 20, and make a 20 by 20 grid, but they still only need 3 in a row, the code is more for the practice rather than an efficient game).</p>
<p>On a side note would this way be recommended as I will need to check if someone has gotten 3 Xs or Os in a row.</p>
<pre><code>class GameBoard:
def printBoard():
print('Welcome to my tic tac toe game')
("Commented gridInput out as it results in an error ")
#gridInput = int(input('Please enter a number between 5-10 to set the grid dimensions for the game board\n'))
def grid_maker(h,w):
grid = [[" | " for _ in range(w)] for _ in range(h)]
return grid
print ('\n'.join(' '.join(row) for row in grid_maker(6,6)))
def print_grid(grid):
for row in grid:
for e in row:
print (e)
</code></pre>
| 0 | 2016-10-19T18:39:14Z | 40,139,243 | <p>I am not sure what exactly you want to do, but I guess there are multiple solutions to it. I will just give one possible solution:</p>
<pre><code>def grid_maker(h,w=None):
if w is None: w=h
grid = [[" | " for _ in range(w)] for _ in range(h)]
return grid
</code></pre>
| 0 | 2016-10-19T18:43:40Z | [
"python",
"python-3.x",
"multidimensional-array",
"grid",
"arguments"
] |
Reformat JSON file? | 40,139,200 | <p>I have two JSON files.</p>
<p>File A:</p>
<pre><code> "features": [
{
"attributes": {
"NAME": "R T CO",
"LTYPE": 64,
"QUAD15M": "279933",
"OBJECTID": 225,
"SHAPE.LEN": 828.21510830520401
},
"geometry": {
"paths": [
[
[
-99.818614674337155,
27.782542677671653
],
[
-99.816056346719051,
27.782590806976135
]
]
]
}
}
</code></pre>
<p>File B:</p>
<pre><code> "features": [
{
"geometry": {
"type": "MultiLineString",
"coordinates": [
[
[
-99.773315512624,
27.808875128096
],
[
-99.771397939251,
27.809512259374
]
]
]
},
"type": "Feature",
"properties": {
"LTYPE": 64,
"SHAPE.LEN": 662.3800009247,
"NAME": "1586",
"OBJECTID": 204,
"QUAD15M": "279933"
}
},
</code></pre>
<p>I would like File B to be reformatted to look like File A.
Change "properties" to "attributes", "coordinates" to "paths", and remove both "type": "MultiLineString" and "type": "Feature". What is the best way to do this via python?</p>
<p>Is there a way to also reorder the "attributes" key value pairs to look like File A? </p>
<p>It's a rather large dataset and I would like to iterate through the entire file.</p>
| 1 | 2016-10-19T18:40:13Z | 40,139,235 | <p>What about:</p>
<pre><code>cat <file> | python -m json.tool
</code></pre>
<p>This will reformat the contents of the file into a uniform human readable format. If you really need to change the names of the fields you could use sed.</p>
<pre><code>cat <file> | sed -e 's/"properties"/"attributes"/'
</code></pre>
<p>This may be sufficient for your use case. If you have something that requires more nuanced parsing, you'll have to read up on how to manage the JSON through an ORM library.</p>
| -2 | 2016-10-19T18:43:14Z | [
"python",
"json",
"reformatting"
] |
Reformat JSON file? | 40,139,200 | <p>I have two JSON files.</p>
<p>File A:</p>
<pre><code> "features": [
{
"attributes": {
"NAME": "R T CO",
"LTYPE": 64,
"QUAD15M": "279933",
"OBJECTID": 225,
"SHAPE.LEN": 828.21510830520401
},
"geometry": {
"paths": [
[
[
-99.818614674337155,
27.782542677671653
],
[
-99.816056346719051,
27.782590806976135
]
]
]
}
}
</code></pre>
<p>File B:</p>
<pre><code> "features": [
{
"geometry": {
"type": "MultiLineString",
"coordinates": [
[
[
-99.773315512624,
27.808875128096
],
[
-99.771397939251,
27.809512259374
]
]
]
},
"type": "Feature",
"properties": {
"LTYPE": 64,
"SHAPE.LEN": 662.3800009247,
"NAME": "1586",
"OBJECTID": 204,
"QUAD15M": "279933"
}
},
</code></pre>
<p>I would like File B to be reformatted to look like File A.
Change "properties" to "attributes", "coordinates" to "paths", and remove both "type": "MultiLineString" and "type": "Feature". What is the best way to do this via python?</p>
<p>Is there a way to also reorder the "attributes" key value pairs to look like File A? </p>
<p>It's a rather large dataset and I would like to iterate through the entire file.</p>
| 1 | 2016-10-19T18:40:13Z | 40,139,464 | <p>Manipulating JSON in Python is a good candidate for the <a href="https://en.wikipedia.org/wiki/IPO_model" rel="nofollow">input-process-output model</a> of programming.</p>
<p>For input, you convert the external JSON file into a Python data structure, using <a href="https://docs.python.org/2/library/json.html#json.load" rel="nofollow"><code>json.load()</code></a>.</p>
<p>For output, you convert the Python data structure into an external JSON file using <a href="https://docs.python.org/2/library/json.html#json.dump" rel="nofollow"><code>json.dump()</code></a>.</p>
<p>For the processing or conversion step, do whatever it is that you need to do, using ordinary Python <code>dict</code> and <code>list</code> methods.</p>
<p>This program might do what you want:</p>
<pre><code>import json
with open("b.json") as b:
b = json.load(b)
for feature in b["features"]:
feature["attributes"] = feature["properties"]
del feature["properties"]
feature["geometry"]["paths"] = feature["geometry"]["coordinates"]
del feature["geometry"]["coordinates"]
del feature["geometry"]["type"]
del feature["type"]
with open("new-b.json", "w") as new_b:
json.dump(b, new_b, indent=1, separators=(',', ': '))
</code></pre>
| 4 | 2016-10-19T18:58:03Z | [
"python",
"json",
"reformatting"
] |
python/pandas/sklearn: getting closest matches from pairwise_distances | 40,139,216 | <p>I have a dataframe and am trying to get the closest matches using mahalanobis distance across three categories, like:</p>
<pre><code>from io import StringIO
from sklearn import metrics
import pandas as pd
stringdata = StringIO(u"""pid,ratio1,pct1,rsp
0,2.9,26.7,95.073615
1,11.6,29.6,96.963660
2,0.7,37.9,97.750412
3,2.7,27.9,102.750412
4,1.2,19.9,93.750412
5,0.2,22.1,96.750412
""")
stats = ['ratio1','pct1','rsp']
df = pd.read_csv(stringdata)
d = metrics.pairwise.pairwise_distances(df[stats].as_matrix(),
metric='mahalanobis')
print(df)
print(d)
</code></pre>
<p>Where that <code>pid</code> column is a unique identifier.</p>
<p>What I need to do is take that <code>ndarray</code> returned by the <code>pairwise_distances</code> call and update the original dataframe so each row has some kind of list of its closest N matches (so <code>pid</code> 0 might have an ordered list by distance of like 2, 1, 5, 3, 4 (or whatever it actually is), but I'm totally stumped how this is done in python.</p>
| 0 | 2016-10-19T18:41:36Z | 40,139,643 | <pre><code>from io import StringIO
from sklearn import metrics
stringdata = StringIO(u"""pid,ratio1,pct1,rsp
0,2.9,26.7,95.073615
1,11.6,29.6,96.963660
2,0.7,37.9,97.750412
3,2.7,27.9,102.750412
4,1.2,19.9,93.750412
5,0.2,22.1,96.750412
""")
stats = ['ratio1','pct1','rsp']
df = pd.read_csv(stringdata)
dist = metrics.pairwise.pairwise_distances(df[stats].as_matrix(),
metric='mahalanobis')
dist = pd.DataFrame(dist)
ranks = np.argsort(dist, axis=1)
df["rankcol"] = ranks.apply(lambda row: ','.join(map(str, row)), axis=1)
df
</code></pre>
| 1 | 2016-10-19T19:09:23Z | [
"python",
"pandas",
"scikit-learn"
] |
iteration counter for GCD | 40,139,296 | <p>I have the following code for calulating the GCD of two numbers:</p>
<pre><code>def gcd(m, n):
r = m % n
while r != 0:
m = n
n = r
r = m % n
return n
print ("\n", "gcd (10, 35) = ", gcd(10, 35))
print ("\n", "gcd (735, 175) = ", gcd(735, 175))
print ("\n", "gcd (735, 350) = ", gcd(735, 350))
</code></pre>
<p>I would like to count the number of iterations that the algorithm has to go through before finding the GCD. I am having trouble making a for loop to determine the number of iterations.</p>
| 0 | 2016-10-19T18:47:11Z | 40,139,335 | <pre><code>def gcd(m, n):
r = m % n
counter = 0
while r != 0:
m = n
n = r
r = m % n
counter += 1
return n, counter
</code></pre>
| 3 | 2016-10-19T18:49:34Z | [
"python",
"iteration"
] |
How to create a web crawler to get multiple pages from agoda,with python3 | 40,139,323 | <p>I'm new to here. Recently, I want to get data from Agoda,and I got a problem that agoda.com don't provide the url(or href) of "next page". So I have no idea to change page. Now, I only get the data from page 1, but I need the data from page2, page3...
Is anyone help me. I need some advise, tools or others. By the way, I use python3 and win10.Please help me and thank you.
Below is my code presently.</p>
<pre><code>import requests
import pandas as pd
import csv
from bs4 import BeautifulSoup
from pandas import Series,DataFrame
import unicodecsv
def name1():
url="https://www.agoda.com/zh-tw/pages/agoda/default/DestinationSearchResult.aspx?asq=%2bZePx52sg5H8gZw3pGCybdmU7lFjoXS%2baxz%2bUoF4%2bbAw3oLIKgWQqUpZ91GacaGdIGlJ%2bfxiotUg7cHef4W8WIrREFyK%2bHWl%2ftRKlV7J5kUcPb7NK6DnLacMaVs1qlGagsx8liTdosF5by%2fmvF3ZvJvZqOWnEqFCm0staf3OvDRiEYy%2bVBJyLXucnzzqZp%2fcBP3%2bKCFNOTA%2br9ARInL665pxj%2fA%2bylTfAGs1qJCjm9nxgYafyEWBFMPjt2sg351B&city=18343&cid=1732641&tag=41460a09-3e65-d173-1233-629e2428d88e&gclid=Cj0KEQjwvve_BRDmg9Kt9ufO15EBEiQAKoc6qlyYthgdt9CgZ7a6g6yijP42n6DsCUSZXvtfEJdYqiAaAvdW8P8HAQ&tick=636119092231&isdym=true&searchterm=%E5%A2%BE%E4%B8%81&pagetypeid=1&origin=TW&cid=1732641&htmlLanguage=zh-tw&checkIn=2016-10-20&checkOut=2016-10-21&los=1&rooms=1&adults=2&children=0&isFromSearchBox=true&ckuid=1b070b17-86c2-4376-a4f5-d3b98fc9cf45"
source_code=requests.get(url)
plain_text=source_code.text
soup=BeautifulSoup(plain_text,"lxml")
hotelname=soup.find_all("h3",{"class":"hotel-name"})
f = csv.writer(open("test.csv", "w",newline=''))
f.writerow(["hotelname","address"])
p = []
for N in hotelname:
a=N.string.strip()
f.writerow([a])
</code></pre>
| 0 | 2016-10-19T18:48:58Z | 40,141,606 | <p>Examine closely in browser development tools what happens when you click next button. </p>
<p>It has click event that sends xhr post request with a lot of parameters. One of the parameters is <code>PageNumber</code>. Most values for the parameters are straightforward to get, maybe except <code>SearchMessageID</code> that you have to find somewhere on page or is generated by javascript. </p>
| 0 | 2016-10-19T21:11:37Z | [
"python",
"scrapy",
"web-crawler",
"webpage"
] |
Python Arguments and Passing Floats in Arguments | 40,139,445 | <p>I've run into a couple of issues using arguments within a python script. Can i please get some help or direction to get this code functional? Thank you in advance.</p>
<p>First issue: I am unable to specify multiple arguments at once.
For example I am able to pass a single argument fine:</p>
<pre><code>$ ./my_arg_scenario.py -a
Argument_A
$ ./my_arg_scenario.py -c
Argument_C
$ ./my_arg_scenario.py -d
Argument_D
</code></pre>
<p>However, I am looking for a way to pass multiple arguments in any position. Is there a way I can accomplish this?
For example, I would like the below to occur:</p>
<pre><code>./my_arg_scenario.py -a -c -d
Argument_A
Argument_C
Argument_D
# OR
./my_arg_scenario.py -c -a
Argument_C
Argument_A
</code></pre>
<p>Second Issue: I am trying to pass both whole numbers and floats in the -b argument. But when I pass a float/decimal I get the below error. Is there a way I can pass both a float and whole number?</p>
<p>This works:</p>
<pre><code>$ ./my_arg_scenario.py -b 5
The number provided is: 5
</code></pre>
<p>But this does NOT:</p>
<pre><code>$ ./my_arg_scenario.py -b 5.50
Traceback (most recent call last):
File "./my_arg_scenario.py", line 18, in <module>
if int(sys.argv[2]) not in range(0,11):
ValueError: invalid literal for int() with base 10: '5.50'
</code></pre>
<p>Below is my testable code:</p>
<pre><code>#!/usr/local/bin/python3.5
import sys
script_options = ['-a', '-b', '-c', '-d']
manual_flag = ''
build_flag = ''
if len(sys.argv) > 1:
if sys.argv[1] in script_options:
pass
else:
print('\n\t\tParameter "' + sys.argv[1] + '" is an invalid argument.\n')
sys.exit()
if sys.argv[1] == '-a':
print('Argument_A')
sys.exit()
elif sys.argv[1] == '-b':
if int(sys.argv[2]) not in range(0,11):
print('Invalid interval. Please select a value bewteen 1-5s.')
sys.exit()
else:
print('The number provided is: ' + (sys.argv[2]))
elif sys.argv[1] == '-c':
manual_flag = 'Argument_C'
print(manual_flag)
elif sys.argv[1] == '-d':
build_flag ='Argument_D'
print(build_flag)
else:
pass
</code></pre>
| 1 | 2016-10-19T18:56:51Z | 40,139,491 | <p><s>You didn't actually provide the code you're using (aside from incidentally in the traceback),</s>(<strong>Update:</strong> Code added later) but the answer is: Stop messing around with parsing <code>sys.argv</code> manually and use <a href="https://docs.python.org/3/library/argparse.html" rel="nofollow">the <code>argparse</code> module</a> (or <code>docopt</code> or something that doesn't involve rolling your own switch parsing).</p>
<pre><code>import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-a', action='store_true')
parser.add_argument('-b', metavar='INTERVAL', type=int, choices=range(11))
parser.add_argument('-c', action='store_true')
parser.add_argument('-d', action='store_true')
args = parser.parse_args()
if args.a: print('Argument_A')
if args.b is not None: print('The number provided is:', args.b)
if args.c: print('Argument_C')
if args.d: print('Argument_D')
</code></pre>
<p>If you want to accept <code>int</code> or <code>float</code>, the easiest solution is to just make <code>type=float</code> and use a consistent type (but the <code>range</code> check must be done outside the parsing step). If you must allow both, <code>ast.literal_eval</code> or a homegrown <code>argparse</code> type conversion function are options. Since you want a range check too (which <code>range</code> won't handle properly for <code>float</code> values that aren't equal to <code>int</code> values), roll a type checker:</p>
<pre><code>def int_or_float(minval=None, maxval=None):
def checker(val):
try:
val = int(val)
except ValueError:
val = float(val)
if minval is not None and val < minval:
raise argparse.ArgumentTypeError('%r must be >= %r' % (val, minval))
if maxval is not None and val > maxval:
raise argparse.ArgumentTypeError('%r must be <= %r' % (val, maxval))
return val
return checker
</code></pre>
<p>Then use it by replacing the definition for <code>-b</code> with:</p>
<pre><code># Might want int_or_float(0, 10) depending on range exclusivity rules
parser.add_argument('-b', metavar='INTERVAL', type=int_or_float(0, 11))
</code></pre>
| 3 | 2016-10-19T18:59:19Z | [
"python",
"python-3.x",
"int",
"argv"
] |
Django templates: why does __call__ magic method breaks the rendering of a non-model object? | 40,139,493 | <p>Today I faced a strange issue on one of my development. I reproduced it with a very minimal example. Have a look at these 2 dummy classes (non Django model subclasses):</p>
<pre><code>class DummyClassA(object):
def __init__(self, name):
self.name = name
def __repr__(self):
return 'Dummy1 object called ' + self.name
class DummyClassB(object):
"""Same as ClassA, with the __call__ method added"""
def __init__(self, name):
self.name = name
def __repr__(self):
return 'Dummy2 object called ' + self.name
def __call__(self, *args, **kwargs):
return "bar"
</code></pre>
<p>They are identical, but the second have a special <code>__call__()</code> method.</p>
<p>I want to display instances of these 2 objects in a view using the builtin Django template engine:</p>
<pre><code>class MyView(TemplateView):
template_name = 'myapp/home.html'
def get_context_data(self, **kwargs):
ctx = super(MyView, self).get_context_data(**kwargs)
list1 = [
DummyClassA(name="John"),
DummyClassA(name="Jack"),
]
list2 = [
DummyClassB(name="Albert"),
DummyClassB(name="Elmer"),
]
ctx.update({
'list1': list1,
'list2': list2,
})
return ctx
</code></pre>
<p>and the corresponding template:</p>
<pre><code> <h1>Objects repr</h1>
<ul>
{% for element in list1 %}
<li>{{ element }}</li>
{% endfor %}
</ul>
<ul>
{% for element in list2 %}
<li>{{ element }}</li>
{% endfor %}
</ul>
<h1>Access members</h1>
<ul>
{% for element in list1 %}
<li>{{ element.name }}</li>
{% endfor %}
</ul>
<ul>
{% for element in list2 %}
<li>{{ element.name }}</li>
{% endfor %}
</ul>
</code></pre>
<p>I obtain this result:</p>
<p><a href="https://i.stack.imgur.com/kL9lZ.png" rel="nofollow"><img src="https://i.stack.imgur.com/kL9lZ.png" alt="html result"></a></p>
<p>When displaying instances of the second class (<code>{{ element }}</code>), the <code>__call__</code> method is executed instead of <code>__repr__()</code>, and when I want to access a member of the class, it returns nothing. </p>
<p>I don't understand why defining the <code>__call__()</code> change the way Django template engine will handle those instances. I imagine this is not a bug but mostly a feature, but I am curious, why <code>__call__()</code> is run in such case. And why I can't get the value of <code>element.name</code> in the 2nd list ?</p>
| 0 | 2016-10-19T18:59:23Z | 40,139,679 | <p>Because that's what the template language is designed to do. As <a href="https://docs.djangoproject.com/en/1.10/ref/templates/language/#variables" rel="nofollow">the docs state</a>:</p>
<blockquote>
<p>If the resulting value [of looking up a variable] is callable, it is called with no arguments. The result of the call becomes the template value.</p>
</blockquote>
<p>Without this, there would be no way of calling methods in templates, since the template syntax does not allow using parentheses.</p>
| 1 | 2016-10-19T19:11:16Z | [
"python",
"django",
"templates",
"magic-methods"
] |
Import error installing tlslite | 40,139,501 | <p>I'm trying to install tlslite. After installed the module I've tried to test it and I receive this error: </p>
<pre><code>from .checker import Checker
ImportError: No module named checker
</code></pre>
<p>I've checked on my pip module list and checker is installed...
Any idea?
Thanks!</p>
| 0 | 2016-10-19T18:59:53Z | 40,139,728 | <p>Assuming you installed tlslite correctly, try this:</p>
<pre><code>>>> from tlslite.checker import Checker
</code></pre>
<p>If that doesn't work, check that tlslite is in your site packages</p>
| 0 | 2016-10-19T19:14:06Z | [
"python"
] |
Import error installing tlslite | 40,139,501 | <p>I'm trying to install tlslite. After installed the module I've tried to test it and I receive this error: </p>
<pre><code>from .checker import Checker
ImportError: No module named checker
</code></pre>
<p>I've checked on my pip module list and checker is installed...
Any idea?
Thanks!</p>
| 0 | 2016-10-19T18:59:53Z | 40,139,824 | <p>To work with <a href="https://pypi.python.org/pypi/tlslite/0.4.6" rel="nofollow">tlslite</a> I recommend to use a virtualenv and install TlsLite inside:</p>
<pre><code>cd ~/virtualenv/ # <- all my virtualenv are here
virtualenv myvenv
source ~/virtualenv/myvenv/bin/activate
pip install -q -U pip setuptools # ensure last version
pip install tlslite
</code></pre>
<p>With that in hand, you can use the <code>Checker</code>:</p>
<pre><code>$ python
>>> from tlslite.checker import Checker
>>>
</code></pre>
<p>Et voilà  !</p>
| 0 | 2016-10-19T19:19:18Z | [
"python"
] |
Scrape Yahoo Finance Financial Ratios | 40,139,537 | <p>I have been trying to scrap the value of the Current Ratio (as shown below) from Yahoo Finance using Beautiful Soup, but it keeps returning an empty value.</p>
<p><a href="https://i.stack.imgur.com/SKunN.jpg" rel="nofollow"><img src="https://i.stack.imgur.com/SKunN.jpg" alt="enter image description here"></a></p>
<p>Interestingly, when I look at the Page Source of the URL, the value of the Current Ratio is not listed there.</p>
<p>My code so far is:</p>
<pre><code>import urllib
from bs4 import BeautifulSoup
url = ("http://finance.yahoo.com/quote/GSB/key-statistics?p=GSB")
html = urllib.urlopen(url).read()
soup = BeautifulSoup(html, "html.parser")
script = soup.find("td", {"class": "Fz(s) Fw(500) Ta(end)",
"data-reactid": ".1ujetg16lcg.0.$0.0.0.3.1.$main-0-Quote-Proxy.$main-0-Quote.2.0.0.0.1.0.1:$FINANCIAL_HIGHLIGHTS.$BALANCE_SHEET.1.0.$CURRENT_RATIO.1"
})
</code></pre>
<p>Does anyone know how to solve this?</p>
| 1 | 2016-10-19T19:02:15Z | 40,140,199 | <p>You can actually get the data is json format, there is a call to an api that returns a lot of the data including the current ratio:</p>
<p><a href="https://i.stack.imgur.com/Zu7sP.png" rel="nofollow"><img src="https://i.stack.imgur.com/Zu7sP.png" alt="enter image description here"></a></p>
<pre><code>import requests
params = {"formatted": "true",
"crumb": "AKV/cl0TOgz", # works without so not sure of significance
"lang": "en-US",
"region": "US",
"modules": "defaultKeyStatistics,financialData,calendarEvents",
"corsDomain": "finance.yahoo.com"}
r = requests.get("https://query1.finance.yahoo.com/v10/finance/quoteSummary/GSB", params=params)
data = r.json()[u'quoteSummary']["result"][0]
</code></pre>
<p>That gives you a dict with numerous pieces of data:</p>
<pre><code>from pprint import pprint as pp
pp(data)
{u'calendarEvents': {u'dividendDate': {u'fmt': u'2016-09-08',
u'raw': 1473292800},
u'earnings': {u'earningsAverage': {},
u'earningsDate': [{u'fmt': u'2016-10-27',
u'raw': 1477526400}],
u'earningsHigh': {},
u'earningsLow': {},
u'revenueAverage': {u'fmt': u'8.72M',
u'longFmt': u'8,720,000',
u'raw': 8720000},
u'revenueHigh': {u'fmt': u'8.72M',
u'longFmt': u'8,720,000',
u'raw': 8720000},
u'revenueLow': {u'fmt': u'8.72M',
u'longFmt': u'8,720,000',
u'raw': 8720000}},
u'exDividendDate': {u'fmt': u'2016-05-19',
u'raw': 1463616000},
u'maxAge': 1},
u'defaultKeyStatistics': {u'52WeekChange': {u'fmt': u'3.35%',
u'raw': 0.033536673},
u'SandP52WeekChange': {u'fmt': u'5.21%',
u'raw': 0.052093267},
u'annualHoldingsTurnover': {},
u'annualReportExpenseRatio': {},
u'beta': {u'fmt': u'0.23', u'raw': 0.234153},
u'beta3Year': {},
u'bookValue': {u'fmt': u'1.29', u'raw': 1.295},
u'category': None,
u'earningsQuarterlyGrowth': {u'fmt': u'-28.00%',
u'raw': -0.28},
u'enterpriseToEbitda': {u'fmt': u'9.22',
u'raw': 9.215},
u'enterpriseToRevenue': {u'fmt': u'1.60',
u'raw': 1.596},
u'enterpriseValue': {u'fmt': u'50.69M',
u'longFmt': u'50,690,408',
u'raw': 50690408},
u'fiveYearAverageReturn': {},
u'floatShares': {u'fmt': u'11.63M',
u'longFmt': u'11,628,487',
u'raw': 11628487},
u'forwardEps': {u'fmt': u'0.29', u'raw': 0.29},
u'forwardPE': {},
u'fundFamily': None,
u'fundInceptionDate': {},
u'heldPercentInsiders': {u'fmt': u'36.12%',
u'raw': 0.36116},
u'heldPercentInstitutions': {u'fmt': u'21.70%',
u'raw': 0.21700001},
u'lastCapGain': {},
u'lastDividendValue': {},
u'lastFiscalYearEnd': {u'fmt': u'2015-12-31',
u'raw': 1451520000},
u'lastSplitDate': {},
u'lastSplitFactor': None,
u'legalType': None,
u'maxAge': 1,
u'morningStarOverallRating': {},
u'morningStarRiskRating': {},
u'mostRecentQuarter': {u'fmt': u'2016-06-30',
u'raw': 1467244800},
u'netIncomeToCommon': {u'fmt': u'3.82M',
u'longFmt': u'3,819,000',
u'raw': 3819000},
u'nextFiscalYearEnd': {u'fmt': u'2017-12-31',
u'raw': 1514678400},
u'pegRatio': {},
u'priceToBook': {u'fmt': u'2.64',
u'raw': 2.6358302},
u'priceToSalesTrailing12Months': {},
u'profitMargins': {u'fmt': u'12.02%',
u'raw': 0.12023},
u'revenueQuarterlyGrowth': {},
u'sharesOutstanding': {u'fmt': u'21.18M',
u'longFmt': u'21,184,300',
u'raw': 21184300},
u'sharesShort': {u'fmt': u'27.06k',
u'longFmt': u'27,057',
u'raw': 27057},
u'sharesShortPriorMonth': {u'fmt': u'36.35k',
u'longFmt': u'36,352',
u'raw': 36352},
u'shortPercentOfFloat': {u'fmt': u'0.20%',
u'raw': 0.001977},
u'shortRatio': {u'fmt': u'0.81', u'raw': 0.81},
u'threeYearAverageReturn': {},
u'totalAssets': {},
u'trailingEps': {u'fmt': u'0.18', u'raw': 0.18},
u'yield': {},
u'ytdReturn': {}},
u'financialData': {u'currentPrice': {u'fmt': u'3.41', u'raw': 3.4134},
u'currentRatio': {u'fmt': u'1.97', u'raw': 1.974},
u'debtToEquity': {},
u'earningsGrowth': {u'fmt': u'-33.30%', u'raw': -0.333},
u'ebitda': {u'fmt': u'5.5M',
u'longFmt': u'5,501,000',
u'raw': 5501000},
u'ebitdaMargins': {u'fmt': u'17.32%',
u'raw': 0.17318001},
u'freeCashflow': {u'fmt': u'4.06M',
u'longFmt': u'4,062,250',
u'raw': 4062250},
u'grossMargins': {u'fmt': u'79.29%', u'raw': 0.79288},
u'grossProfits': {u'fmt': u'25.17M',
u'longFmt': u'25,172,000',
u'raw': 25172000},
u'maxAge': 86400,
u'numberOfAnalystOpinions': {},
u'operatingCashflow': {u'fmt': u'6.85M',
u'longFmt': u'6,853,000',
u'raw': 6853000},
u'operatingMargins': {u'fmt': u'16.47%',
u'raw': 0.16465001},
u'profitMargins': {u'fmt': u'12.02%', u'raw': 0.12023},
u'quickRatio': {u'fmt': u'1.92', u'raw': 1.917},
u'recommendationKey': u'strong_buy',
u'recommendationMean': {u'fmt': u'1.00', u'raw': 1.0},
u'returnOnAssets': {u'fmt': u'7.79%', u'raw': 0.07793},
u'returnOnEquity': {u'fmt': u'15.05%', u'raw': 0.15054},
u'revenueGrowth': {u'fmt': u'5.00%', u'raw': 0.05},
u'revenuePerShare': {u'fmt': u'1.51', u'raw': 1.513},
u'targetHighPrice': {},
u'targetLowPrice': {},
u'targetMeanPrice': {},
u'targetMedianPrice': {},
u'totalCash': {u'fmt': u'20.28M',
u'longFmt': u'20,277,000',
u'raw': 20277000},
u'totalCashPerShare': {u'fmt': u'0.96', u'raw': 0.957},
u'totalDebt': {u'fmt': None,
u'longFmt': u'0',
u'raw': 0},
u'totalRevenue': {u'fmt': u'31.76M',
u'longFmt': u'31,764,000',
u'raw': 31764000}}}
</code></pre>
<p>What you want is in <code>data[u'financialData']</code>:</p>
<pre><code> pp(data[u'financialData'])
{u'currentPrice': {u'fmt': u'3.41', u'raw': 3.4134},
u'currentRatio': {u'fmt': u'1.97', u'raw': 1.974},
u'debtToEquity': {},
u'earningsGrowth': {u'fmt': u'-33.30%', u'raw': -0.333},
u'ebitda': {u'fmt': u'5.5M', u'longFmt': u'5,501,000', u'raw': 5501000},
u'ebitdaMargins': {u'fmt': u'17.32%', u'raw': 0.17318001},
u'freeCashflow': {u'fmt': u'4.06M',
u'longFmt': u'4,062,250',
u'raw': 4062250},
u'grossMargins': {u'fmt': u'79.29%', u'raw': 0.79288},
u'grossProfits': {u'fmt': u'25.17M',
u'longFmt': u'25,172,000',
u'raw': 25172000},
u'maxAge': 86400,
u'numberOfAnalystOpinions': {},
u'operatingCashflow': {u'fmt': u'6.85M',
u'longFmt': u'6,853,000',
u'raw': 6853000},
u'operatingMargins': {u'fmt': u'16.47%', u'raw': 0.16465001},
u'profitMargins': {u'fmt': u'12.02%', u'raw': 0.12023},
u'quickRatio': {u'fmt': u'1.92', u'raw': 1.917},
u'recommendationKey': u'strong_buy',
u'recommendationMean': {u'fmt': u'1.00', u'raw': 1.0},
u'returnOnAssets': {u'fmt': u'7.79%', u'raw': 0.07793},
u'returnOnEquity': {u'fmt': u'15.05%', u'raw': 0.15054},
u'revenueGrowth': {u'fmt': u'5.00%', u'raw': 0.05},
u'revenuePerShare': {u'fmt': u'1.51', u'raw': 1.513},
u'targetHighPrice': {},
u'targetLowPrice': {},
u'targetMeanPrice': {},
u'targetMedianPrice': {},
u'totalCash': {u'fmt': u'20.28M',
u'longFmt': u'20,277,000',
u'raw': 20277000},
u'totalCashPerShare': {u'fmt': u'0.96', u'raw': 0.957},
u'totalDebt': {u'fmt': None, u'longFmt': u'0', u'raw': 0},
u'totalRevenue': {u'fmt': u'31.76M',
u'longFmt': u'31,764,000',
u'raw': 31764000}}
</code></pre>
<p>You can see <code>u'currentRatio'</code> in there, the fmt is the formatted output you see on the site, formatted to two decimal places. So to get the 1.97:</p>
<pre><code>In [5]: import requests
...: data = {"formatted": "true",
...: "crumb": "AKV/cl0TOgz",
...: "lang": "en-US",
...: "region": "US",
...: "modules": "defaultKeyStatistics,financialData,calendarEvents",
...: "corsDomain": "finance.yahoo.com"}
...: r = requests.get("https://query1.finance.yahoo.com/v10/finance/quoteSumm
...: ary/GSB", params=data)
...: data = r.json()[u'quoteSummary']["result"][0][u'financialData']
...: ratio = data[u'currentRatio']
...: print(ratio)
...: print(ratio["fmt"])
...:
{'raw': 1.974, 'fmt': '1.97'}
1.97
</code></pre>
<p>The equivalent code using <em>urllib</em>:</p>
<pre><code>In [1]: import urllib
...: from urllib import urlencode
...: from json import load
...:
...:
...: data = {"formatted": "true",
...: "crumb": "AKV/cl0TOgz",
...: "lang": "en-US",
...: "region": "US",
...: "modules": "defaultKeyStatistics,financialData,calendarEvents",
...: "corsDomain": "finance.yahoo.com"}
...: url = "https://query1.finance.yahoo.com/v10/finance/quoteSummary/GSB"
...: r = urllib.urlopen(url, data=urlencode(data))
...: data = load(r)[u'quoteSummary']["result"][0][u'financialData']
...: ratio = data[u'currentRatio']
...: print(ratio)
...: print(ratio["fmt"])
...:
{u'raw': 1.974, u'fmt': u'1.97'}
1.97
</code></pre>
<p>It works fine for APPL also:</p>
<pre><code>In [1]: import urllib
...: from urllib import urlencode
...: from json import load
...: data = {"formatted": "true",
...: "lang": "en-US",
...: "region": "US",
...: "modules": "defaultKeyStatistics,financialData,calendarEvents",
...: "corsDomain": "finance.yahoo.com"}
...: url = "https://query1.finance.yahoo.com/v10/finance/quoteSummary/AAPL"
...: r = urllib.urlopen(url, data=urlencode(data))
...: data = load(r)[u'quoteSummary']["result"][0][u'financialData']
...: ratio = data[u'currentRatio']
...: print(ratio)
...: print(ratio["fmt"])
...:
{u'raw': 1.312, u'fmt': u'1.31'}
1.31
</code></pre>
<p>Adding the crumb parameters seems to have no effect, if you need to get it at a later date:</p>
<pre><code>soup = BeautifulSoup(urllib.urlopen("http://finance.yahoo.com/quote/GSB/key-statistics?p=GSB").read())
script = soup.find("script", text=re.compile("root.App.main")).text
data = loads(re.search("root.App.main\s+=\s+(\{.*\})", script).group(1))
print(data["context"]["dispatcher"]["stores"]["CrumbStore"]["crumb"])
</code></pre>
| 3 | 2016-10-19T19:41:41Z | [
"python",
"beautifulsoup"
] |
Scrape Yahoo Finance Financial Ratios | 40,139,537 | <p>I have been trying to scrap the value of the Current Ratio (as shown below) from Yahoo Finance using Beautiful Soup, but it keeps returning an empty value.</p>
<p><a href="https://i.stack.imgur.com/SKunN.jpg" rel="nofollow"><img src="https://i.stack.imgur.com/SKunN.jpg" alt="enter image description here"></a></p>
<p>Interestingly, when I look at the Page Source of the URL, the value of the Current Ratio is not listed there.</p>
<p>My code so far is:</p>
<pre><code>import urllib
from bs4 import BeautifulSoup
url = ("http://finance.yahoo.com/quote/GSB/key-statistics?p=GSB")
html = urllib.urlopen(url).read()
soup = BeautifulSoup(html, "html.parser")
script = soup.find("td", {"class": "Fz(s) Fw(500) Ta(end)",
"data-reactid": ".1ujetg16lcg.0.$0.0.0.3.1.$main-0-Quote-Proxy.$main-0-Quote.2.0.0.0.1.0.1:$FINANCIAL_HIGHLIGHTS.$BALANCE_SHEET.1.0.$CURRENT_RATIO.1"
})
</code></pre>
<p>Does anyone know how to solve this?</p>
| 1 | 2016-10-19T19:02:15Z | 40,140,593 | <p>One thing I'd add to Padriac's answer is to except KeyErrors, since you'll probably be scraping more than one ticker. </p>
<pre><code>import requests
a = requests.get('https://query2.finance.yahoo.com/v10/finance/quoteSummary/GSB?formatted=true&crumb=A7e5%2FXKKAFa&lang=en-US&region=US&modules=defaultKeyStatistics%2CfinancialData%2CcalendarEvents&corsDomain=finance.yahoo.com')
b = a.json()
try:
ratio = b['quoteSummary']['result'][0]['financialData']['currentRatio']['raw']
print(ratio) #prints 1.974
except (IndexError, KeyError):
pass
</code></pre>
<p>A cool thing about doing it like this is that you can easily change the keys for the information you want. A good way to see the way the dictionary is nested on the Yahoo! Finance pages is to use <code>pprint</code>. Furthermore, for the pages that have quarterly information just change <code>[0]</code> to <code>[1]</code> to get the info for the second quarter instead of the first.. and so on and so forth. </p>
| 1 | 2016-10-19T20:07:15Z | [
"python",
"beautifulsoup"
] |
passing an array of COM pointers from Python to C++ | 40,139,573 | <p>I've been reading a lot of docs, examples and StackOverflow topics, but still it doesn't work! I'm writing a Python interface to my C++ COM objects. This is not the first time I've done this. In the past I've successfully used comtypes to acquire individual interface pointers and passed them my COM classes, but this time I need to pass a pointer to an array of interface pointers.</p>
<p>The COM interface I need to call:</p>
<pre><code>STDMETHOD(ExportGeopackage)([in] IMap* pMap,
[in] imageFormatType imageFormat,
[in] long imageQuality,
[in] long zoomMin,
[in] long zoomMax,
[in] IFeatureLayer** attributeExportLayers,
[in] BSTR title,
[in] BSTR description,
[in] BSTR saveToPath,
[in] ITrackCancel* pTrackCancel);
</code></pre>
<p>The attributeExportLayers argument is expected to be a pointer to a null-terminated C array of IFeatureLayer pointers. ExportGeopackage() has already been tested with C++ clients. I'm writing the first Python client.</p>
<p>In Python:</p>
<pre><code># append a null pointer to the list of comtypes IFeatureLayer pointers
exportLayers.append(comtypes.cast(0, comtypes.POINTER(esriCarto.IFeatureLayer)))
# create ctypes array and populate
PointerArray = ctypes.c_void_p * len(exportLayers)
pointers = PointerArray()
for i in range(len(exportLayers)):
pointers[i] = exportLayers[i]
# export is comtypes interface pointer acquired earlier
export.ExportGeopackage(map, format, quality, min, max,
ctypes.cast(pointers, ctypes.POINTER(esriCarto.IFeatureLayer)),
title, desc, geopackage_path, 0)
</code></pre>
<p>Comparing Python dumps of the content of exportLayer and pointers variables shows the pointer values being successfully transferred from the former to the latter. Python tests of these pointers are successful. However when I debug into ExportGeopackage() the memory pointed to by attributeExportLayers has no resemblance to the expected array of IFeatureLayer pointers. It looks like a single pointer (pointing to the wrong place) followed by a long string of null pointers. Thinking that possibly the Python pointers variable had already been garbage collected, I added a reference to pointers after the call to ExportGeopackage(). This made no difference.</p>
<p>Am I somehow inserting an extra level of indirection, or not enough indirection? I'm mystified.</p>
<p>TIA for any help (or guesses).
Alan</p>
| 0 | 2016-10-19T19:04:59Z | 40,141,084 | <p>Once again, answering my own question. There is an additional level of indirection being introduced beyond what is required. Apparently, unlike a cast in C, ctypes.cast actually takes the address of the first argument.</p>
<p>Change:</p>
<pre><code>PointerArray = ctypes.c_void_p * len(exportLayers)
</code></pre>
<p>To:</p>
<pre><code>PointerArray = comtypes.POINTER(esriCarto.IFeatureLayer) * len(exportLayers)
</code></pre>
<p>And eliminate the use of ctypes.cast in the call to ExportGeopackage():</p>
<pre><code>export.ExportGeopackage(map, format, quality, min, max,
pointers,
title, desc, geopackage_path, 0)
</code></pre>
| 0 | 2016-10-19T20:37:25Z | [
"python",
"windows",
"types",
"comtypes"
] |
Characters from listbox are still recorded even when deleted from listbox | 40,139,628 | <p>So my little game is programmed to have two characters fight each other. One from the left side and one from the right side. After they fight both should be deleted regardless of who wins or loses. They are in fact deleted from listboxes, but after you have two more charachters from each side fight those previous characters sometimes show up. If you start with Zys and Rash fighting no other names are printed in the win and loss section besides theirs. Only when you go backwards from Dant and Ilora does it work the way it should with each character making a place in either wins or loss only once. If you start with some other characters they could be put in the wins and loss section more then once. It is also possible for a character to be placed as a win or loss even if it hasnt been selected to fight. The bottomline is each character gets to fight a character on the opposite side ONCE and after that it is placed and then deleted with no use in the later part of the program. For some apparent reason it does not do that.</p>
<pre><code>from tkinter import *
from tkinter import ttk
from tkinter import messagebox
class Character:
def __init__(self, name, attack, defense, health):
self.name = name
self.attack = attack
self.defense = defense
self.health = health
self.total = attack+defense+health
#Left side characters
Rash = Character("Rash", 42, 50, 80)
Untss = Character("Untss", 15, 54, 100)
Ilora = Character("Ilora", 60, 35, 80)
#Both sides have totals of 165 168 and 175
#Right side characters
Zys = Character("Zys", 12, 97, 83)
Eentha = Character("Eentha", 55, 17, 90)
Dant = Character("Dant", 73, 28, 88)
def fight(): #Part of code that checks for wins and loss checks which has greater total stats and deletes from list box
try:
namel = ""
namer=""
left = lbox.curselection()[0]
right = rbox.curselection()[0]
totalleft = 0
totalright = 0
if left == 0:
namel = "Rash"
totalleft = Rash.total
elif left==1:
namel = "Untss"
totalleft = Untss.total
elif left==2:
namel = "Ilora"
totalleft = 60+35+80
if right == 0:
namer = "Zys"
totalright = Zys.total
elif right==1:
namer = "Eentha"
totalright = Eentha.total
elif right==2:
namer = "Dant"
totalright = Dant.total
lbox.delete(lbox.curselection()[0])
rbox.delete(rbox.curselection()[0])
print(namel)
print(namer)
if (totalleft>totalright): #Checks if won or lost
wins.set(wins.get()+"\n"+namel)
loss.set(loss.get()+"\n"+namer)
else:
wins.set(wins.get()+"\n"+namer)
loss.set(loss.get()+"\n"+namel)
except IndexError:
pass
#The left listbox and its characters
leftnames = ('Rash', 'Untss', 'Ilora')
lnames = StringVar(value=leftnames)
lbox = Listbox(mainframe, listvariable=lnames, exportselection=0, height=3)
lbox.grid(column=0, row=0)
#Right listboxes characters
rightnames = ('Zys', 'Eentha', 'Dant')
rnames = StringVar(value=rightnames)
rbox = Listbox(mainframe, listvariable=rnames, exportselection=0, height=3)
rbox.grid(column=1, row=0)
#Shows users wins and lossses
wins = StringVar()
loss = StringVar()
#Label that
ttk.Label(mainframe, text="Wins", width=13).grid(column=2, row=0, sticky=N)
ttk.Label(mainframe, text="Loss", width=13).grid(column=2, row=1, sticky=N)
ttk.Label(mainframe, textvariable=wins).grid(column=2, row=0, sticky=(S,E))
ttk.Label(mainframe, textvariable=loss).grid(column=2, row=1, sticky=(S, E))
#Button for fighting
fightbttn= ttk.Button(mainframe, text="Fight", command=fight)
fightbttn.grid(column=3, row=3, sticky=(E))
root.mainloop()
</code></pre>
<p>This is only the part of the code that could relate to the problem not the code as a whole.</p>
<p>This is not the same question from yesterday just the same code. I thought it would be more appropriate to work with the bugs one at a time as different problems so they could be more organized.</p>
| 1 | 2016-10-19T19:08:33Z | 40,142,209 | <p>Problem is because you use always <code>if left == 0: namel = "Rash" even if</code>"Rash"<code>was deleted from listbox and now</code>left == 0<code>means</code>"Untss".</p>
<p>You have to get selected name instead of index </p>
<pre><code> namel = lbox.get(lbox.curselection()[0])
namer = rbox.get(rbox.curselection()[0])
</code></pre>
<p>and use it </p>
<pre><code> if namel == "Rush":
totalleft = Rash.total
</code></pre>
<p>But you could use dictionary to get data </p>
<pre><code>left_characters = {
"Rash": Character("Rash", 42, 50, 80),
"Untss": Character("Untss", 15, 54, 100),
"Ilora": Character("Ilora", 60, 35, 80),
}
right_characters = {
"Zys": Character("Zys", 12, 97, 83),
"Eentha": Character("Eentha", 55, 17, 90),
"Dant": Character("Dant", 73, 28, 88),
}
leftnames = list(left_characters.keys())
rightnames = list(right_characters.keys())
</code></pre>
<p>and then</p>
<pre><code>def fight():
try:
namel = lbox.get(lbox.curselection()[0])
namer = rbox.get(rbox.curselection()[0])
print(namel)
print(namer)
totalleft = left_characters[namel].total
totalright = right_characters[namer].total
lbox.delete(lbox.curselection()[0])
rbox.delete(rbox.curselection()[0])
if totalleft > totalright : #Checks if won or lost
wins.set(wins.get()+"\n"+namel)
loss.set(loss.get()+"\n"+namer)
else:
wins.set(wins.get()+"\n"+namer)
loss.set(loss.get()+"\n"+namel)
except IndexError as e:
print("ERROR:", e)
</code></pre>
<p>If you add new characters to dictionary then you don't have to change code.</p>
<p>BTW: don't use <code>pass</code> in <code>except</code> because you don't see error if there is something wrong with code.</p>
| 0 | 2016-10-19T21:59:32Z | [
"python",
"tkinter",
"listbox"
] |
Percentage data from .csv to excel | 40,139,709 | <p>I read some data under percentage form (11.00%) from a .csv file.
I copy them into an excel file and i want to represent them in a chart.
The problem is, when i copy them into excel, data is automatically converted to string type and i cannot represent them in the chart correctly.
I tried few methods but nothing successfully.</p>
<pre><code>f = open("any.csv")
wb = openpyxl.load_workbook("any.xlsx")
ws = wb.get_sheet_by_name('Sheet1')
reader = csv.reader(f, delimiter=',')
for row in ws.iter_rows(row_offset=0):
for i in reader:
ws.append(i[2:]) code here
</code></pre>
<p>I tried using:</p>
<pre><code>for row in ws.iter_rows(row_offset=0):
for i in reader:
ws.append(float(i[2:]))
</code></pre>
<p>and i recieve this error:<br>
TypeError: float() argument must be a string or a number </p>
<p>I have tried using:</p>
<pre><code>for i in reader:
i[2:] = [float(x) for x in i[2:]]
ws.append(i)
</code></pre>
<p>and i got this eror:
ValueError: invalid literal for float()11.1%</p>
<p>I use the i[2:] because first first and second column contain some text that dont need to be converted</p>
| -1 | 2016-10-19T19:13:00Z | 40,139,789 | <pre><code>for row in ws.iter_rows(row_offset=0):
for i in reader:
ws.append(float(i[2:-1])) code here
</code></pre>
<p>Float the value before you append it</p>
| 0 | 2016-10-19T19:17:08Z | [
"python",
"python-2.7",
"python-3.x",
"openpyxl"
] |
Attribute error for PersonalInfoForm | 40,139,735 | <p>I'm a little confused why is 'clickjacking middleware` <em>trowing</em> Attribute Error on my form.</p>
<p>I'm making a simple application for collecting labor or user information, and I'm facing a small problem, can someone please help me and clarify what is wrong in this code</p>
<p><a href="http://dpaste.com/373PYDK" rel="nofollow">Dpaste</a> from my Traceback, this is my view</p>
<pre><code>class PersonalInfoView(FormView):
"""TODO: CreateView for PersonalInfoForm
return: TODO
"""
template_name = 'apply_to/apply_now.html'
form_class = PersonalInfoForm
success_url = 'success/'
def get(self, form, *args, **kwargs):
"""TODO: define get request
return: TODO
"""
self.object = None
form_class = self.get_form_class()
form = self.get_form(form_class)
return self.render_to_response(
self.get_context_data(form=form))
def post(self, form, *args, **kwargs):
"""TODO: Post request for PersonalInfoForm
return: TODO
"""
self.object = None
form_class = self.get_form_class()
form = self.get_form(form_class)
if form.is_valid():
return self.form_valid(form)
else:
return self.form_class(form)
def form_valid(self, form, *args, **kwargs):
"""TODO: Validate form
return: TODO
"""
self.object = form.save()
return HttpResponseRedirect(self.get_success_url())
def form_invalid(self, form, *args, **kwargs):
"""TODO: handle invalid form request
return: TODO
"""
return self.render_to_response(
self.get_context_data(form=form))
</code></pre>
<p>Urls </p>
<pre><code>"""superjobs URL Configuration
the `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
examples:
function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
including another URLconf
1. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import include, url
from django.contrib import admin
from django.views.generic import TemplateView
from labor_apply_app.views import PersonalInfoView
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
# django-contrib-flatpages
# url(r'^apply_to/', include('labor_apply_app.urls')),
url(r'^$', 'labor_apply_app.views.index', name='index'),
url(r'^apply_now/$', PersonalInfoView.as_view()),
url(r'^success/$', TemplateView.as_view()),
# Django Allauth
url(r'^accounts/', include('allauth.urls')),
]
</code></pre>
| 0 | 2016-10-19T19:14:39Z | 40,139,929 | <p>Your traceback is showing that you haven't used the view above at all, but the form. Presumably you've assigned the wrong thing in urls.py.</p>
<p><strong>Edit</strong> Actually the problem is that your post method, when the form is not valid, returns the form itself and not an HttpResponse.</p>
<p>However you should <strong>not</strong> be defining any of these methods. You are just replicating what the class-based views are already supposed to be doing for you. Make your view actually inherit from CreateView and remove all those method definitions completely.</p>
| 1 | 2016-10-19T19:25:10Z | [
"python",
"django",
"django-forms",
"django-views",
"django-middleware"
] |
Setting Image background for a line plot in matplotlib | 40,139,770 | <p>I am trying to set a background image to a line plot that I have done in matplotlib. While importing the image and using zorder argument also, I am getting two seperate images, in place of a single combined image. Please suggest me a way out. My code is -- </p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>import quandl
import pandas as pd
import sys, os
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
import itertools
def flip(items, ncol):
return itertools.chain(*[items[i::ncol] for i in range(ncol)])
df = pd.read_pickle('neer.pickle')
rows = list(df.index)
countries = ['USA','CHN','JPN','DEU','GBR','FRA','IND','ITA','BRA','CAN','RUS']
x = range(len(rows))
df = df.pct_change()
fig, ax = plt.subplots(1)
for country in countries:
ax.plot(x, df[country], label=country)
plt.xticks(x, rows, size='small', rotation=75)
#legend = ax.legend(loc='upper left', shadow=True)
plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
plt.show(1)
plt.figure(2)
im = plt.imread('world.png')
ax1 = plt.imshow(im, zorder=1)
ax1 = df.iloc[:,:].plot(zorder=2)
handles, labels = ax1.get_legend_handles_labels()
plt.legend(flip(handles, 2), flip(labels, 2), loc=9, ncol=12)
plt.show()</code></pre>
</div>
</div>
</p>
<p>So in the figure(2) I am facing problem and getting two separate plots</p>
| 0 | 2016-10-19T19:16:14Z | 40,139,937 | <p>You're creating two separate figures in your code. The first one with <code>fig, ax = plt.subplots(1)</code> and the second with <code>plt.figure(2)</code></p>
<p>If you delete that second figure, you should be getting closer to your goal</p>
| 0 | 2016-10-19T19:25:46Z | [
"python",
"matplotlib"
] |
Setting Image background for a line plot in matplotlib | 40,139,770 | <p>I am trying to set a background image to a line plot that I have done in matplotlib. While importing the image and using zorder argument also, I am getting two seperate images, in place of a single combined image. Please suggest me a way out. My code is -- </p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>import quandl
import pandas as pd
import sys, os
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
import itertools
def flip(items, ncol):
return itertools.chain(*[items[i::ncol] for i in range(ncol)])
df = pd.read_pickle('neer.pickle')
rows = list(df.index)
countries = ['USA','CHN','JPN','DEU','GBR','FRA','IND','ITA','BRA','CAN','RUS']
x = range(len(rows))
df = df.pct_change()
fig, ax = plt.subplots(1)
for country in countries:
ax.plot(x, df[country], label=country)
plt.xticks(x, rows, size='small', rotation=75)
#legend = ax.legend(loc='upper left', shadow=True)
plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
plt.show(1)
plt.figure(2)
im = plt.imread('world.png')
ax1 = plt.imshow(im, zorder=1)
ax1 = df.iloc[:,:].plot(zorder=2)
handles, labels = ax1.get_legend_handles_labels()
plt.legend(flip(handles, 2), flip(labels, 2), loc=9, ncol=12)
plt.show()</code></pre>
</div>
</div>
</p>
<p>So in the figure(2) I am facing problem and getting two separate plots</p>
| 0 | 2016-10-19T19:16:14Z | 40,141,461 | <p>In order to overlay background image over plot, we need <code>imshow</code> and <code>extent</code> parameter from <code>matplotlib</code>.</p>
<p>Here is an condensed version of your code. Didn't have time to clean up much.</p>
<p>First a sample data is created for 11 countries as listed in your code. It is then <code>pickled</code> and saved to a file (since there is no pickle file data).</p>
<pre><code>import quandl
import pandas as pd
import sys, os
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
import itertools
from scipy.misc import imread
countries = ['USA','CHN','JPN','DEU','GBR','FRA','IND','ITA','BRA','CAN','RUS']
df_sample = pd.DataFrame(np.random.randn(10, 11), columns=list(countries))
df_sample.to_pickle('c:\\temp\\neer.pickle')
</code></pre>
<p>Next the pickle file is read and we create bar plot directly from <code>pandas</code></p>
<pre><code>df = pd.read_pickle('c:\\temp\\neer.pickle')
my_plot = df.plot(kind='bar',stacked=True,title="Plot Over Image")
my_plot.set_xlabel("countries")
my_plot.set_ylabel("some_number")
</code></pre>
<p>Next we use <code>imread</code> to read image into <code>plot</code>.</p>
<pre><code>img = imread("c:\\temp\\world.png")
plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
plt.imshow(img,zorder=0, extent=[0.1, 10.0, -10.0, 10.0])
plt.show()
</code></pre>
<p>Here is an output plot with image as background.
As stated this is crude and can be improved further.
<a href="https://i.stack.imgur.com/UybYo.png" rel="nofollow"><img src="https://i.stack.imgur.com/UybYo.png" alt="enter image description here"></a></p>
| 0 | 2016-10-19T21:00:57Z | [
"python",
"matplotlib"
] |
Is there a way to refer two attributes of an object in a list? | 40,139,814 | <p>I want to know who is the taller athlete (object) in a list of objects. If I want to print it, I tried to write this:</p>
<pre><code>print ("The greater height is",max(x.height for x in athletes_list),"meters.")
</code></pre>
<p>It shows the height of the taller athlete, but I don't know how to get his name by this way, putting all commands in print's body. Is there any way to do this?</p>
<p>I know its possible by creating a for like this:</p>
<pre><code>for i in athletes_list:
if i.height==max(x.height for x in athletes_list):
print ("The taller athlete is",i.name,"with",i.height,"meters.")
</code></pre>
<p>Is it possible to get both informations only in print's body?
Sorry for bad english.</p>
| 1 | 2016-10-19T19:18:41Z | 40,139,916 | <p>Reread your question. The answer is still yes. Use the <code>format</code> method of strings:</p>
<pre><code>print("The taller athlete is {0.name} with {0.height} meters.".format(max(athletes_list, key=lambda a: a.height)))
</code></pre>
| 2 | 2016-10-19T19:24:21Z | [
"python"
] |
Is there a way to refer two attributes of an object in a list? | 40,139,814 | <p>I want to know who is the taller athlete (object) in a list of objects. If I want to print it, I tried to write this:</p>
<pre><code>print ("The greater height is",max(x.height for x in athletes_list),"meters.")
</code></pre>
<p>It shows the height of the taller athlete, but I don't know how to get his name by this way, putting all commands in print's body. Is there any way to do this?</p>
<p>I know its possible by creating a for like this:</p>
<pre><code>for i in athletes_list:
if i.height==max(x.height for x in athletes_list):
print ("The taller athlete is",i.name,"with",i.height,"meters.")
</code></pre>
<p>Is it possible to get both informations only in print's body?
Sorry for bad english.</p>
| 1 | 2016-10-19T19:18:41Z | 40,139,934 | <p>Use <code>max</code> over both values (with height first):</p>
<pre><code>from future_builtins import map # Only on Py2, to get generator based map
from operator import attrgetter
# Ties on height will go to first name alphabetically
maxheight, name = max(map(attrgetter('height', 'name'), athletes))
print("The taller athlete is", name, "with", maxheight, "meters.")
</code></pre>
<p>Or so ties are resolved by order of appearance, not name:</p>
<pre><code>maxheight, name = attrgetter('height', 'name')(max(athletes, key=attrgetter('height')))
</code></pre>
| 1 | 2016-10-19T19:25:28Z | [
"python"
] |
How do I return a nonflat numpy array selecting elements given a set of conditions? | 40,139,826 | <p>I have a multidimensional array, say of shape (4, 3) that looks like</p>
<pre><code>a = np.array([(1,2,3),(4,5,6),(7,8,9),(10,11,12)])
</code></pre>
<p>If I have a list of fixed conditions</p>
<pre><code>conditions = [True, False, False, True]
</code></pre>
<p>How can I return the list</p>
<pre><code>array([(1,2,3),(10,11,12)])
</code></pre>
<p>Using <code>np.extract</code> returns</p>
<pre><code>>>> np.extract(conditions, a)
array([1, 4])
</code></pre>
<p>which only returns the first element along each nested array, as opposed to the array itself. I wasn't sure if or how I could do this with <code>np.where</code>. Any help is much appreciated, thanks!</p>
| 0 | 2016-10-19T19:19:34Z | 40,139,884 | <p>Let's define you variables:</p>
<pre><code>>>> import numpy as np
>>> a = np.array([(1,2,3),(4,5,6),(7,8,9),(10,11,12)])
>>> conditions = [True, False, False, True]
</code></pre>
<p>Now, let's select the elements that you want:</p>
<pre><code>>>> a[np.array(conditions)]
array([[ 1, 2, 3],
[10, 11, 12]])
</code></pre>
<h3>Aside</h3>
<p>Note that the simpler <code>a[conditions]</code> has some ambiguity:</p>
<pre><code>>>> a[conditions]
-c:1: FutureWarning: in the future, boolean array-likes will be handled as a boolean array index
array([[4, 5, 6],
[1, 2, 3],
[1, 2, 3],
[4, 5, 6]])
</code></pre>
<p>As you can see, <code>conditions</code> are treated here as (integer-like) index values which is not what we wanted.</p>
| 1 | 2016-10-19T19:22:24Z | [
"python",
"arrays",
"numpy",
"conditional",
"slice"
] |
How do I return a nonflat numpy array selecting elements given a set of conditions? | 40,139,826 | <p>I have a multidimensional array, say of shape (4, 3) that looks like</p>
<pre><code>a = np.array([(1,2,3),(4,5,6),(7,8,9),(10,11,12)])
</code></pre>
<p>If I have a list of fixed conditions</p>
<pre><code>conditions = [True, False, False, True]
</code></pre>
<p>How can I return the list</p>
<pre><code>array([(1,2,3),(10,11,12)])
</code></pre>
<p>Using <code>np.extract</code> returns</p>
<pre><code>>>> np.extract(conditions, a)
array([1, 4])
</code></pre>
<p>which only returns the first element along each nested array, as opposed to the array itself. I wasn't sure if or how I could do this with <code>np.where</code>. Any help is much appreciated, thanks!</p>
| 0 | 2016-10-19T19:19:34Z | 40,139,895 | <p>you can use simple list slicing and <code>np.where</code> It's more or less made specifically for this situation..</p>
<pre><code>>>> a[np.where(conditions)]
array([[[ 1, 2, 3],
[10, 11, 12]]])
</code></pre>
| 1 | 2016-10-19T19:23:08Z | [
"python",
"arrays",
"numpy",
"conditional",
"slice"
] |
Is it possible to use FillBetweenItem to fill between two PlotCurveItem's in pyqtgraph? | 40,139,984 | <p>I'm attempting to fill between two curves that were created using PlotCurveItem in pyqtgraph.</p>
<pre><code> phigh = self.p2.addItem(pg.PlotCurveItem(x, y, pen = 'k'))
plow = self.p2.addItem(pg.PlotCurveItem(x, yy, pen = 'k'))
pfill = pg.FillBetweenItem(phigh, plow, brush = br)
self.p2.addItem(pfill)
</code></pre>
<p>The curve items are plotting properly however there is no fill. </p>
| 0 | 2016-10-19T19:28:11Z | 40,140,083 | <p>This fixed it. </p>
<pre><code> phigh = pg.PlotCurveItem(x, y, pen = 'k')
plow = pg.PlotCurveItem(x, yy, pen = 'k')
pfill = pg.FillBetweenItem(ph, plow, brush = br)
self.p2.addItem(ph)
self.p2.addItem(plow)
self.p2.addItem(pfill)
</code></pre>
| 0 | 2016-10-19T19:35:18Z | [
"python",
"python-2.7",
"pyqtgraph"
] |
Try and Except (TypeError) | 40,140,094 | <p>What I'm trying to do is create a menu-style start in my program that let's the user choose whether they want to validate a code or generate one. The code looks like this:</p>
<pre><code>choice = input("enter v for validate, or enter g for generate").lower()
try:
choice == "v" and "g"
except TypeError:
print("Not a valid choice! Try again")
restartCode() *#pre-defined function, d/w about this*
</code></pre>
<p>So I would like my program to output that print statement and do that defined function when the user inputs something other than "v" or "g" (not including when they enter capitalised versions of those characters).
There is something wrong with my try and except function, but whenever the user inputs something other than those 2 characters the code just ends.</p>
| 0 | 2016-10-19T19:35:50Z | 40,140,163 | <p>Try.</p>
<pre><code>choice = input("enter v for validate, or enter g for generate").lower()
if (choice == "v") or (choice == "g"):
#do something
else :
print("Not a valid choice! Try again")
restartCode() #pre-defined function, d/w about this*
</code></pre>
<p>However, if you really want to stick with try/except you can store the desired inputs, and compare against them. The error will be a KeyError instead of a TypeError. </p>
<pre><code>choice = input("enter v for validate, or enter g for generate").lower()
valid_choices = {'v':1, 'g':1}
try:
valid_choices[choice]
#do something
except:
KeyError
print("Not a valid choice! Try again")
restartCode() #pre-defined function, d/w about this
</code></pre>
| 1 | 2016-10-19T19:39:57Z | [
"python",
"try-catch",
"typeerror",
"except"
] |
Try and Except (TypeError) | 40,140,094 | <p>What I'm trying to do is create a menu-style start in my program that let's the user choose whether they want to validate a code or generate one. The code looks like this:</p>
<pre><code>choice = input("enter v for validate, or enter g for generate").lower()
try:
choice == "v" and "g"
except TypeError:
print("Not a valid choice! Try again")
restartCode() *#pre-defined function, d/w about this*
</code></pre>
<p>So I would like my program to output that print statement and do that defined function when the user inputs something other than "v" or "g" (not including when they enter capitalised versions of those characters).
There is something wrong with my try and except function, but whenever the user inputs something other than those 2 characters the code just ends.</p>
| 0 | 2016-10-19T19:35:50Z | 40,140,231 | <p>You are confused about what <code>try/except</code> does. <code>try/except</code> is used when an error is likely to be raised. No error will be raised because everything in your program is valid. Errors are raised only when there is an execution error in your code. Errors are not just raised when you need them to be.</p>
<p><em>You</em>, however, want an error to be shown if the user does not enter a valid choice. You need to use an <code>if/else</code> logic instead, and print the error out yourself. And as a side note, the line <code>choice == "v" and "g"</code> does not test if choice is equal to <code>'v'</code> or <code>'g'</code>. It test if choice i equal to v and if the string <code>'g'</code> is "truthy". Your estenially saying</p>
<p><code>if variable = value and True</code></p>
<p>I'm pretty sure that is not what you want. Here is how I would re-write your code.</p>
<pre><code>if choice.lower() in {"v", "g"}: # if choice is 'v' or 'g'
# do stuff
else: # otherwise
print("Not a valid choice! Try again") # print a custom error message.
</code></pre>
| 0 | 2016-10-19T19:43:49Z | [
"python",
"try-catch",
"typeerror",
"except"
] |
Try and Except (TypeError) | 40,140,094 | <p>What I'm trying to do is create a menu-style start in my program that let's the user choose whether they want to validate a code or generate one. The code looks like this:</p>
<pre><code>choice = input("enter v for validate, or enter g for generate").lower()
try:
choice == "v" and "g"
except TypeError:
print("Not a valid choice! Try again")
restartCode() *#pre-defined function, d/w about this*
</code></pre>
<p>So I would like my program to output that print statement and do that defined function when the user inputs something other than "v" or "g" (not including when they enter capitalised versions of those characters).
There is something wrong with my try and except function, but whenever the user inputs something other than those 2 characters the code just ends.</p>
| 0 | 2016-10-19T19:35:50Z | 40,140,234 | <p>The problem is not in your <code>try</code> and <code>except</code> but in the fact that you are using <code>try</code> and <code>except</code> at all. The code in your <code>try</code> block won't give you an error so <code>except</code> will never be triggered. You want to use an <code>if</code> statement.</p>
<p>Also, your condition only checks for <code>choice == "v"</code> because it is evaluated as <code>(choice == "v") and "g"</code>, and <code>"g"</code> is a string not of length 0, so is always "truthy" (taken as true in a Boolean context). Anything <code>and</code> True is unchanged, so only the first test has any meaning. The best way to do this test is with <code>in</code>.</p>
<p>Finally, you can and should use a <code>while</code> loop to repeat the prompt until the user enters a valid entry.</p>
<p>Putting it all together, you want something like this:</p>
<pre><code>prompt = "Enter v for validate, or g for generate >"
choice = input(prompt).strip().lower()[:1] # take at most 1 character
while choice not in ("v", "g"):
print("Not a valid choice! Try again.")
choice = input(prompt).strip().lower()[:1]
</code></pre>
<p>If you think of how you might generalize the code to use it again (as you probably will in the rest of your script), it's easy and useful to do so. First, you can break out the <code>input</code> stuff into a separate function, since it's called twice:</p>
<pre><code>def input1char(prompt):
return input(prompt + " >").strip().lower()[:1]
</code></pre>
<p>And then break out the while loop into its own function too:</p>
<pre><code>def validinput(prompt, options):
letters = tuple(options)
choice = input1char(prompt)
while choice not in options:
print("'%s' is not a valid choice! Try again." % choice)
choice = input1char(prompt)
return choice
</code></pre>
<p>And then you just write:</p>
<pre><code> choice = validinput("Enter v for validate, or g for generate", "vg")
</code></pre>
| 2 | 2016-10-19T19:44:04Z | [
"python",
"try-catch",
"typeerror",
"except"
] |
if-else in python list comprehensions | 40,140,202 | <p>is it possible to write list comprehensions for the following python code:</p>
<pre><code>for str in range(0,len(mixed_content)):
if (mixed_content[str].isdigit()):
num_list.append(mixed_content[str])
else:
string_list.append(mixed_content[str])
</code></pre>
<p>can we use else block in list comprehensions ? I tried to write list comprehensions for above code :</p>
<pre><code>num_list , string_list = [ mixed_content[str] for str in range(0,len(mixed_content)) if(mixed_content[str].isdigit()) else ]
</code></pre>
| 2 | 2016-10-19T19:41:45Z | 40,140,261 | <p>You can only construct one list at a time with list comprehension. You'll want something like:</p>
<pre><code>nums = [foo for foo in mixed_list if foo.isdigit()]
strings = [foo for foo in mixed_list if not foo.isdigit()]
</code></pre>
| 2 | 2016-10-19T19:45:53Z | [
"python",
"python-2.7",
"python-3.x",
"list-comprehension"
] |
if-else in python list comprehensions | 40,140,202 | <p>is it possible to write list comprehensions for the following python code:</p>
<pre><code>for str in range(0,len(mixed_content)):
if (mixed_content[str].isdigit()):
num_list.append(mixed_content[str])
else:
string_list.append(mixed_content[str])
</code></pre>
<p>can we use else block in list comprehensions ? I tried to write list comprehensions for above code :</p>
<pre><code>num_list , string_list = [ mixed_content[str] for str in range(0,len(mixed_content)) if(mixed_content[str].isdigit()) else ]
</code></pre>
| 2 | 2016-10-19T19:41:45Z | 40,140,267 | <p>It's not possible as-is, but if you're looking for one-liners you can do that with a ternary expression inside your loop (saves a test and is compact):</p>
<pre><code>num_list=[]
string_list=[]
for s in ["45","hello","56","foo"]:
(num_list if s.isdigit() else string_list).append(s)
print(num_list,string_list)
</code></pre>
<p>result:</p>
<pre><code>['45', '56'] ['hello', 'foo']
</code></pre>
<p>Notes:</p>
<ul>
<li>despite the parenthesized syntax and the context of the question, <code>(num_list if s.isdigit() else string_list)</code> is not a generator, a ternary expression (protected between parentheses to counter <code>.append</code> precedence) which returns <code>num_list</code> if s is a sequence of (positive) digits and <code>string_list</code> if s otherwise.</li>
<li>this code won't work with negative numbers because <code>isdigits</code> will return false. You'll have to code a special function for that (classical problem here on SO)</li>
</ul>
| 6 | 2016-10-19T19:46:26Z | [
"python",
"python-2.7",
"python-3.x",
"list-comprehension"
] |
if-else in python list comprehensions | 40,140,202 | <p>is it possible to write list comprehensions for the following python code:</p>
<pre><code>for str in range(0,len(mixed_content)):
if (mixed_content[str].isdigit()):
num_list.append(mixed_content[str])
else:
string_list.append(mixed_content[str])
</code></pre>
<p>can we use else block in list comprehensions ? I tried to write list comprehensions for above code :</p>
<pre><code>num_list , string_list = [ mixed_content[str] for str in range(0,len(mixed_content)) if(mixed_content[str].isdigit()) else ]
</code></pre>
| 2 | 2016-10-19T19:41:45Z | 40,140,315 | <p>You can accomplish what you want with two list comprehensions:</p>
<pre><code>num_list = [num for num in mixed_content if num.isdigit()]
string_list = [string for string in mixed_content if not string.isdigit()]
</code></pre>
<p>The else clause is not supported in list comprehensions:</p>
<pre><code>>>> [c for c in range(5) if c == 1 else 0]
SyntaxError: invalid syntax
</code></pre>
| 0 | 2016-10-19T19:49:30Z | [
"python",
"python-2.7",
"python-3.x",
"list-comprehension"
] |
if-else in python list comprehensions | 40,140,202 | <p>is it possible to write list comprehensions for the following python code:</p>
<pre><code>for str in range(0,len(mixed_content)):
if (mixed_content[str].isdigit()):
num_list.append(mixed_content[str])
else:
string_list.append(mixed_content[str])
</code></pre>
<p>can we use else block in list comprehensions ? I tried to write list comprehensions for above code :</p>
<pre><code>num_list , string_list = [ mixed_content[str] for str in range(0,len(mixed_content)) if(mixed_content[str].isdigit()) else ]
</code></pre>
| 2 | 2016-10-19T19:41:45Z | 40,140,324 | <p>A super messy and unpractical way of doing is:</p>
<pre><code>mixed_content = ['a','b','c',"4"]
string_list = []
print [y for y in [x if mixed_content[x].isdigit() else string_list.append(mixed_content[x]) for x in range(0,len(mixed_content))] if y != None]
print string_list
</code></pre>
<p>Returns: </p>
<pre><code>[3]
['a', 'b', 'c']
</code></pre>
<p>Basically list comprehension for your condition and then filter that list comprehension to only accept non <code>None</code></p>
| 0 | 2016-10-19T19:50:06Z | [
"python",
"python-2.7",
"python-3.x",
"list-comprehension"
] |
if-else in python list comprehensions | 40,140,202 | <p>is it possible to write list comprehensions for the following python code:</p>
<pre><code>for str in range(0,len(mixed_content)):
if (mixed_content[str].isdigit()):
num_list.append(mixed_content[str])
else:
string_list.append(mixed_content[str])
</code></pre>
<p>can we use else block in list comprehensions ? I tried to write list comprehensions for above code :</p>
<pre><code>num_list , string_list = [ mixed_content[str] for str in range(0,len(mixed_content)) if(mixed_content[str].isdigit()) else ]
</code></pre>
| 2 | 2016-10-19T19:41:45Z | 40,140,340 | <p>Let's initialize variables:</p>
<pre><code>>>> mixed_content='ab42c1'; num_list=[]; string_list=[]
</code></pre>
<p>Let's create the lists that you want with a single list comprehension:</p>
<pre><code>>>> [num_list.append(c) if c.isdigit() else string_list.append(c) for c in mixed_content]
[None, None, None, None, None, None]
</code></pre>
<p>Let's verify that we have the lists that you want:</p>
<pre><code>>>> num_list, string_list
(['4', '2', '1'], ['a', 'b', 'c'])
</code></pre>
| 1 | 2016-10-19T19:51:06Z | [
"python",
"python-2.7",
"python-3.x",
"list-comprehension"
] |
if-else in python list comprehensions | 40,140,202 | <p>is it possible to write list comprehensions for the following python code:</p>
<pre><code>for str in range(0,len(mixed_content)):
if (mixed_content[str].isdigit()):
num_list.append(mixed_content[str])
else:
string_list.append(mixed_content[str])
</code></pre>
<p>can we use else block in list comprehensions ? I tried to write list comprehensions for above code :</p>
<pre><code>num_list , string_list = [ mixed_content[str] for str in range(0,len(mixed_content)) if(mixed_content[str].isdigit()) else ]
</code></pre>
| 2 | 2016-10-19T19:41:45Z | 40,140,383 | <p>Here is an example of using <code>x if b else y</code> in a list comprehension.</p>
<pre><code>mixed_content = "y16m10"
num_list, string_list = zip(
*[(ch, None) if ch.isdigit() else (None, ch) for ch in mixed_content])
num_list = filter(None, num_list)
string_list = filter(None, string_list)
print num_list, string_list
</code></pre>
| 2 | 2016-10-19T19:53:56Z | [
"python",
"python-2.7",
"python-3.x",
"list-comprehension"
] |
Python Print %s | 40,140,288 | <p>I've got a little Problem with my Python code.</p>
<pre><code>elif option in ['2','zwei','two']:
packagelist = os.popen("adb -d shell pm list packages").read()
print packagelist
print " "
package = parseInput(PACKAGE_QST)
packagelist.index %package
print ("Your package is: %s" %package)
os.system("adb -d backup %s " %package)
</code></pre>
<p>I want that the user can paste the packagename into the input (option) and than it shall do "adb -d backup "
But idk why it doesn't work. I searched pretty long in the internet for a solution, but haven't got one yet. </p>
<p>Im a noob and would appreciate your help so I can get better.</p>
<p>Thank you in advance!</p>
| -5 | 2016-10-19T19:47:43Z | 40,140,318 | <p>You must pass a tuple when using <code>%</code>:</p>
<pre><code># notice how package is wrapped in ()
print ("Your package is: %s" % (package))
# and do the same when you call os.system()
os.system ("adb -d backup %s" % (package))
</code></pre>
| -3 | 2016-10-19T19:49:43Z | [
"python",
"string",
"adb"
] |
Matplotlib: Sharing axes when having 3 graphs 2 at the left and 1 at the right | 40,140,397 | <p>I have following graph:
<a href="https://i.stack.imgur.com/Vqd85.png" rel="nofollow"><img src="https://i.stack.imgur.com/Vqd85.png" alt="enter image description here"></a></p>
<p>However, I want that graphs 221 and 223 share the same x axis. I have the following code:</p>
<pre><code>self.fig_part_1 = plt.figure()
self.plots_part_1 = [
plt.subplot(221),
plt.subplot(223),
plt.subplot(122),
]
</code></pre>
<p>How can I achieve that? In the end I do not want the numbers of axis x in plot 221 to be shown.</p>
| 0 | 2016-10-19T19:55:01Z | 40,140,568 | <p>Just use <code>plt.subplots</code> (different from <code>plt.subplot</code>) to define all your axes, with the option <code>sharex=True</code>:</p>
<pre><code>f, axes = plt.subplots(2,2, sharex=True)
plt.subplot(122)
plt.show()
</code></pre>
<p>Note that the second call with larger subplot array overlay the preceding one.</p>
<p><a href="https://i.stack.imgur.com/Y6SWD.png" rel="nofollow">Example</a> (could not display image due to reputation...)</p>
| 1 | 2016-10-19T20:05:43Z | [
"python",
"matplotlib"
] |
POST XML file with requests | 40,140,412 | <p>I'm getting:</p>
<pre><code><error>You have an error in your XML syntax...
</code></pre>
<p>when I run this python script I just wrote (I'm a newbie)</p>
<pre><code>import requests
xml = """xxx.xml"""
headers = {'Content-Type':'text/xml'}
r = requests.post('https://example.com/serverxml.asp', data=xml)
print (r.content);
</code></pre>
<p>Here is the content of the xxx.xml</p>
<pre><code><xml>
<API>4.0</API>
<action>login</action>
<password>xxxx</password>
<license_number>xxxxx</license_number>
<username>xxx@xyz.com</username>
<training>1</training>
</xml>
</code></pre>
<p>I know that the xml is valid because I use the same xml for a perl script and the contents are being printed back.</p>
<p>Any help will greatly appreciated as I am very new to python.</p>
| 0 | 2016-10-19T19:55:38Z | 40,140,503 | <p>You want to give the XML data from a file to <code>requests.post</code>. But, this function will not open a file for you. It expects you to pass a file object to it, not a file name. You need to open the file before you call requests.post.</p>
<p>Try this:</p>
<pre><code>import requests
# Set the name of the XML file.
xml_file = "xxx.xml"
headers = {'Content-Type':'text/xml'}
# Open the XML file.
with open(xml_file) as xml:
# Give the object representing the XML file to requests.post.
r = requests.post('https://example.com/serverxml.asp', data=xml)
print (r.content);
</code></pre>
| 2 | 2016-10-19T20:01:58Z | [
"python",
"python-requests"
] |
How can I extend the unit selection logic in my RTS game to apply to multiple units? | 40,140,432 | <p>Currently if you left-click on the unit, it becomes 'selected' (or 'de-selected'), and a green square is drawn around it. Then when you right-click somewhere on the screen, the unit moves neatly into the square in the location that you clicked.</p>
<p>Also if you use the up, down, left or right keys it will scroll the screen.</p>
<pre><code>import pygame
import random
pygame.init()
#Define mouse position
mouse_position_x = 525
mouse_position_y = 315
# Define colors
green = (0,255,0)
brown = (150,75,0)
#Define border position
border_x = 0
border_y = 0
#Define character selection box
def character_selection_box():
pygame.draw.line(screen,green,(character_location_x,character_location_y),(character_location_x+character_width,character_location_y),2) # Top bar
pygame.draw.line(screen,green,(character_location_x,character_location_y+character_height),(character_location_x+character_width,character_location_y+character_height),2) # Bottom bar
pygame.draw.line(screen,green,(character_location_x,character_location_y),(character_location_x,character_location_y+character_height),2) # Left bar
pygame.draw.line(screen,green,(character_location_x+character_width,character_location_y),(character_location_x+character_width,character_location_y+character_height+1),2) # Right bar
#Define round
def assign_square(n):
div = (n/35)
rou = round(div)
mul = (35*rou)
return int(mul)
#Set window
screen_width = 981
screen_height = 700
game_screen_width = 800
game_screen_height = 700
screen_size = (screen_width,screen_height)
screen = pygame.display.set_mode(screen_size)
pygame.display.set_caption("Warpath")
#Set block character
character_width = 35
character_height = 35
character_location_x = 525
character_location_y = 315
movement = 1
unit_selected = 0
#Load images
orc_grunt_forward = pygame.image.load('orc_forward3.png') #(35 by 35 pixel image)
character_image = orc_grunt_forward
#Loop until the user clicks the close button
shutdown = False
#Set clock
clock = pygame.time.Clock()
#Set scroll limit
scroll_x = 0
scroll_y = 0
# ---------- Main program loop -----------
while not shutdown:
# --- Main event loop ---
for event in pygame.event.get():
# --- If quit button pressed, shutdown
if event.type == pygame.QUIT:
shutdown = True
# --- If mouse button pressed
elif event.type == pygame.MOUSEBUTTONDOWN: # If a mouse button is pressed
mouse_position = pygame.mouse.get_pos() # Get mouse position
button_type = pygame.mouse.get_pressed() # Check which button was pressed
# --- If left click pressed and the curser was on a character, select that character
if button_type[0] == 1 and mouse_position[0] >= character_location_x and mouse_position[0] <= character_location_x + character_width and mouse_position[1] >= character_location_y and mouse_position[1] <= character_location_y + character_height:
print("Unit selected",unit_selected)
print(button_type)
unit_selected += 1
unit_selected /= unit_selected #(Otherwise it will add up unit selected if you click more than once)
int(unit_selected)
# --- If right click pressed and a character was selected (and it's within the game screen), move the character to the location
elif button_type[2] == 1 and unit_selected == 1 and mouse_position[0] > 175:
mouse_position_x *= 0
mouse_position_y *= 0
if mouse_position[0] >= assign_square(mouse_position[0]):
mouse_position_x += assign_square(mouse_position[0])
elif mouse_position[0] <= assign_square(mouse_position[0]):
mouse_position_x -= 35
mouse_position_x += assign_square(mouse_position[0])
if mouse_position[1] >= assign_square(mouse_position[1]):
mouse_position_y += assign_square(mouse_position[1])
elif mouse_position[1] <= assign_square(mouse_position[1]):
mouse_position_y -= 35
mouse_position_y += assign_square(mouse_position[1])
# --- If left click pressed and the curser was not on a character, deselect the character
elif button_type[0] == 1 and mouse_position[0] < character_location_x or mouse_position[0] > character_location_x + character_width or mouse_position[1] < character_location_y or mouse_position[1] > character_location_y + character_height:
print("Unit not selected")
print(button_type)
unit_selected *= 0
int(unit_selected)
# --- If key pressed, scroll the screen
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT and scroll_x > -10:
direction = "right"
character_location_x -= 35
mouse_position_x -= 35
border_x -= 35
scroll_x -= 1
if event.key == pygame.K_LEFT and scroll_x < 10:
direction = "left"
character_location_x += 35
mouse_position_x += 35
border_x += 35
scroll_x += 1
if event.key == pygame.K_UP and scroll_y < 10:
direction = "up"
character_location_y += 35
mouse_position_y += 35
border_y += 35
scroll_y += 1
if event.key == pygame.K_DOWN and scroll_y > -10:
direction = "down"
character_location_y -= 35
mouse_position_y -= 35
border_y -= 35
scroll_y -= 1
# --- Game logic ---
# --- Set character movement
if character_location_x < mouse_position_x:
character_location_x += movement
if character_location_x > mouse_position_x:
character_location_x -= movement
if character_location_y < mouse_position_y:
character_location_y += movement
if character_location_y > mouse_position_y:
character_location_y -= movement
# --- Drawing ---
screen.fill(brown) # Draw background
screen.blit(character_image,(character_location_x,character_location_y)) # Draw character
if unit_selected == 1:
character_selection_box() # Draw character selection box if unit is selected
clock.tick(30)
pygame.display.flip()
#Shutdown
if shutdown == True:
pygame.quit()
</code></pre>
<p>The problem is that I can't figure out how to extend this to multiple units - currently if I want to add more units I can only either manage to:</p>
<p>a) Move them all at once</p>
<p>or </p>
<p>b) Paste the same code multiple times adjusting the character variable (not a robust / scalable solution)</p>
<p>How can I adjust my code so that I have a scalable solution where:</p>
<p>1) I can select a single unit and move it, without moving every unit at once</p>
<p>2) I can select multiple units by clicking on each one individually, and move them all at once (not worrying about pathfinding right now)</p>
<p>I also tried using classes to achieve this but it still felt like I was copying / pasting multiple functions rather than having a robust solution.</p>
<p>I've removed any code that doesn't concern the issue while keeping a functioning program.</p>
<p>Thanks</p>
| 0 | 2016-10-19T19:57:17Z | 40,142,078 | <p>There are few things to do:</p>
<ol>
<li>Change variables <code>character_*</code> to object that holds all data about the unit.</li>
<li>Create array of units / characters. That way each unit in array can have unique position, velocity ets. </li>
<li>Everywhere in code where you check <code>character_*</code>, change to for loops where you iterate over characters array to check every unit.</li>
<li>Next step should be adding functions like move / shoot to character class, to make keypress event working for multiple units.</li>
</ol>
<p>That should give you code where you can select multiple units (if they occupy same spot) and move them independently of deselected units.</p>
| 1 | 2016-10-19T21:48:59Z | [
"python",
"python-3.x",
"pygame",
"2d-games"
] |
Python Homework score of each name pair | 40,140,498 | <p>I've got an exercise to do and I don't know why, it is not working...</p>
<p>I really hope someone could help me</p>
<p>Thank you in advance</p>
<blockquote>
<p>Calculate and display the score of each name pair (using the lists
list_2D = [âJohnâ,âKateâ,âOliâ]and[âGreenâ, âFletcherâ,âNelsonâ]). The
score of a name combination is calculated by taking the length of the
concatenated (merged) string storing the first and last names and
adding the number of vowels in it. For example, Oli Green has length 9
(counting space between first and last name) + 4 for the four vowels,
resulting in a total score of 13.</p>
</blockquote>
| -2 | 2016-10-19T20:01:39Z | 40,141,075 | <p>I have changed some aspects because I am not going to do your homework for you, but I understand just starting out on Stack and learning to program. It isn't easy so here's some explanation.</p>
<p>So what you will want to do is loop through all of the possible combinations of the first and last names.</p>
<p>I would do a nested for loop:</p>
<p>here is the first part:</p>
<pre><code>array1 = ['John', 'Kate', 'Oli']
array2 = ['Green', 'Fletcher' ,'Nelson']
for i in range(0,3):
for k in range(0,3):
val = array1[i] + " " + array2[k]
print(val)
</code></pre>
<p>What you are doing is you are keeping <code>i</code> at zero, and then looping through everything in the second list. This way you can get every permutation of your list. To find the length you can do a for counting loop starting at position 0 or you can use the <code>.len()</code> function. To find the vowels you will need to look through each string you create and check to see if they match <code>[a, e, i, o, u]</code>. You can do something like </p>
<p><code>if (val[k] == vowelList[j]):
score += score</code> </p>
<p>That is how I would do it, but I am not as experienced as other people here.</p>
<p>Welcome to Stack! It is scary and a lot of people can be off putting and rude, just make sure to check other questions before you post and show some of your own work (what you have tried/attempted.)</p>
| 0 | 2016-10-19T20:36:54Z | [
"python",
"python-2.7",
"python-3.x",
"cloud9-ide",
"cloud9"
] |
Report progress to QProgressBar using variable from an imported module | 40,140,531 | <p>I have a PyQT GUI application <code>progress_bar.py</code>with a single progressbar and an external module <code>worker.py</code> with a <code>process_files()</code> function which does some routine with a list of files and reports current progress using <code>percent</code> variable.</p>
<p>What I want to do is to report the current progress of the <code>worker.process_files</code> using <code>QProgressBar.setValue()</code> method, but I have no idea how to implement it (callback function or something?)</p>
<p>Here are my modules:</p>
<p><strong>progress_bar.py</strong></p>
<pre><code>import sys
from PyQt4 import QtGui
from worker import process_files
class Window(QtGui.QMainWindow):
def __init__(self):
super(Window, self).__init__()
self.setGeometry(100, 100, 300, 100)
self.progress = QtGui.QProgressBar(self)
self.progress.setGeometry(100, 50, 150, 20)
self.progress.setValue(0)
self.show()
app = QtGui.QApplication(sys.argv)
GUI = Window()
# process files and report progress using .setValue(percent)
process_files()
sys.exit(app.exec_())
</code></pre>
<p><strong>worker.py</strong></p>
<pre><code>def process_files():
file_list = ['file1', 'file2', 'file3']
counter = 0
for file in file_list:
# do_stuff_with_the_file
counter += 1
percent = 100 * counter / len(file_list)
print percent
</code></pre>
| 1 | 2016-10-19T20:03:33Z | 40,140,793 | <p>Make the <code>process_files</code> function a generator function that <em>yields</em> a value (the progress value) and pass it as a callback to a method in your <code>Window</code> class that updates the progress bar value. I have added a <code>time.sleep</code> call in your function so you can observe the progress:</p>
<pre><code>import time
from worker import process_files
class Window(QtGui.QMainWindow):
def __init__(self):
...
def observe_process(self, func=None):
try:
for prog in func():
self.progress.setValue(prog)
except TypeError:
print('callback function must be a generator function that yields integer values')
raise
app = QtGui.QApplication(sys.argv)
GUI = Window()
# process files and report progress using .setValue(percent)
GUI.observe_process(process_files)
sys.exit(app.exec_())
</code></pre>
<p><strong>worker.py</strong></p>
<pre><code>def process_files():
file_list = ['file1', 'file2', 'file3']
counter = 0
for file in file_list:
counter += 1
percent = 100 * counter / len(file_list)
time.sleep(1)
yield percent
</code></pre>
<hr>
<p><strong>Result</strong>:</p>
<p>After processing <code>file2</code></p>
<p><a href="https://i.stack.imgur.com/10LSf.png" rel="nofollow"><img src="https://i.stack.imgur.com/10LSf.png" alt="enter image description here"></a></p>
| 2 | 2016-10-19T20:19:41Z | [
"python",
"callback",
"pyqt"
] |
Print random line from txt file? | 40,140,660 | <p>I'm using random.randint to generate a random number, and then assigning that number to a variable. Then I want to print the line with the number I assigned to the variable, but I keep getting the error:</p>
<blockquote>
<p>list index out of range</p>
</blockquote>
<p>Here's what I tried:</p>
<pre><code>f = open(filename. txt)
lines = f.readlines()
rand_line = random. randint(1,10)
print lines[rand_line]
</code></pre>
| 1 | 2016-10-19T20:11:11Z | 40,140,722 | <p>You want to use <code>random.choice</code></p>
<pre><code>import random
with open(filename) as f:
lines = f.readlines()
print(random.choice(lines))
</code></pre>
| 6 | 2016-10-19T20:14:51Z | [
"python",
"random"
] |
Print random line from txt file? | 40,140,660 | <p>I'm using random.randint to generate a random number, and then assigning that number to a variable. Then I want to print the line with the number I assigned to the variable, but I keep getting the error:</p>
<blockquote>
<p>list index out of range</p>
</blockquote>
<p>Here's what I tried:</p>
<pre><code>f = open(filename. txt)
lines = f.readlines()
rand_line = random. randint(1,10)
print lines[rand_line]
</code></pre>
| 1 | 2016-10-19T20:11:11Z | 40,140,814 | <p>This code is correct, assuming that you meant to pass a string to <code>open</code> function, and that you have no space after the dot...
However, be careful to the indexing in Python, namely it starts at 0 and not 1, and then ends at <code>len(your_list)-1</code>.</p>
<p>Using <code>random.choice</code> is better, but if you want to follow your idea it would rather be:</p>
<pre><code>import random
with open('name.txt') as f:
lines = f.readlines()
random_int = random.randint(0,len(lines)-1)
print lines[random_int]
</code></pre>
<p>Since <code>randint</code> includes both boundary, you must look until <code>len(lines)-1</code>.</p>
| 0 | 2016-10-19T20:20:37Z | [
"python",
"random"
] |
Print random line from txt file? | 40,140,660 | <p>I'm using random.randint to generate a random number, and then assigning that number to a variable. Then I want to print the line with the number I assigned to the variable, but I keep getting the error:</p>
<blockquote>
<p>list index out of range</p>
</blockquote>
<p>Here's what I tried:</p>
<pre><code>f = open(filename. txt)
lines = f.readlines()
rand_line = random. randint(1,10)
print lines[rand_line]
</code></pre>
| 1 | 2016-10-19T20:11:11Z | 40,140,827 | <pre><code>f = open(filename. txt)
lines = f.readlines()
rand_line = random.randint(0, (len(lines) - 1)) # https://docs.python.org/2/library/random.html#random.randint
print lines[rand_line]
</code></pre>
| 0 | 2016-10-19T20:21:17Z | [
"python",
"random"
] |
Django get related objects ManyToMany relationships | 40,140,733 | <p>i have two models:</p>
<pre><code>class CartToys(models.Model):
name = models.CharField(max_length=350)
quantity = models.IntegerField()
class Cart(models.Model):
cart_item = models.ManyToManyField(CartToys)
</code></pre>
<p>i want to get all related toys to this cart. how can i do this </p>
| 0 | 2016-10-19T20:15:31Z | 40,140,796 | <p>you would use...</p>
<pre><code>cart = Cart.objects.first()
objects = cart.cart_item.all() # this line return all related objects for CartToys
# and in reverse
cart_toy = CartToys.objects.first()
carts = cart_toy.cart_set.all() # this line return all related objects for Cart
</code></pre>
| 1 | 2016-10-19T20:19:46Z | [
"python",
"django"
] |
How do you look for a line in a text file, from a sentence a user has inputted, by using its keywords? | 40,140,821 | <pre><code>a=input("Please enter your problem?")
problem= ()
with open('solutions.txt', 'r') as searchfile:
for line in searchfile:
if problem in line:
print (line)
</code></pre>
<p>Can someone please help me on how to get the keywords from the inputed string by the user. Thanks. I need help on how to look for some of the words the users inputed in to =a and search for them on the textfile and print the line</p>
| 0 | 2016-10-19T20:21:01Z | 40,141,002 | <p>I assume your keywords is meant to be a list? </p>
<p>Then you use <a href="https://docs.python.org/3/library/functions.html#any" rel="nofollow"><code>any()</code></a> to check if any word out of the keywords is in the line. </p>
<pre><code>a=input("Please enter your problem?")
problem= ['#keywords', 'not', 'sure', 'how']
with open('solutions.txt', 'r') as searchfile:
for line in searchfile:
if any(word in line for word in problem):
print (line)
</code></pre>
<p>Though, you may want to <code>split()</code> your line to improve that detection. </p>
<p>Otherwise, you have <code>a</code>, which stores the user's input, so you can use that. </p>
<pre><code>a=input("Please enter your problem?")
problem= a.split()
</code></pre>
<p>Then, again <code>problem</code> is a list, so you use <code>any()</code> as before</p>
<p>Or, if you want to check if the entire entered value is in a line, then </p>
<pre><code>if a in line:
print(line)
</code></pre>
| 2 | 2016-10-19T20:31:51Z | [
"python",
"python-3.x"
] |
How do you look for a line in a text file, from a sentence a user has inputted, by using its keywords? | 40,140,821 | <pre><code>a=input("Please enter your problem?")
problem= ()
with open('solutions.txt', 'r') as searchfile:
for line in searchfile:
if problem in line:
print (line)
</code></pre>
<p>Can someone please help me on how to get the keywords from the inputed string by the user. Thanks. I need help on how to look for some of the words the users inputed in to =a and search for them on the textfile and print the line</p>
| 0 | 2016-10-19T20:21:01Z | 40,141,278 | <p>I am not sure I understood the question but is this what you want?. this will take the line containing the most words from the user input:</p>
<pre><code>problem = a.split(' ')
max_num, current_num = 0,0 #max_num count the maximum apparition of words from the input in the line| current_num count the current number of apparition of words of the user input in the line
chosen_line = ''
with open('solutions.txt', 'r') as searchfile:
for line in searchfile:
for word in problem:
if word in line:
current_num+=1
if current_num>max_num:
print line,max_num,current_num
max_num=current_num
chosen_line = line
current_num = 0
print chosen_line
</code></pre>
<p>but it seems to me the easiest way to do what you want is to store at the start of each answer the question, or even easier - just ask the user the question number and return this corresponding answer.</p>
| 0 | 2016-10-19T20:49:21Z | [
"python",
"python-3.x"
] |
Python creating objects from a class using multiple files | 40,140,883 | <p>I need to use a 'Student' class with 5 variables and create objects using more than one file. </p>
<p>The text files: (Students.txt)</p>
<pre><code>Last Name Midle Name First Name Student ID
----------------------------------------------
Howard Moe howar1m
Howard Curly howar1c
Fine Lary fine1l
Howard Shemp howar1s
Besser Joe besse1j
DeRita Joe Curly derit1cj
Tiure Desilijic Jaba tiure1jd
Tharen Bria thare1b
Tai Besadii Durga tai1db
</code></pre>
<p>Text file 2: (CourseEnrollment.txt)</p>
<pre><code>PH03
----
fine1l
howar1s
besse1j
derit1cj
tiure1jd
targa1d
bomba1t
brand1m
took1p
mccoy1l
solo1h
edrie1m
mccoy1e
adama1l
grays1z
MT03
----
cottl1s
fine1l
clega1s
targa1d
took1p
mccoy1l
crush1w
dane1a
monto1i
rugen1t
talto1v
watso1j
carpe1m
rosli1l
biggs1gj
tigh1e
PH05
----
zarek1t
adama1w
tigh1s
cottl1s
howar1m
howar1s
besse1j
balta1g
derit1cj
thare1b
hego1d
lanni1t
stark1a
clega1s
scott1m
monto1i
flaum1e
watso1j
biggs1gj
dane1a
EN01
----
howar1c
fine1l
tai1db
targa1d
brand1m
corey1c
edrie1m
watso1j
carpe1m
sobch1w
EN02
----
howar1m
howar1s
besse1j
tiure1jd
tai1db
hego1d
lanni1t
stark1a
mccoy1l
scott1m
crush1w
dane1a
monto1i
rugen1t
solo1h
flaum1e
talto1v
watso1j
mccoy1e
CS02
----
howar1m
howar1c
besse1j
derit1cj
thare1b
hego1d
clega1s
targa1d
brand1m
rugen1t
flaum1e
talto1v
mccoy1e
grube1h
AR00
----
tigh1e
rosli1l
murph1a
grays1z
howar1c
howar1s
tiure1jd
thare1b
lanni1t
clega1s
bomba1t
balta1g
brand1m
took1p
crush1w
corey1c
edrie1m
grube1h
sobch1w
MT01
----
derit1cj
tai1db
hego1d
stark1a
bomba1t
took1p
scott1m
crush1w
grube1h
rugen1t
solo1h
corey1c
flaum1e
talto1v
mccoy1e
carpe1m
sobch1w
CS01
----
howar1m
howar1c
fine1l
tiure1jd
thare1b
tai1db
lanni1t
stark1a
bomba1t
mccoy1l
monto1i
solo1h
biggs1gj
corey1c
edrie1m
carpe1m
CS05
----
grays1z
adama1w
adama1l
rosli1l
balta1g
tigh1e
tigh1s
cottl1s
zarek1t
murph1a
sobch1w
dane1a
EN08
----
grays1z
adama1w
adama1l
rosli1l
balta1g
tigh1e
tigh1s
cottl1s
zarek1t
murph1a
grube1h
biggs1gj
OT02
----
adama1w
adama1l
tigh1s
scott1m
zarek1t
murph1a
</code></pre>
<p>I need to read in the text files to create Student objects using both files and the 'Student' class.
The class is: </p>
<pre><code>class Student (object):
def __init__(self, first_name, middle_name, last_name, student_id, enrolled_courses):
"""Initialization method"""
self.first_name = first_name
self.middle_name = middle_name
self.last_name = last_name
self.student_id = student_id
self.enrolled_courses = enrolled_courses
</code></pre>
<p>and in the main method I have:</p>
<pre><code>if __name__ == '__main__':
list_of_students = []
with open('Students.txt') as f:
for line in f:
data = line.split()
if len(data) == 3:
first_name, last_name, student_id = data
list_of_students.append(Student(last_name, '', first_name, student_id))
elif len(data) == 4:
list_of_students.append(Student(*data))
else:
continue
</code></pre>
<p>When I run the program without an <code>enrolled_courses</code> variable and only read in 'Students.txt', it runs perfect and creates the <code>Student</code> objects with <code>first_name</code>, <code>middle_name</code>, <code>last_name</code> and <code>student_id</code>. However, I still need to use add the <code>enrolled_courses</code> variable to the objects and obtain it from 'EnrolledCourses.txt'. How can I read in both files and assign the variables to the objects I'm trying to create?</p>
| 1 | 2016-10-19T20:24:35Z | 40,141,068 | <p>First read your student/course and create a dictionary: key=student, value=list of courses</p>
<p>The format is strange but the code below has been tested and works (maybe not as robust as it should, though). Read line by line, course first, and list of students. Add to dictionary (create empty list if key doesn't exist, nice <code>defaultdict</code> object does that):</p>
<pre><code>from collections import defaultdict
student_course = defaultdict(list)
with open("CourseEnrollment.txt") as enr:
while True:
try:
course_name = next(enr).strip()
next(enr) # skip dashes
while True:
student = next(enr).strip()
if student=="":
break
student_course[student].append(course_name)
except StopIteration:
break
</code></pre>
<p>and in your code, call <code>Student</code> constructor like this:</p>
<pre><code>list_of_students.append(Student(last_name, '', first_name, student_id, student_course[student_id]))
</code></pre>
| 1 | 2016-10-19T20:36:21Z | [
"python",
"file",
"object"
] |
Java like function getLeastSignificantBits() & getMostSignificantBits in Python? | 40,140,892 | <p>Can someone please help me out in forming an easy function to extract the leastSignificant & mostSignificant bits in Python?</p>
<p>Ex code in Java:</p>
<pre><code>UUID u = UUID.fromString('a316b044-0157-1000-efe6-40fc5d2f0036');
long leastSignificantBits = u.getLeastSignificantBits();
private UUID(byte[] data) {
long msb = 0;
long lsb = 0;
assert data.length == 16 : "data must be 16 bytes in length";
for (int i=0; i<8; i++)
msb = (msb << 8) | (data[i] & 0xff);
for (int i=8; i<16; i++)
lsb = (lsb << 8) | (data[i] & 0xff);
this.mostSigBits = msb;
this.leastSigBits = lsb;
}
</code></pre>
<p>--> Output value: -1160168401362026442</p>
| 0 | 2016-10-19T20:25:10Z | 40,141,219 | <p><code>efe640fc5d2f0036</code> in decimal is 17286575672347525174. Substract <code>0x10000000000000000</code> from it & negate: you get <code>-1160168401362026442</code></p>
<pre><code>int("efe640fc5d2f0036",16)-0x10000000000000000 -> -1160168401362026442
</code></pre>
<p>Note that it's only guesswork but seems to work with the sole test case you provided (fortunately it was negative). Call that reverse engineering.</p>
<p>Take 2 last hex values (dash separated) and join them. I suppose the storage means that it becomes negative when first digit is above 7, so negate it with higher 2-power if that's the case:</p>
<pre><code>def getLeastSignificantBits(s):
hv = "".join(s.split("-")[-2:])
v = int(hv,16)
if int(hv[0],16)>7:
# negative
v = v-0x10000000000000000
return v
print(getLeastSignificantBits('a316b044-0157-1000-efe6-40fc5d2f0036'))
</code></pre>
<p>result:</p>
<pre><code>-1160168401362026442
</code></pre>
<p>EDIT: providing a method which takes the whole string and returns lsb & msb couple</p>
<pre><code>def getLeastMostSignificantBits(s):
sp=s.split("-")
lsb_s = "".join(sp[-2:])
lsb = int(lsb_s,16)
if int(lsb_s[0],16)>7:
# negative
lsb = lsb-0x10000000000000000
msb_s = "".join(sp[:3])
msb = int(msb_s,16)
if int(msb_s[0],16)>7:
# negative
msb = msb-0x10000000000000000
return lsb,msb
print(getLeastMostSignificantBits('a316b044-0157-1000-efe6-40fc5d2f0036'))
</code></pre>
<p>result:</p>
<pre><code>(-1160168401362026442, -6694969989912915968)
</code></pre>
| 1 | 2016-10-19T20:45:32Z | [
"python",
"bitmap",
"bit"
] |
What do &=, |=, and ~ do in Pandas | 40,140,933 | <p>I frequently see code like this at work:</p>
<pre><code>overlap &= group['ADMSN_DT'].loc[i] <= group['epi_end'].loc[j]
</code></pre>
<p>My question is what do operators such as <code>&=</code>, <code>|=</code>, and <code>~</code> do in pandas?</p>
| 3 | 2016-10-19T20:27:27Z | 40,141,039 | <p>From the <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow">documentation</a></p>
<blockquote>
<p>The operators are: | for or, & for and, and ~ for not. These must be
grouped by using parentheses.</p>
</blockquote>
<p><a href="https://docs.python.org/3/reference/simple_stmts.html#augmented-assignment-statements" rel="nofollow">Augmented assignment statements</a></p>
<blockquote>
<p>An augmented assignment evaluates the target (which, unlike normal
assignment statements, cannot be an unpacking) and the expression
list, performs the binary operation specific to the type of assignment
on the two operands, and assigns the result to the original target.
The target is only evaluated once.</p>
</blockquote>
<p>just like <code>a += 1</code> increments <code>a</code>, <code>a &= b</code> compares <code>a</code> and <code>b</code> and assigns the result to <code>a</code>.</p>
<pre><code>a = 1
b = 0
print(a & b)
>>> 0
a &= b
print(a)
>>> 0
</code></pre>
<p>And a <code>pandas</code> example</p>
<p>Let's generate a dataframe of zeros and ones.</p>
<pre><code>import numpy as np
import pandas as pd
a = pd.DataFrame(np.random.randint(0, 2, size=(6,4)), columns=list('ABCD'))
b = pd.DataFrame(np.random.randint(0, 2, size=(6,4)), columns=list('ABCD'))
</code></pre>
<p>Our initial dataframe</p>
<pre><code>print(a)
</code></pre>
<blockquote>
<pre><code> A B C D
0 0 1 1 0
1 0 0 1 0
2 1 0 0 1
3 1 1 0 0
4 0 0 0 1
5 0 0 0 0
</code></pre>
</blockquote>
<pre><code>print(b)
</code></pre>
<blockquote>
<pre><code> A B C D
0 0 0 0 0
1 1 1 1 0
2 0 1 1 1
3 0 1 1 1
4 1 1 1 0
5 1 1 1 1
</code></pre>
</blockquote>
<p>The 4th row of <code>a</code> and <code>b</code></p>
<pre><code>print(a.loc[3])
</code></pre>
<blockquote>
<pre><code>A 1
B 1
C 0
D 0
Name: 1, dtype: int32
</code></pre>
</blockquote>
<pre><code>print(b.loc[3])
</code></pre>
<blockquote>
<pre><code>A 0
B 1
C 1
D 1
Name: 1, dtype: int32
</code></pre>
</blockquote>
<p>Now evaluate and assign row 4</p>
<pre><code>a.loc[3] &= b.loc[3]
</code></pre>
<p>Row 4 of <code>a</code> has changed. Only where both rows have 1 at the same position a 1 is written back to <code>a</code>.</p>
<pre><code>print(a.loc[3])
</code></pre>
<blockquote>
<pre><code>A 0
B 1
C 0
D 0
Name: 3, dtype: int32
</code></pre>
</blockquote>
| 2 | 2016-10-19T20:34:39Z | [
"python",
"python-2.7",
"pandas"
] |
Numpy: How to vectorize parameters of a functional form of a function applied to a data set | 40,140,942 | <p>Ultimately, I want to remove all explicit loops in the code below to take advantage of numpy vectorization and function calls in C instead of python.</p>
<p>Below is simplified for uses of numpy in python.
I have the following quadratic function:</p>
<pre><code>def quadratic_func(a,b,c,x):
return a*x*x + b*x + c
</code></pre>
<p>I am trying to optimize choices of a,b,c given input data x and output data y of the same size (of course, this should be done by linear regression...but humor me). Say len(x)=100. Easy to vectorize with scalars a,b,c to get back a result of length 100.</p>
<p>Let's say that we know a,b,c should be inside of [-10,10] and I optimize by building a grid and picking the point with the min sum square error.</p>
<pre><code>a=np.arange(-10.0, 10.01, 2.0)
nodes=np.array(np.meshgrid(a,a,a)).T.reshape(-1,3) #3-d cartesian product with array of nodes
</code></pre>
<p>For each of the 1331 nodes, I would like to calculate all 1331 of the length 100 return values. </p>
<pre><code>res=[]
x=np.random.uniform(-5.0,5.0, 100)
for node in nodes:
res.append(quadratic_func(*node, x=x))
</code></pre>
<p>How can I take advantage of broadcasting so as to get my list of 1331 items each with 100 values that are the results of calling quadratic_func on x? Answer must use vectorization, broadcasting, etc to get the orders of magnitude speed improvements I am looking for. Also, the answer must use calls to quadratic_func - or more generally, my_func(*node, x=x).</p>
<p>In real life I am optimizing a non-linear function that is not even close to being convex and has many local minimums. It is a great functional form to use if I can get to the "right" local minimum - I already know how to do that, but would like to get there faster!</p>
| 4 | 2016-10-19T20:27:52Z | 40,141,272 | <p>One approach using a combination of <a href="https://docs.scipy.org/doc/numpy/user/basics.broadcasting.html" rel="nofollow"><code>broadcasting</code></a> and <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.einsum.html" rel="nofollow"><code>np.einsum</code></a> -</p>
<pre><code>np.einsum('ij,jk->ik',nodes,x**np.array([2,1,0])[:,None])
</code></pre>
<p>Another one using matrix-multiplication with <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.dot.html" rel="nofollow"><code>np.dot</code></a> -</p>
<pre><code>nodes.dot(x**np.array([2,1,0])[:,None])
</code></pre>
| 1 | 2016-10-19T20:48:48Z | [
"python",
"numpy",
"vectorization",
"numpy-broadcasting"
] |
Python/Spyder: General Working Directory | 40,140,958 | <p>So far I have code that opens a text file, manipulates it into a pandas data file, then exports to excel.</p>
<p>I'm sharing this code with other people, and we all have the same working directory within Spyder. All the code works fine, the only lines I want to manipulate are the opening of the file, and the exporting of the file.</p>
<pre><code>with open(r'C:\Users\"my_name"\Desktop\data\file.txt', 'r') as data_file:
</code></pre>
<hr>
<p>The issue here is, I want to set my working directory to just "\data" so that I can just write: </p>
<pre><code>with open(r'file.txt', 'r') as data_file:
</code></pre>
<p>this way, the people I send it to, who also have "\data" as their working directory on their computer can just run the code, and it will select the "file.txt" that is in their data directory.</p>
| 1 | 2016-10-19T20:28:31Z | 40,141,235 | <p>The answer that you are technically looking for is using <code>os.chdir()</code> as follows</p>
<pre><code>import os
os.chdir('.', 'data')
#THE REST OF THE CODE IS THE SAME
with open(r'file.txt', 'r') as data_file:
</code></pre>
<p>A safer answer would however be </p>
<pre><code>def doTheThing(fName):
return os.path.join(os.getcwd(),'data',fName)
with open(doTheThing('file.txt'), 'r') as data_file:
</code></pre>
| 1 | 2016-10-19T20:46:39Z | [
"python",
"python-3.x",
"directory",
"spyder"
] |
HTML select options from a python list | 40,141,000 | <p>I'm writing a python cgi script to setup a Hadoop cluster.
I want to create an HTML select dropdown where the options are taken from a python list. Is this possible??
I've looked around a lot. Couldn't find any proper answer to this.</p>
<p>This is what i've found so far on another thread...</p>
<pre><code>def makeSelect(name,values):
SEL = '<select name="{0}">\n{1}</select>\n'
OPT = '<option value="{0}">{0}</option>\n'
return SEL.format(name, ''.join(OPT.format(v) for v in values))
</code></pre>
<p>I really need some help. Please. Thanks.</p>
| 1 | 2016-10-19T20:31:39Z | 40,141,433 | <p>You need to generate a list of "option"s and pass them over to your javascript to make the list</p>
<pre><code>values = {"A": "One", "B": "Two", "C": "Three"}
options = []
for value in sorted(values.keys()):
options.append("<option value='" + value + "'>" + values[value] + "</option>")
</code></pre>
<p>Then inject "options" into your html. Say, in your "template.html" there is a line:</p>
<pre><code>var options = $python_list;
</code></pre>
<p>Then at the end of your python script:</p>
<pre><code>####open the html template file, read it into 'content'
html_file = "template.html"
f = open(html_file, 'r')
content = f.read()
f.close()
####replace the place holder with your python-generated list
content = content.replace("$python_list", json.dumps(options))
####write content into the final html
output_html_file = "index.html"
f = open(output_html_file, 'w')
f.write(temp_content)
f.close()
</code></pre>
<p>In your "index.html", you should have one line after "var options = ..." that takes the list and generate the dropdown.</p>
<pre><code>$('#my_dropdown').append(options.join("")).selectmenu();
</code></pre>
<p>Alternatively, I suggest that you use your python to generate a json file (with json.dumps()), a file called "config.json" maybe. And your html javascript file should read this json file to render the final page. So in your json file, there should be something like:</p>
<p>{ ... "options": ["One", "Two", "Three"] ...}</p>
<p>And in your html section, you could read the option values</p>
<pre><code>d3.json("config.json", function(data)) {
var options = [];
for (var i= 0; i < data.options.length; i++)
{
options.push("<option value='" + data.options[i] + "'>" + data.options[i] + "</option>");
}
$('#my_dropdown').append(options.join("")).selectmenu();
}
</code></pre>
| 1 | 2016-10-19T20:59:15Z | [
"python",
"html",
"cgi"
] |
Use a xref of values to sub into tuple based on value - Python | 40,141,134 | <p>I have a list of xref values</p>
<pre><code>internal_customer = {'01':'11', '03':'33', '05':'55', '07':'77', '08':'88', '06':'66', '09':'22', '11':'18', '12':'19'}
</code></pre>
<p>that I would like to use to sub a value in a tuple:</p>
<pre><code>('03', 'S/N A1631703')
</code></pre>
<p>So my resulting tuple would be</p>
<pre><code>('33', 'S/N A1631703')
</code></pre>
<p>Can someone point me in the direction of the tools I could use to accomplish this? </p>
| 1 | 2016-10-19T20:41:05Z | 40,141,206 | <p>Unpack and access the dict using the first element, presuming you have an list of tuples:</p>
<pre><code>internal_customer = {'01':'11', '03':'33', '05':'55', '07':'77', '08':'88', '06':'66', '09':'22', '11':'18', '12':'19'}
lst = [('03', 'S/N A1631703'),('05', 'S/N A1631703')]
lst[:] = ((internal_customer[a], b) for a,b in t)
print(t)
</code></pre>
<p>tuples are immutable so there is no notion of mutating, you have to create a new tuple comprising of the new value from the dict and the existing second element. The <code>lst[:]</code> syntax at least allows you to modify the original list. You can of course just reassign the name or create a completely new list if you want to maintain the original.</p>
| 2 | 2016-10-19T20:44:56Z | [
"python"
] |
Python: Finding palindromes in a list | 40,141,171 | <pre><code>def num_sequence (num1, num2):
#This function takes the lower and upper bound and builds a list.
array = []
for i in range(num2 + 1):
if i >= num1:
array.append(i)
return array
def inverted_sequence (array):
#This function takes the previous and list inverts the numbers in every element.
for i in range(len(array)):
if array[i] > 10:
array[i] = str(array[i])
#Converts the i element of the array to a string.
array[i] = array[i][::-1]
#Inverts the the position of the numbers in every element.
array[i] = int(array[i])
#Converts the i element of the array to an integer.
return array
def main ():
#Main program.
lower = int(input("Type the lower bound: "))
upper = int(input("Type the upper bound: "))
sequence = num_sequence(lower, upper)
inv_sequence = sequence[:]
inv_sequence = inverted_sequence(inv_sequence)
print (sequence)
print (inv_sequence)
"""While loop inside the for loop that checks if the number is a palindrome.
if to check if it is a palindrome return True, else return False"""
pal_count = 0
seq_sum = []
for i in range(len(sequence)):
if sequence[i] != inv_sequence[i]:
while sequence[i] != inv_sequence[i]:
seq_sum.append(sequence[i] + inv_sequence[i])
sequence = seq_sum
inv_sequence = inverted_sequence(inv_sequence)
print (seq_sum)
if sequence[i] == inv_sequence[i]:
pal_count *= 1
print (pal_count)
main()
</code></pre>
<p>I am trying to make a program that finds all the palindromes in a range of numbers and if they are not palindromes, reverse the number and add it to the original until it becomes a palindrome. In my code I created a list of numbers with two inputs and name the list sequence. inv_sequence is the previous list but with numbers of each element reversed. when i try to add sequence[i] and inv_sequence[i] the program throws an error saying that the list is out of range. I am testing the program with the lower bound being 5 and the upper bound being 15.</p>
| 0 | 2016-10-19T20:43:24Z | 40,142,008 | <p>I assume that you mean that you want the final list to contain the lowest palindrome in the sequence formed by the sum of the previous number in the sequence and the result of reversing the previous number in the sequence.</p>
<p>If so, here is some code (not bulletproof):</p>
<pre><code>#checks if a number is a palindrome by comparing the string written fowards
#with the string written backwards
def is_pal(x):
if str(x)==str(x)[::-1]:
return True
return False
#iterates a number by adding and reversing until it is a palindrom
def iter_pal(x):
while not is_pal(x):
x+=int(str(x)[::-1]) #adds the number's reverse to itself
return x
#main program
def main():
#gets input
lower = int(input("Type the lower bound: "))
upper = int(input("Type the upper bound: "))
#uses range to make the sequence of numbers
sequence = list(range(lower,upper+1))
#iterates through the list performing iter_pal
for i in range(upper-lower+1):
sequence[i]=iter_pal(sequence[i])
#prints the final sequence
print(sequence)
main()
</code></pre>
<p>I'm not sure what you will do with the <a href="https://en.wikipedia.org/wiki/Lychrel_number" rel="nofollow">Lychrel numbers</a>.</p>
| 0 | 2016-10-19T21:44:04Z | [
"python",
"python-3.x"
] |
JavaScript double backslash in WebSocket messages | 40,141,181 | <p>I'm sending binary data over WebSocket to a Python application. This binary data is decoded by calling <code>struct.unpack("BH", data")</code> on it, requiring a 4-long bytes object.<br>
The problem I'm currently facing is, that all data contains duplicate backslashes, even in <code>arraybuffer</code> mode and is therefor 16 bytes long. I can't detect the varying size because there is data appended to the back of it (irrelevant for this question) and even if I could, I also couldn't find a way to strip the backslashes in Python.</p>
<p>How the data is sent:</p>
<pre class="lang-js prettyprint-override"><code>// this.webSocket.binaryType = "arraybuffer";
var message = "\\x05\\x00\\x00\\x00"; // escaping required
var buffer = new Int8Array(message.length);
for (var i = 0; i < message.length; i++) {
buffer[i] = message.charCodeAt(i);
}
this.webSocket.send(buffer.buffer);
</code></pre>
<p>In comparison, this is how said data looks when defined in Python:</p>
<pre class="lang-py prettyprint-override"><code>b'\x05\x00\x00\x00'
</code></pre>
<p>And this is how it looks as a received message:
</p>
<pre><code>b'\\x05\\x00\\x00\\x00'
</code></pre>
<p>The ideal solution for this issue would be on the JavaScript-side because I can't really change the implementation of the Python application without breaking Python-based clients.</p>
| 0 | 2016-10-19T20:44:07Z | 40,141,584 | <p>You should define the message as bytes and not as string:</p>
<pre><code>var buffer = new Int8Array([5,0,0,0])
this.webSocket.send(buffer.buffer)
</code></pre>
| 1 | 2016-10-19T21:09:56Z | [
"javascript",
"python",
"struct",
"byte"
] |
selenium run chrome on raspberry pi | 40,141,260 | <p>If your seeing this I guess you are looking to run chromium on a raspberry pi with selenium.</p>
<p>like this <code>Driver = webdriver.Chrome("path/to/chomedriver")</code> or like this <code>webdriver.Chrome()</code></p>
| 1 | 2016-10-19T20:48:21Z | 40,141,261 | <p>I have concluded that after hours and a hole night of debugging that you can't because there is no chromedriver compatible with a raspberry pi processor. Even if you download the linux 32bit. You can confirm this by running this in a terminal window <code>path/to/chromedriver</code> it will give you this error </p>
<blockquote>
<p>cannot execute binary file: Exec format error</p>
</blockquote>
<p>hope this helps anyone that wanted to do this :)</p>
| 1 | 2016-10-19T20:48:21Z | [
"python",
"selenium",
"raspberry-pi"
] |
Convert multiple columns to one column | 40,141,353 | <p>I'm looking to merge multiple columns to one column.</p>
<p>Here's my current dataset :</p>
<pre><code>Column A Column B Column C
a1 b1 c1
b2 a2 e2
</code></pre>
<p>I am looking for the following as output</p>
<pre><code>Column D
a1
b1
c1
b2
a2
e2
</code></pre>
<p>Is this possible ? Using R or Python ?</p>
| 1 | 2016-10-19T20:54:39Z | 40,141,589 | <p>With the data that you provided, in the format you provided, you could do this with:</p>
<pre><code>data.frame(ColumnD=c(t(df)))
ColumnD
1 a1
2 b1
3 c1
4 b2
5 a2
6 e2
</code></pre>
<p>We transpose the data, then combine it.</p>
| 0 | 2016-10-19T21:10:23Z | [
"python",
"list"
] |
Easier way to check if a string contains only one type of letter in python | 40,141,540 | <p>I have a string <code>'829383&&*&@<<<<>><>GG'</code>. I want a way to measure if a string has only one type of letter. For example the string above would return True, because it only has two Gs, but this string, <code>'829383&&*&@<<<<>><>GGAa'</code> would not. I've been iteratively going through the string having made it into an array. I was hoping someone knew an easier way. </p>
| 1 | 2016-10-19T21:06:36Z | 40,141,601 | <p>use <code>filter</code> with <code>str.isalpha</code> function to create a sublist containing only letters, then create a set. Final length must be one or your condition isn't met.</p>
<pre><code>v="829383&&&@<<<<>><>GG"
print(len(set(filter(str.isalpha,v)))==1)
</code></pre>
| 1 | 2016-10-19T21:11:05Z | [
"python",
"string",
"python-3.x"
] |
Easier way to check if a string contains only one type of letter in python | 40,141,540 | <p>I have a string <code>'829383&&*&@<<<<>><>GG'</code>. I want a way to measure if a string has only one type of letter. For example the string above would return True, because it only has two Gs, but this string, <code>'829383&&*&@<<<<>><>GGAa'</code> would not. I've been iteratively going through the string having made it into an array. I was hoping someone knew an easier way. </p>
| 1 | 2016-10-19T21:06:36Z | 40,142,143 | <p>Jean-Francois's answer is what I'd actually use 99% of the time, but for cases where the string is <em>huge</em> you might want a solution that will return as soon as the second unique character is detected, instead of finishing processing:</p>
<pre><code>from future_builtins import map, filter # Only on Py2, to get lazy map/filter
from itertools import groupby, islice
from operator import itemgetter
# Remove non-alphas, then reduce consecutive identical alphabetic characters
# to a single instance of that character
lets = map(itemgetter(0), groupby(filter(str.isalpha, somestr)))
# Skip the first result, and if we find a second, then there was more than one
# in the string
if next(islice(lets, 1, None), None) is not None:
# There were at least two unique alphabetic characters
else:
# There were only 0-1 unique alphabetic characters
</code></pre>
<p>Distinguishing no alphabetic from one alphabetic could instead be done without <code>islice</code> as:</p>
<pre><code>atleastone = next(lets, None) is not None
multiple = next(lets, None) is not None
</code></pre>
| 0 | 2016-10-19T21:55:01Z | [
"python",
"string",
"python-3.x"
] |
Python regex : trimming special characters | 40,141,572 | <p>Is it possible to remove special characters using regex?</p>
<p>I'm attempting to trim:</p>
<pre><code>\n\t\t\t\t\t\t\t\t\t\tButte County High School\t\t\t\t\t\t\t\t\t
</code></pre>
<p>down to:</p>
<pre><code>Butte County High School
</code></pre>
<p>using </p>
<pre><code>regexform = re.sub("[A-Z]+[a-z]+\s*",'', schoolstring)
print regexform
</code></pre>
| 1 | 2016-10-19T21:09:07Z | 40,141,588 | <p>You do not need regex for this simple task. Use <a href="https://docs.python.org/2/library/string.html#string.lstrip" rel="nofollow"><code>string.strip()</code></a> instead. For example:</p>
<pre><code>>>> my_string = '\t\t\t\t\t\t\t\t\t\tButte County High School\t\t\t\t\t\t\t\t\t'
>>> my_string.strip()
'Butte County High School'
</code></pre>
<p>In case it is must to use <code>regex</code>, your expression should be:</p>
<pre><code>>>> re.sub('[^A-Za-z0-9]\s+', '', my_string)
'Butte County High School'
</code></pre>
<p>It matches a string of characters that are not letters or numbers.</p>
| 3 | 2016-10-19T21:10:19Z | [
"python",
"regex",
"expression"
] |
Python regex : trimming special characters | 40,141,572 | <p>Is it possible to remove special characters using regex?</p>
<p>I'm attempting to trim:</p>
<pre><code>\n\t\t\t\t\t\t\t\t\t\tButte County High School\t\t\t\t\t\t\t\t\t
</code></pre>
<p>down to:</p>
<pre><code>Butte County High School
</code></pre>
<p>using </p>
<pre><code>regexform = re.sub("[A-Z]+[a-z]+\s*",'', schoolstring)
print regexform
</code></pre>
| 1 | 2016-10-19T21:09:07Z | 40,141,636 | <p>Except you have reasons to want to use regex, you can remove all edge white space with <code>.strip()</code> function in python</p>
| 0 | 2016-10-19T21:14:17Z | [
"python",
"regex",
"expression"
] |
Python regex : trimming special characters | 40,141,572 | <p>Is it possible to remove special characters using regex?</p>
<p>I'm attempting to trim:</p>
<pre><code>\n\t\t\t\t\t\t\t\t\t\tButte County High School\t\t\t\t\t\t\t\t\t
</code></pre>
<p>down to:</p>
<pre><code>Butte County High School
</code></pre>
<p>using </p>
<pre><code>regexform = re.sub("[A-Z]+[a-z]+\s*",'', schoolstring)
print regexform
</code></pre>
| 1 | 2016-10-19T21:09:07Z | 40,141,638 | <p>If you're really set on using regular expressions:</p>
<pre><code>re.sub(r'^\s+|\s+$', '', schoolstring)
</code></pre>
<p>This will work for:</p>
<pre><code>' this is a test ' # multiple leading and trailing spaces
' this is a test ' # one leading and trailing space
'this is a test' # no leading or trailing spaces
'\t\tthis is a test\t\t' # leading or trailing whitespace characters
</code></pre>
<p>This expression one or more whitespace characters from the start <code>^\s+</code> of the string or <code>|</code> one or more whitespace characters from the end of the string <code>\s+$</code>.</p>
<p>However, <code>string.strip()</code> is simpler for removing leading and trailing space.</p>
| 1 | 2016-10-19T21:14:25Z | [
"python",
"regex",
"expression"
] |
Yes or No answer from user with Validation and restart option? | 40,141,660 | <p>(py) At the moment, the code below does not validate/output error messages when the user inputs something other than the two choices "y" and "n" because it's in a while loop. </p>
<pre><code>again2=input("Would you like to calculate another GTIN-8 code? Type 'y' for Yes and 'n' for No. ").lower() #**
while again2 == "y":
print("\nOK! Thanks for using this GTIN-8 calculator!\n\n")
restart2()
break #Break ends the while loop
restart2()
</code></pre>
<p>I'm struggling to think of ways that will allow me to respond with an output when they input neither of the choices given. For example:</p>
<pre><code>if again2 != "y" or "n"
print("Not a valid choice, try again")
#Here would be a statement that sends the program back to the line labelled with a **
</code></pre>
<p>So, when the user's input is not equal to "y" or "n" the program would return to the initial statement and ask the user to input again. Any ideas that still supports an efficient code with as little lines as possible? Thanks!</p>
| 0 | 2016-10-19T21:16:09Z | 40,141,714 | <pre><code>def get_choice(prompt="Enter y/n?",choices=["Y","y","n","N"],error="Invalid choice"):
while True:
result = input(prompt)
if result in choices: return result
print(error)
</code></pre>
<p>is probably a nice generic way to approach this problem</p>
<pre><code>result = get_choice("Enter A,B, or C:",choices=list("ABCabc"),error="Thats not A or B or C")
</code></pre>
<p>you could of coarse make it not case sensitive... or add other types of criteria (e.g. must be an integer between 26 and 88) </p>
| 1 | 2016-10-19T21:20:36Z | [
"python",
"validation",
"loops",
"while-loop",
"restart"
] |
Yes or No answer from user with Validation and restart option? | 40,141,660 | <p>(py) At the moment, the code below does not validate/output error messages when the user inputs something other than the two choices "y" and "n" because it's in a while loop. </p>
<pre><code>again2=input("Would you like to calculate another GTIN-8 code? Type 'y' for Yes and 'n' for No. ").lower() #**
while again2 == "y":
print("\nOK! Thanks for using this GTIN-8 calculator!\n\n")
restart2()
break #Break ends the while loop
restart2()
</code></pre>
<p>I'm struggling to think of ways that will allow me to respond with an output when they input neither of the choices given. For example:</p>
<pre><code>if again2 != "y" or "n"
print("Not a valid choice, try again")
#Here would be a statement that sends the program back to the line labelled with a **
</code></pre>
<p>So, when the user's input is not equal to "y" or "n" the program would return to the initial statement and ask the user to input again. Any ideas that still supports an efficient code with as little lines as possible? Thanks!</p>
| 0 | 2016-10-19T21:16:09Z | 40,141,720 | <p>A recursive solution:</p>
<pre><code>def get_input():
ans = input('Y/N? ') #Use raw_input in python2
if ans.lower() in ('y', 'n'):
return ans
else:
print('Please try again.')
return get_input()
</code></pre>
<p>If they're really stubborn this will fail when it reaches maximum recursion depth (~900 wrong answers)</p>
| 0 | 2016-10-19T21:21:20Z | [
"python",
"validation",
"loops",
"while-loop",
"restart"
] |
Design: Google OAuth using AngularJS and Flask | 40,141,705 | <p>I am building a web application using AngularJS on the frontend and Python with Flask on the server side. I am trying to implement the OpenID/OAuth login feature following the documentation available on <a href="https://developers.google.com/identity/protocols/OpenIDConnect" rel="nofollow">google developers site</a>. I began by building the server side code first(where everything worked fine when tested using Postman), and started to work on frontend. Now, I have a feeling that the design I followed for adding this feature is really bad. Below is the problem I am facing:</p>
<p>Following the Google OAuth documentation, I have setup my server side flow somewhat like this:</p>
<p><strong>gAuth</strong>:
It is a function in my Flask app that will be invoked by a GET request from Angular when the user clicks on the Google signIn button.</p>
<p>It sends a GET request to the Google authorization endpoint to fetch the authorization code. The response to this request has got a text field which has an HTML code that shows the google login page. I am returning this to Angular(because that's where this function has been invoked from). Then Angular renders this on the browser for the user to enter credentials. Once the user enters credentials and authorizes my application, Google sends the auth code to another function in my app <strong>requestToken</strong> using a GET request, because that is the redirect_URI I am using for the Google OAuth. At this point, I am completely cut from Angular. Now requestToken sends a POST request to token endpoint of Google using the auth code in order to exchange it for an id_token. Now requestToken has the id_token and does what it is supposed to do with it. </p>
<p>I am returning a value of '1' from the requestToken function, but that goes to the Google code, because that is where the request to requestToken came from. </p>
<p>Now, the problem is how can I let the frontend know that everything went fine with OAuth and user must be redirected to the homepage. I want the return value of requestToken to go to Angular. I want to ask if that is possible, but my commonsense says that it is not possible. But, I am wondering if there is a way by which I can send a request from Flask to Angular. Any help is much appreciated.</p>
| 0 | 2016-10-19T21:19:34Z | 40,141,944 | <p>I gave up with manual implementation. There is a ready to use lib: <a href="https://github.com/sahat/satellizer" rel="nofollow">Satellizer</a> as well as server implementation (for Python example see the docs).</p>
| 0 | 2016-10-19T21:39:05Z | [
"javascript",
"python",
"angularjs",
"google-app-engine",
"oauth"
] |
Sending Function as Argument to Another Function | 40,141,729 | <p>I have came across this logic:</p>
<pre><code>def f2(f):
def g(arg):
return 2 * f(arg)
return g
def f1(arg):
return arg + 1
f_2 = f2(f1)
print f_2(3)
</code></pre>
<p>From a first glance it may seem it is a very simple code.
But it takes some time to figure out what is going on here.
Sending a function as an argument to another function is unusual to me.
While it works I wonder if a technique like this should be avoided (since it does appear quite confusing at first). </p>
| 0 | 2016-10-19T21:22:00Z | 40,141,769 | <p>The passing of functions to other functions is a common idiom in so-called functional programming languages like LISP, Scheme, Haskell, etc. Python is sometimes referred to as a "multi-paradigm language" because it has some features of functional languages (as well as of imperative/structured and object-oriented languages). </p>
<p>So while it is considered an advanced technique, it is hardly uncommon to see it in Python. Python even has a language keyword (<code>lambda</code>) to let you define short anonymous functions "in line" when calling a function, so you don't have to give them a name and define them elsewhere. It also has built-in functions like <code>map</code>, <code>filter</code>, and <code>reduce</code>, which are explicitly designed to work with functions passed in to them; these are borrowed from the aforementioned functional languages. And a commonly-used language feature, decorators, is basically a function that takes a function and returns a function.</p>
| 2 | 2016-10-19T21:26:33Z | [
"python"
] |
Getting combinations back from memoized subset-sum algorithm? | 40,141,753 | <p>I've been working on a pretty basic subset sum problem. Given a sum (say, s=6) and the numbers ((1:s), so, [1,2,3,4,5]), I
had to find the total number of combinations that totalled s (so: [1,5], [2,4], [1,2,3]). It was quite easy to satisify the
requirements of the problem by doing a brute-force approach. For my own learning, I've been trying to understand how I can instead implement a memoizable algorithm that would allow me to calculate combinations for very large values of n (say, 500). Obviously, the brute-force approach becomes untenable quickly for values over 70 or so.</p>
<p>Digging around on the internet quite a bit, I already found an algorithm <a href="http://www.markandclick.com/advance.html#SubsetSum" rel="nofollow">here</a> that works quite well. This is the code I'm currently working with:</p>
<pre><code>def get_combos_wrapped():
cache = {}
def get_combos(numbers, idx, total, depth=0, which=''):
dstr = '\t' * depth
print("%scalled: idx=%s, total=%s %s" % (dstr, idx, total, which))
if (idx, total) in cache:
# print("cache hit: %s, %s" % (idx, total))
to_return = cache[(idx, total)]
del(cache[(idx, total)])
return to_return
depth += 1
if idx >= len(numbers):
to_return = 1 if total == 0 else 0
print("%sreturning %s" % (dstr, to_return))
return to_return
the_sum = get_combos(numbers, idx + 1, total, depth) \
+ get_combos(numbers, idx + 1, total - numbers[idx], depth)
print("%sreturning %s" % (dstr, the_sum))
cache[(idx, total)] = the_sum
return the_sum
return get_combos
</code></pre>
<p>Here's my problem... The algorithm is still completely mysterious to me -- I just know that it returns the right totals. I'm wondering if anyone can indulge my ignorance and offer insight into understanding 1) how this works, and 2) whether I would be able to use this algorithm to actually get back the unique number combinations given a value of s. The following is some output I hacked together to help me visualize the program flow for s=6, though unfortunately it hasn't really helped. Thank you very much for your help.</p>
<pre><code>called: idx=0, total=6
called: idx=1, total=6
called: idx=2, total=6
called: idx=3, total=6
called: idx=4, total=6
called: idx=5, total=6
returning 0
called: idx=5, total=1
returning 0
returning 0
called: idx=4, total=2
called: idx=5, total=2
returning 0
called: idx=5, total=-3
returning 0
returning 0
returning 0
called: idx=3, total=3
called: idx=4, total=3
called: idx=5, total=3
returning 0
called: idx=5, total=-2
returning 0
returning 0
called: idx=4, total=-1
called: idx=5, total=-1
returning 0
called: idx=5, total=-6
returning 0
returning 0
returning 0
returning 0
called: idx=2, total=4
called: idx=3, total=4
called: idx=4, total=4
called: idx=5, total=4
returning 0
called: idx=5, total=-1
returning 0
returning 0
called: idx=4, total=0
called: idx=5, total=0
returning 1
called: idx=5, total=-5
returning 0
returning 1
returning 1
called: idx=3, total=1
called: idx=4, total=1
called: idx=5, total=1
returning 0
called: idx=5, total=-4
returning 0
returning 0
called: idx=4, total=-3
called: idx=5, total=-3
returning 0
called: idx=5, total=-8
returning 0
returning 0
returning 0
returning 1
returning 1
called: idx=1, total=5
called: idx=2, total=5
called: idx=3, total=5
called: idx=4, total=5
called: idx=5, total=5
returning 0
called: idx=5, total=0
returning 1
returning 1
called: idx=4, total=1
returning 1
called: idx=3, total=2
called: idx=4, total=2
called: idx=4, total=-2
called: idx=5, total=-2
returning 0
called: idx=5, total=-7
returning 0
returning 0
returning 0
returning 1
called: idx=2, total=3
called: idx=3, total=3
called: idx=3, total=0
called: idx=4, total=0
called: idx=4, total=-4
called: idx=5, total=-4
returning 0
called: idx=5, total=-9
returning 0
returning 0
returning 1
returning 1
returning 2
returning 3
3
</code></pre>
| 0 | 2016-10-19T21:23:57Z | 40,142,157 | <p>You may simplify your problem using <a href="https://docs.python.org/2/library/itertools.html#itertools.combinations" rel="nofollow"><code>itertools.combinations()</code></a> as:</p>
<pre><code>>>> from itertools import combinations
>>> s = 6
>>> my_list = range(1, s)
# Value of 'my_list':
# [1, 2, 3, 4, 5]
>>> my_combinations = [combinations(my_list, i) for i in range(2, s)]
# Value of 'my_combinations' (in actual will be containg <combinations> objects):
# [[(1, 2), (1, 3), (1, 4), (1, 5), (2, 3), (2, 4), (2, 5), (3, 4), (3, 5), (4, 5)], [(1, 2, 3), (1, 2, 4), (1, 2, 5), (1, 3, 4), (1, 3, 5), (1, 4, 5), (2, 3, 4), (2, 3, 5), (2, 4, 5), (3, 4, 5)], [(1, 2, 3, 4), (1, 2, 3, 5), (1, 2, 4, 5), (1, 3, 4, 5), (2, 3, 4, 5)], [(1, 2, 3, 4, 5)]]
>>> my_required_set = [my_set for my_sublist in my_combinations for my_set in my_sublist if sum(my_set) == s]
>>> my_required_set
[(1, 5), (2, 4), (1, 2, 3)]
</code></pre>
| 0 | 2016-10-19T21:55:43Z | [
"python",
"algorithm",
"memoization",
"subset-sum"
] |
Django ImportError No module named x.settings | 40,141,828 | <p>I have the following structure:</p>
<pre><code>mysite
-> manage.py
-> mysite (again)
-> __init__.py
-> wsgi.py
-> settings.py
etc
-> myapp
-> __init__.py
-> myscript.py
-> models.py
etc
</code></pre>
<p>When I run a script from myapp (that does myapp-related things, putting stuff in a the database for example) i need to do </p>
<pre><code>import django
django.setup()
</code></pre>
<p>in order to be able to <code>from models import MyModel</code>. But if i do this in the myapp directory, I get:</p>
<pre><code>Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python27\lib\site-packages\django\__init__.py", line 22, in setup
configure_logging(settings.LOGGING_CONFIG, settings.LOGGING)
File "C:\Python27\lib\site-packages\django\conf\__init__.py", line 53, in __getattr__
self._setup(name)
File "C:\Python27\lib\site-packages\django\conf\__init__.py", line 41, in _setup
self._wrapped = Settings(settings_module)
File "C:\Python27\lib\site-packages\django\conf\__init__.py", line 97, in __init__
mod = importlib.import_module(self.SETTINGS_MODULE)
File "C:\Python27\lib\importlib\__init__.py", line 37, in import_module
__import__(name)
ImportError: No module named mysite.settings
</code></pre>
<p>Which I kind of understand since it's further up the directory tree and not in the same directory as e.g <code>manage.py</code> (the root I guess?). When I issue a python interpreter in mysite where <code>manage.py</code> is located, I dont get this error.</p>
<p>What should I do to be able to place my scripts in myapp and still be able to use <code>django.setup()</code> from that dir? </p>
| 0 | 2016-10-19T21:30:25Z | 40,141,935 | <p>You need to make sure the root of your project is in python path when you run the script. Something like this might help.</p>
<pre>
import os
import sys
projpath = os.path.dirname(__file__)
sys.path.append(os.path.join(projpath, '..'))
</pre>
| 0 | 2016-10-19T21:38:28Z | [
"python",
"django"
] |
How can I manipulate strings in a slice of a pandas MultiIndex | 40,141,856 | <p>I have a <code>MultiIndex</code> like this:</p>
<pre><code> metric
sensor variable side
foo Speed Left Left speed
Right Right speed
bar Speed Left Left_Speed
Right Right_Speed
baz Speed Left speed
foo Support Left Left support
Right Right support
bar Support Left Left_support
Right Right_support
baz Support Left support
</code></pre>
<p>I'm trying to apply a string mapping to a slice of this dataframe:</p>
<pre><code>df.loc['baz',:,'Left'].metric.map(lambda s: "Left_" + s)
</code></pre>
<p>How can I apply this map to just the <code>baz-Left</code> rows, and get back the resulting <code>DataFrame</code>?</p>
<pre><code> metric
sensor variable side
foo Speed Left Left speed
Right Right speed
bar Speed Left Left_Speed
Right Right_Speed
baz Speed Left Left_speed
foo Support Left Left support
Right Right support
bar Support Left Left_support
Right Right_support
baz Support Left Left_support
</code></pre>
| 2 | 2016-10-19T21:31:52Z | 40,142,490 | <p>I found the following method, but i think/hope there must be a more elegant way to achieve that:</p>
<pre><code>In [101]: index_saved = df.index
</code></pre>
<p>Let's sort index in order to get rid of <code>KeyError: 'MultiIndex Slicing requires the index to be fully lexsorted tuple len (3), lexsort depth (0)'</code> error:</p>
<pre><code>In [102]: df = df.sort_index()
In [103]: df
Out[103]:
metric
sensor variable side
bar Speed Left Left_Speed
Right Right_Speed
Support Left Left_support
Right Right_support
baz Speed Left speed
Support Left support
foo Speed Left Left speed
Right Right speed
Support Left Left support
Right Right support
In [119]: df.loc[pd.IndexSlice['baz', :, 'Left'], 'metric'] = \
...: 'AAA__' + df.loc[pd.IndexSlice['baz', :, 'Left'], 'metric']
In [120]: df
Out[120]:
metric
sensor variable side
bar Speed Left Left_Speed
Right Right_Speed
Support Left Left_support
Right Right_support
baz Speed Left AAA__speed
Support Left AAA__support
foo Speed Left Left speed
Right Right speed
Support Left Left support
Right Right support
</code></pre>
<p>set back old (saved) index:</p>
<pre><code>In [121]: df = df.reindex(index_saved)
In [122]: df
Out[122]:
metric
sensor variable side
foo Speed Left Left speed
Right Right speed
bar Speed Left Left_Speed
Right Right_Speed
baz Speed Left AAA__speed
foo Support Left Left support
Right Right support
bar Support Left Left_support
Right Right_support
baz Support Left AAA__support
</code></pre>
| 1 | 2016-10-19T22:23:15Z | [
"python",
"pandas"
] |
pandas groupby transform behaving differently with seemingly equivalent representations | 40,141,881 | <p>consider the <code>df</code></p>
<pre><code>df = pd.DataFrame(dict(A=['a', 'a'], B=[0, 1]))
</code></pre>
<p>I expected the following two formulations to be equivalent.</p>
<p><strong><em>formulation 1</em></strong> </p>
<pre><code>df.groupby('A').transform(np.mean)
</code></pre>
<p><a href="https://i.stack.imgur.com/euRkW.png" rel="nofollow"><img src="https://i.stack.imgur.com/euRkW.png" alt="enter image description here"></a></p>
<p><strong><em>formulation 2</em></strong></p>
<pre><code>df.groupby('A').transform(lambda x: np.mean(x))
</code></pre>
<p><a href="https://i.stack.imgur.com/18pe5.png" rel="nofollow"><img src="https://i.stack.imgur.com/18pe5.png" alt="enter image description here"></a></p>
<p>I'd consider the results from <strong><em>formulation 2</em></strong> incorrect. But before I go crying <em>bug</em> maybe someone has a rational explanation for it.</p>
| 4 | 2016-10-19T21:34:18Z | 40,142,095 | <p>It looks like a bug to me:</p>
<pre><code>In [19]: df.groupby('A').transform(lambda x: x.sum())
Out[19]:
B
0 1
1 1
In [20]: df.groupby('A').transform(lambda x: len(x))
Out[20]:
B
0 2
1 2
In [21]: df.groupby('A').transform(lambda x: x.sum()/len(x))
Out[21]:
B
0 0
1 0
</code></pre>
<p>PS Pandas version: 0.19.0</p>
| 3 | 2016-10-19T21:50:48Z | [
"python",
"pandas"
] |
How to do a substring using pandas or numpy | 40,141,895 | <p>I'm trying to do a substring on data from column "ORG". I only need the 2nd and 3rd character. So for 413 I only need 13. I've tried the following:</p>
<pre><code>Attempt 1: dr2['unit'] = dr2[['ORG']][1:2]
Attempt 2: dr2['unit'] = dr2[['ORG'].str[1:2]
Attempt 3: dr2['unit'] = dr2[['ORG'].str([1:2])
</code></pre>
<p>My dataframe:</p>
<pre><code> REGION ORG
90 4 413
91 4 413
92 4 413
93 5 503
94 5 503
95 5 503
96 5 503
97 5 504
98 5 504
99 1 117
100 1 117
101 1 117
102 1 117
103 1 117
104 1 117
105 1 117
106 3 3
107 3 3
108 3 3
109 3 3
</code></pre>
<p>Expected output:</p>
<pre><code> REGION ORG UNIT
90 4 413 13
91 4 413 13
92 4 413 13
93 5 503 03
94 5 503 03
95 5 503 03
96 5 503 03
97 5 504 04
98 5 504 04
99 1 117 17
100 1 117 17
101 1 117 17
102 1 117 17
103 1 117 17
104 1 117 17
105 1 117 17
106 3 3 03
107 3 3 03
108 3 3 03
109 3 3 03
</code></pre>
<p>thanks for any and all help!</p>
| 1 | 2016-10-19T21:35:05Z | 40,141,954 | <p>Your square braces are not matching and you can easily slice with <code>[-2:]</code>.</p>
<p><em>apply</em> <code>str.zfill</code> with a width of 2 to pad the items in the new series:</p>
<pre><code>>>> import pandas as pd
>>> ld = [{'REGION': '4', 'ORG': '413'}, {'REGION': '4', 'ORG': '414'}]
>>> df = pd.DataFrame(ld)
>>> df
ORG REGION
0 413 4
1 414 4
>>> df['UNIT'] = df['ORG'].str[-2:].apply(str.zfill, args=(2,))
>>> df
ORG REGION UNIT
0 413 4 13
1 414 4 14
2 3 4 03
</code></pre>
| 1 | 2016-10-19T21:40:24Z | [
"python",
"pandas",
"numpy"
] |
Efficiently summing outer product for 1D NumPy arrays | 40,142,004 | <p>I have a function of the form</p>
<p><a href="https://i.stack.imgur.com/MwLCs.gif" rel="nofollow"><img src="https://i.stack.imgur.com/MwLCs.gif" alt="enter image description here"></a></p>
<p>One way to implement this function in numpy is to assemble a matrix to sum over:</p>
<pre><code>y = a*b - np.sum(np.outer(a*b, b), axis=0)
</code></pre>
<p>Is there a better way to implement this function with numpy, one that doesn't involve creating an NxN array?</p>
| 1 | 2016-10-19T21:43:45Z | 40,142,158 | <p>You could use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.einsum.html" rel="nofollow"><code>np.einsum</code></a> -</p>
<pre><code>y = a*b - np.einsum('i,i,j->j',a,b,b)
</code></pre>
<p>We can also perform <code>a*b</code> and feed to <code>einsum</code> -</p>
<pre><code>y = a*b - np.einsum('i,j->j',a*b,b)
</code></pre>
<p>On the second approach, we can save some runtime by storing <code>a*b</code> and reusing.</p>
<p>Runtime test -</p>
<pre><code>In [253]: a = np.random.rand(4000)
In [254]: b = np.random.rand(4000)
In [255]: %timeit np.sum(np.outer(a*b, b), axis=0)
10 loops, best of 3: 105 ms per loop
In [256]: %timeit np.einsum('i,i,j->j',a,b,b)
10 loops, best of 3: 24.2 ms per loop
In [257]: %timeit np.einsum('i,j->j',a*b,b)
10 loops, best of 3: 21.9 ms per loop
</code></pre>
| 2 | 2016-10-19T21:55:43Z | [
"python",
"numpy",
"optimization"
] |
Pandas df to dictionary with values as python lists aggregated from a df column | 40,142,024 | <p>I have a pandas df containing 'features' for stocks, which looks like this: </p>
<p><a href="https://i.stack.imgur.com/fekQs.png" rel="nofollow"><img src="https://i.stack.imgur.com/fekQs.png" alt="features for stocks previous to training neural net"></a></p>
<p>I am now trying to create a dictionary with <strong>unique sector</strong> as <strong>key</strong>, and a <strong>python list of tickers</strong> for that unique sector as <strong>values</strong>, so I end up having something that looks like this:</p>
<pre><code>{'consumer_discretionary': ['AAP',
'AMZN',
'AN',
'AZO',
'BBBY',
'BBY',
'BWA',
'KMX',
'CCL',
'CBS',
'CHTR',
'CMG',
</code></pre>
<p>etc.</p>
<p>I could iterate over the pandas df rows to create the dictionary, but I prefer a more pythonic solution. Thus far, this code is a partial solution:</p>
<pre><code>df.set_index('sector')['ticker'].to_dict()
</code></pre>
<p>Any feedback is appreciated.</p>
<p><strong>UPDATE:</strong></p>
<p>The solution by @wrwrwr </p>
<pre><code>df.set_index('ticker').groupby('sector').groups
</code></pre>
<p>partially works, but it returns a <strong>pandas series</strong> as a the value, instead of a <strong>python list</strong>. Any ideas about how to transform the pandas series into a python list in the same line and w/o having to iterate the dictionary?</p>
| 1 | 2016-10-19T21:44:57Z | 40,142,613 | <p>Wouldn't <code>f.set_index('ticker').groupby('sector').groups</code> be what you want?</p>
<p>For example:</p>
<pre><code>f = DataFrame({
'ticker': ('t1', 't2', 't3'),
'sector': ('sa', 'sb', 'sb'),
'name': ('n1', 'n2', 'n3')})
groups = f.set_index('ticker').groupby('sector').groups
# {'sa': Index(['t1']), 'sb': Index(['t2', 't3'])}
</code></pre>
<p>To ensure that they have the type you want:</p>
<pre><code>{k: list(v) for k, v in f.set_index('ticker').groupby('sector').groups.items()}
</code></pre>
<p>or:</p>
<pre><code>f.set_index('ticker').groupby('sector').apply(lambda g: list(g.index)).to_dict()
</code></pre>
| 2 | 2016-10-19T22:34:49Z | [
"python",
"pandas",
"dictionary"
] |
How to fix "TypeError: len() of unsized object" | 40,142,166 | <p>I am getting:</p>
<p><strong>TypeError: len() of unsized object</strong></p>
<p>after running the following script:</p>
<pre><code>from numpy import *
v=array(input('Introduce un vector v: '))
u=array(input('Introduce un vector u: '))
nv= len(v)
nu= len(u)
diferenza= 0; i=0
if nv==nu:
while i<nv:
diferenza=diferenza + ((v[i+1]-u[i+1]))**2
modulo= sqrt(diferenza)
print('Distancia', v)
else:
print('Vectores de diferente dimensión')
</code></pre>
<p>How can I fix this?</p>
| -1 | 2016-10-19T21:56:19Z | 40,142,263 | <p>Use the arrays' <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.size.html" rel="nofollow"><code>size</code></a> attribute instead:</p>
<pre><code>nv = v.size
nu = u.size
</code></pre>
<hr>
<p>You also probably want to use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.fromstring.html#numpy.fromstring" rel="nofollow"><code>numpy.fromstring</code></a> to take and convert the input string into an array:</p>
<pre><code>>>> v = np.fromstring(input('enter the elements of the vector separated by comma: '), dtype=int, sep=',')
enter the elements of the vector separated by comma: 1, 2, 3
>>> v
array([1, 2, 3])
>>> len(v)
3
>>> v.size
3
</code></pre>
| 1 | 2016-10-19T22:02:47Z | [
"python",
"arrays",
"numpy"
] |
How to fix "TypeError: len() of unsized object" | 40,142,166 | <p>I am getting:</p>
<p><strong>TypeError: len() of unsized object</strong></p>
<p>after running the following script:</p>
<pre><code>from numpy import *
v=array(input('Introduce un vector v: '))
u=array(input('Introduce un vector u: '))
nv= len(v)
nu= len(u)
diferenza= 0; i=0
if nv==nu:
while i<nv:
diferenza=diferenza + ((v[i+1]-u[i+1]))**2
modulo= sqrt(diferenza)
print('Distancia', v)
else:
print('Vectores de diferente dimensión')
</code></pre>
<p>How can I fix this?</p>
| -1 | 2016-10-19T21:56:19Z | 40,142,305 | <p>The problem is that a <code>numpy</code>-<strong>scalar</strong> has no length. When you use <code>input</code> it returns a string (assuming Python3 here) and that's just converted to a numpy-string when you pass it to <code>numpy.array</code>:</p>
<pre><code>>>> import numpy as np
>>> np.array('abcdefg')
array('abcdefg',
dtype='<U7')
>>> len(np.array('abcdefg'))
TypeError
</code></pre>
<p>You need to parse it before you pass it to <code>numpy.array</code>. For example with <code>ast.literal_eval</code> (Thanks @PaulRooney for mentioning it):</p>
<pre><code>>>> import ast
>>> np.array(ast.literal_eval(input('Enter vector'))) # input "[1, 2, 3]"
array([1, 2, 3])
>>> len(_)
3
</code></pre>
<p>If you're dealing with multidimensional <code>array</code> you have to use <code>array.size</code> instead of <code>len</code>.</p>
| -2 | 2016-10-19T22:06:11Z | [
"python",
"arrays",
"numpy"
] |
errors with webdriver.Firefox() with selenium | 40,142,194 | <p>I am using python 3.5, firefox 45 (also tried 49) and selenium 3.0.1</p>
<p>I tried:</p>
<pre><code>from selenium import webdriver
from selenium.webdriver.common.keys import Keys
driver = webdriver.Firefox()
</code></pre>
<p>Then I got the error message:</p>
<pre><code>C:\Users\A\AppData\Local\Programs\Python\Python35\python.exe
C:/Users/A/Desktop/car/test.py
Traceback (most recent call last):
File "C:\Users\A\AppData\Local\Programs\Python\Python35\lib\site-packages\selenium\webdriver\common\service.py", line 64, in start
stdout=self.log_file, stderr=self.log_file)
File "C:\Users\A\AppData\Local\Programs\Python\Python35\lib\subprocess.py", line 950, in __init__
restore_signals, start_new_session)
File "C:\Users\A\AppData\Local\Programs\Python\Python35\lib\subprocess.py", line 1220, in _execute_child
startupinfo)
FileNotFoundError: [WinError 2] The system cannot find the file specified
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:/Users/A/Desktop/car/test.py", line 4, in <module>
driver = webdriver.Firefox()
File "C:\Users\A\AppData\Local\Programs\Python\Python35\lib\site-packages\selenium\webdriver\firefox\webdriver.py", line 135, in __init__
self.service.start()
File "C:\Users\A\AppData\Local\Programs\Python\Python35\lib\site-packages\selenium\webdriver\common\service.py", line 71, in start
os.path.basename(self.path), self.start_error_message)
selenium.common.exceptions.WebDriverException: Message: 'geckodriver' executable needs to be in PATH.
Exception ignored in: <bound method Service.__del__ of <selenium.webdriver.firefox.service.Service object at 0x0000000000EB8278>>
Traceback (most recent call last):
File "C:\Users\A\AppData\Local\Programs\Python\Python35\lib\site-packages\selenium\webdriver\common\service.py", line 163, in __del__
self.stop()
File "C:\Users\A\AppData\Local\Programs\Python\Python35\lib\site-packages\selenium\webdriver\common\service.py", line 135, in stop
if self.process is None:
AttributeError: 'Service' object has no attribute 'process'
</code></pre>
<p>What can I do? Any help is much appreciated!</p>
| 1 | 2016-10-19T21:58:32Z | 40,143,317 | <p>If you are using firefox ver >47.0.1 you need to have the <code>[geckodriver][1]</code> executable in your system path. For earlier versions you want to turn marionette off. You can to so like this:</p>
<pre><code>from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
capabilities = DesiredCapabilities.FIREFOX.copy()
capabilities['marionette'] = False
driver = webdriver.Firefox(capabilities=capabilities)
</code></pre>
| 0 | 2016-10-19T23:50:04Z | [
"python",
"selenium",
"firefox"
] |
Numbers separated by spaces in txt file into python list | 40,142,236 | <p>I am trying to convert a txt file containing lines of numbers separated by spaces into numbers separated by commas in lists, where each line is a new list of these numbers using Python 3.</p>
<p>E.g. txt file contains </p>
<blockquote>
<p>1 2 3 4 5</p>
<p>6 7 8 9 10</p>
</blockquote>
<p>and I want this in python:</p>
<pre><code>[1,2,3,4,5]
[6,7,8,9,10]
</code></pre>
<p>I can't seem to find a good solution, I used numpy and obtained the list of lists but not comma separated, e.g.:
<code>[[1 2 3 4 5],[6 7 8 9 10]]</code></p>
<p>Here is the example code I've used that doesn't quite work:</p>
<pre><code>import numpy as np
mymatrix = np.loadtxt('file')
</code></pre>
<p>Grateful for any input! (ps I'm a beginner but want to use the lists in a programme I am developing)</p>
| -3 | 2016-10-19T22:01:05Z | 40,142,467 | <p>Following uses plain Python 3 (without NumPy)</p>
<pre><code># open file
with open('file.txt') as fp:
# 1. iterate over file line-by-line
# 2. strip line of newline symbols
# 3. split line by spaces into list (of number strings)
# 4. convert number substrings to int values
# 5. convert map object to list
data = [list(map(int, line.strip().split(' '))) for line in fp]
</code></pre>
<p>This provides the result you're looking for:</p>
<pre><code>>>> with open('data.txt') as fp:
... data = [list(map(int, line.strip().split(' '))) for line in fp]
...
>>> print(data)
[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]
</code></pre>
| 0 | 2016-10-19T22:21:22Z | [
"python"
] |
Build a single list of element from bi-dimensional array list | 40,142,259 | <p>I'm totally noob to python so please forgive my mistake and lack of vocabulary. Long Story Short, I have the following list of array :</p>
<pre><code>[url1, data1][url2, data2][url3, data3]etc...
</code></pre>
<p>I want to build a simple list of element by only keeping the url. So I'm doing this :</p>
<pre><code> if results:
for row in results.get('rows'):
data.append(row[:1])
print data
</code></pre>
<p>for this result:</p>
<pre><code>[[url1][url2][url3]etc...]
</code></pre>
<p>However I would like to have something like this :</p>
<pre><code>[[url1, url2, url3,etc...]
</code></pre>
<p>I've imported numpy and tried this but doesn't work :</p>
<pre><code>np.array(data).tolist()
</code></pre>
<p>Any help ? </p>
<p>thanks.</p>
| 0 | 2016-10-19T22:02:40Z | 40,142,433 | <p>I'm bad at python but I think like this
when you result.get('rows'):
row is [url1] not url1
Why don't you try extend?
Sorry about my silly English ( I'm bat at English too)</p>
| -1 | 2016-10-19T22:18:29Z | [
"python",
"arrays"
] |
Build a single list of element from bi-dimensional array list | 40,142,259 | <p>I'm totally noob to python so please forgive my mistake and lack of vocabulary. Long Story Short, I have the following list of array :</p>
<pre><code>[url1, data1][url2, data2][url3, data3]etc...
</code></pre>
<p>I want to build a simple list of element by only keeping the url. So I'm doing this :</p>
<pre><code> if results:
for row in results.get('rows'):
data.append(row[:1])
print data
</code></pre>
<p>for this result:</p>
<pre><code>[[url1][url2][url3]etc...]
</code></pre>
<p>However I would like to have something like this :</p>
<pre><code>[[url1, url2, url3,etc...]
</code></pre>
<p>I've imported numpy and tried this but doesn't work :</p>
<pre><code>np.array(data).tolist()
</code></pre>
<p>Any help ? </p>
<p>thanks.</p>
| 0 | 2016-10-19T22:02:40Z | 40,142,482 | <p>If you just want the <code>url</code>, and your data is basically a list of lists then you can just use the <code>index</code> number, in this case <code>[0]</code> as url is the 1st element in a nested list</p>
<pre><code>l = [['url1', 'data1'],['url2', 'data2'],['url3', 'data3']]
endlist = []
for i in l:
endlist.append(i[0])
print endlist
</code></pre>
<p>Output:</p>
<pre><code>['url1', 'url2', 'url3']
</code></pre>
<p>However, make sure how your data is structured. A list of lists looks like <code>[[],[],[]]</code>, where each nested list is seperated by a <code>,</code> (comma) which is absent in the example you posted. </p>
| 1 | 2016-10-19T22:22:50Z | [
"python",
"arrays"
] |
Build a single list of element from bi-dimensional array list | 40,142,259 | <p>I'm totally noob to python so please forgive my mistake and lack of vocabulary. Long Story Short, I have the following list of array :</p>
<pre><code>[url1, data1][url2, data2][url3, data3]etc...
</code></pre>
<p>I want to build a simple list of element by only keeping the url. So I'm doing this :</p>
<pre><code> if results:
for row in results.get('rows'):
data.append(row[:1])
print data
</code></pre>
<p>for this result:</p>
<pre><code>[[url1][url2][url3]etc...]
</code></pre>
<p>However I would like to have something like this :</p>
<pre><code>[[url1, url2, url3,etc...]
</code></pre>
<p>I've imported numpy and tried this but doesn't work :</p>
<pre><code>np.array(data).tolist()
</code></pre>
<p>Any help ? </p>
<p>thanks.</p>
| 0 | 2016-10-19T22:02:40Z | 40,142,487 | <p>If I understood you correctly, you need this:</p>
<pre><code>results = [[url_1, data_1], [url_2, data_2], ...]
urls = list()
for r in results:
# r = [url_i, data_i]
urls.append(r[0])
</code></pre>
| 1 | 2016-10-19T22:23:02Z | [
"python",
"arrays"
] |
Why to use Lambda to send Function as Argument to Another Function | 40,142,302 | <p>While digging into <code>lambda</code> I defined this code below:</p>
<pre><code>def f2(number, lambda_function):
return lambda_function(number)
def f1(number):
return f2(number, lambda x: x*2)
number = 2
print f1(number)
</code></pre>
<p>While I do agree the code like this looks pretty cool I wonder why wouldn't I just put it down using a more traditional approach, like so:</p>
<pre><code>def f1(number):
return number*2
number = 2
print f1(number)
</code></pre>
<p>I understand that some languages rely on the functional programming more than Python. But in Python I end up with less lines and more readable friendly code if I just avoid <code>lambda</code> and the function programming tricks. Can the code above be modified to illustrate a situation when a task could not be completed without using <code>lambda</code>? What is the purpose of <code>lambda</code> in Python? Can you show me the example of where <code>lambda</code> really "shines"? May be an example where the use of <code>lambda</code> simplified the code?</p>
| 1 | 2016-10-19T22:05:58Z | 40,142,356 | <p><a href="https://docs.python.org/3/tutorial/controlflow.html#lambda-expressions" rel="nofollow"><code>lambda</code></a> functions work like normal function but are used in cases where they will be executed just once. Then, why to create the message body and define the function? For example, sorting the list of tuples:</p>
<pre><code>>>> my_list = [(1, 3) , (4, 8), (2, 3), (1, 6)]
>>> my_list.sort(key=lambda x: (x[0], -x[1]))
>>> my_list
[(1, 6), (1, 3), (2, 3), (4, 8)]
</code></pre>
<p>Here, I am sorting <code>my_list</code> in increasing order of index <code>0</code> and then decreasing order of index <code>1</code>. But <code>list.sort()</code> accepts value of <code>key</code> as function. Instead of defining the function and then pass that function over here, it is cleaner to make a <code>lambda</code> call within it. </p>
<p>Since these can be written as an expression, they are termed as <a href="https://docs.python.org/3/tutorial/controlflow.html#lambda-expressions" rel="nofollow"><code>Lambda Expression</code></a> in document, instead of <em>Lambda Function</em>.</p>
<p>Also read: <a href="http://stackoverflow.com/questions/890128/why-are-python-lambdas-useful">Why are Python lambdas useful?</a></p>
<p>In the example that you have given, I do not think that using <code>lambda</code> there is any useful.</p>
| 3 | 2016-10-19T22:11:17Z | [
"python"
] |
How to split files according to a field and edit content | 40,142,380 | <p>I am not sure if I can do this using unix commands or I need a more complicated code, like python.</p>
<p>I have a big input file with 3 columns - id, different sequences (second column) grouped in different groups (3rd column).</p>
<pre><code>Seq1 MVRWNARGQPVKEASQVFVSYIGVINCREVPISMEN Group1
Seq2 PSLFIAGWLFVSTGLRPNEYFTESRQGIPLITDRFDSLEQLDEFSRSF Group1
Seq3 HQAPAPAPTVISPPAPPTDTTLNLNGAPSNHLQGGNIWTTIGFAITVFLAVTGYSF Group20
</code></pre>
<p>I would like:
split this file according the group id, and create separate files for each group; edit the info in each file, adding a ">" sign in the beginning of the id; and then create a new row for the sequence</p>
<pre><code>Group1.txt file
>Seq1
MVRWNARGQPVKEASQVFVSYIGVINCREVPISMEN
>Seq2
PSLFIAGWLFVSTGLRPNEYFTESRQGIPLITDRFDSLEQLDEFSRSF
Group20.txt file
>Seq3
HQAPAPAPTVISPPAPPTDTTLNLNGAPSNHLQGGNIWTTIGFAITVFLAVTGYSF
</code></pre>
<p>How can I do that? </p>
| 0 | 2016-10-19T22:13:40Z | 40,142,525 | <p>This shell script should do the trick:</p>
<pre><code>#!/usr/bin/env bash
filename="data.txt"
while read line; do
id=$(echo "${line}" | awk '{print $1}')
sequence=$(echo "${line}" | awk '{print $2}')
group=$(echo "${line}" | awk '{print $3}')
printf ">${id}\n${sequence}\n" >> "${group}.txt"
done < "${filename}"
</code></pre>
<p>where <code>data.txt</code> is the name of the file containing the original data.</p>
<p>Importantly, the Group-files should not exist prior to running the script.</p>
| 0 | 2016-10-19T22:26:55Z | [
"python",
"unix",
"split"
] |
How to split files according to a field and edit content | 40,142,380 | <p>I am not sure if I can do this using unix commands or I need a more complicated code, like python.</p>
<p>I have a big input file with 3 columns - id, different sequences (second column) grouped in different groups (3rd column).</p>
<pre><code>Seq1 MVRWNARGQPVKEASQVFVSYIGVINCREVPISMEN Group1
Seq2 PSLFIAGWLFVSTGLRPNEYFTESRQGIPLITDRFDSLEQLDEFSRSF Group1
Seq3 HQAPAPAPTVISPPAPPTDTTLNLNGAPSNHLQGGNIWTTIGFAITVFLAVTGYSF Group20
</code></pre>
<p>I would like:
split this file according the group id, and create separate files for each group; edit the info in each file, adding a ">" sign in the beginning of the id; and then create a new row for the sequence</p>
<pre><code>Group1.txt file
>Seq1
MVRWNARGQPVKEASQVFVSYIGVINCREVPISMEN
>Seq2
PSLFIAGWLFVSTGLRPNEYFTESRQGIPLITDRFDSLEQLDEFSRSF
Group20.txt file
>Seq3
HQAPAPAPTVISPPAPPTDTTLNLNGAPSNHLQGGNIWTTIGFAITVFLAVTGYSF
</code></pre>
<p>How can I do that? </p>
| 0 | 2016-10-19T22:13:40Z | 40,142,998 | <p>AWK will do the trick:</p>
<pre><code>awk '{ print ">"$1 "\n" $2 >> $3".txt"}' input.txt
</code></pre>
| 0 | 2016-10-19T23:15:05Z | [
"python",
"unix",
"split"
] |
Recursive functions : Inversing word | 40,142,476 | <p>I'm trying to make a simple function that inverses a string using recursion.</p>
<p>this is what i tried : </p>
<pre><code> def inverse(ch):
if ch=='' :
return ''
else:
return ch[len(ch)]+inverse(ch[1:len(ch)-1])
print inverse('hello')
</code></pre>
<p>And this is what i get : </p>
<blockquote>
<p>line 13, in inverse
return ch[len(ch)]+inverse(ch[1:len(ch)-1]) IndexError: string index out of range</p>
</blockquote>
| 1 | 2016-10-19T22:21:57Z | 40,142,510 | <p>Check this:</p>
<pre><code>ch[len(ch)-1]+inverse(ch[0:len(ch)-1])
</code></pre>
| 1 | 2016-10-19T22:24:59Z | [
"python",
"recursion"
] |
Recursive functions : Inversing word | 40,142,476 | <p>I'm trying to make a simple function that inverses a string using recursion.</p>
<p>this is what i tried : </p>
<pre><code> def inverse(ch):
if ch=='' :
return ''
else:
return ch[len(ch)]+inverse(ch[1:len(ch)-1])
print inverse('hello')
</code></pre>
<p>And this is what i get : </p>
<blockquote>
<p>line 13, in inverse
return ch[len(ch)]+inverse(ch[1:len(ch)-1]) IndexError: string index out of range</p>
</blockquote>
| 1 | 2016-10-19T22:21:57Z | 40,142,514 | <p>You're indexing the string at its length, but remember that indexing is zero based so you'll have to slice at length minus 1 which is the maximum index you can safely use.</p>
<p>You can however choose to be oblivious of the length by using <code>[-1]</code> to index the last item:</p>
<pre><code>def inverse(ch):
if ch=='' :
return ''
else:
return ch[-1]+inverse(ch[:-1])
print inverse('hello')
# olleh
</code></pre>
<p>And you also probably want to keep in mind that slicing with <code>[::-1]</code> provides the same result as your recursive function.</p>
| 3 | 2016-10-19T22:25:06Z | [
"python",
"recursion"
] |