title stringlengths 10 172 | question_id int64 469 40.1M | question_body stringlengths 22 48.2k | question_score int64 -44 5.52k | question_date stringlengths 20 20 | answer_id int64 497 40.1M | answer_body stringlengths 18 33.9k | answer_score int64 -38 8.38k | answer_date stringlengths 20 20 | tags listlengths 1 5 |
|---|---|---|---|---|---|---|---|---|---|
What is the quickest way to ensure a specific column is last (or first) in a dataframe | 38,601,841 | <p>given <code>df</code></p>
<pre><code>df = pd.DataFrame(np.arange(8).reshape(2, 4), columns=list('abcd'))
</code></pre>
<p><a href="http://i.stack.imgur.com/UXlIN.png" rel="nofollow"><img src="http://i.stack.imgur.com/UXlIN.png" alt="enter image description here"></a></p>
<p>Suppose I need column <code>'b'</code> to be at the end. I could do:</p>
<pre><code>df[['a', 'c', 'd', 'b']]
</code></pre>
<p><a href="http://i.stack.imgur.com/miBss.png" rel="nofollow"><img src="http://i.stack.imgur.com/miBss.png" alt="enter image description here"></a></p>
<p>But what is the most efficient way to ensure that a given column is at the end?</p>
<p>This is what I've been going with. What would others do?</p>
<pre><code>def put_me_last(df, column):
return pd.concat([df.drop(column, axis=1), df[column]], axis=1)
put_me_last(df, 'b')
</code></pre>
<p><a href="http://i.stack.imgur.com/miBss.png" rel="nofollow"><img src="http://i.stack.imgur.com/miBss.png" alt="enter image description here"></a></p>
<hr>
<h3>Timing Results</h3>
<p><strong>conclusion</strong>
mfripp is the winner. Seems as if <code>reindex_axis</code> is a large efficiency gain over <code>[]</code>. That is really good info.</p>
<p><a href="http://i.stack.imgur.com/C8T6N.png" rel="nofollow"><img src="http://i.stack.imgur.com/C8T6N.png" alt="enter image description here"></a></p>
<p><strong>code</strong></p>
<pre><code>from string import lowercase
df_small = pd.DataFrame(np.arange(8).reshape(2, 4), columns=list('abcd'))
df_large = pd.DataFrame(np.arange(1000000).reshape(10000, 100),
columns=pd.MultiIndex.from_product([list(lowercase[:-1]), ['One', 'Two', 'Three', 'Four']]))
def pir1(df, column):
return pd.concat([df.drop(column, axis=1), df[column]], axis=1)
def pir2(df, column):
if df.columns[-1] == column:
return df
else:
pos = df.columns.values.__eq__('b').argmax()
return df[np.roll(df.columns, len(df.columns) - 1 - pos)]
def pir3(df, column):
if df.columns[-1] == column:
return df
else:
pos = df.columns.values.__eq__('b').argmax()
cols = df.columns.values
np.concatenate([cols[:pos], cols[1+pos:], cols[[pos]]])
return df[np.concatenate([cols[:pos], cols[1+pos:], cols[[pos]]])]
def pir4(df, column):
if df.columns[-1] == column:
return df
else:
return df[np.roll(df.columns.drop(column).insert(0, column), -1)]
def carsten1(df, column):
cols = list(df)
if cols[-1] == column:
return df
else:
return pd.concat([df.drop(column, axis=1), df[column]], axis=1)
def carsten2(df, column):
cols = list(df)
if cols[-1] == column:
return df
else:
idx = cols.index(column)
new_cols = cols[:idx] + cols[idx + 1:] + [column]
return df[new_cols]
def mfripp1(df, column):
new_cols = [c for c in df.columns if c != column] + [column]
return df[new_cols]
def mfripp2(df, column):
new_cols = [c for c in df.columns if c != column] + [column]
return df.reindex_axis(new_cols, axis='columns', copy=False)
def ptrj1(df, column):
return df.reindex(columns=df.columns.drop(column).append(pd.Index([column])))
def shivsn1(df, column):
column_list=list(df)
column_list.remove(column)
column_list.append(column)
return df[column_list]
def merlin1(df, column):
return df[df.columns.drop(["b"]).insert(99999, 'b')]
list_of_funcs = [pir1, pir2, pir3, pir4, carsten1, carsten2, mfripp1, mfripp2, ptrj1, shivsn1]
def test_pml(df, pml):
for c in df.columns:
pml(df, c)
summary = pd.DataFrame([], [f.__name__ for f in list_of_funcs], ['Small', 'Large'])
for f in list_of_funcs:
summary.at[f.__name__, 'Small'] = timeit(lambda: test_pml(df_small, f), number=100)
summary.at[f.__name__, 'Large'] = timeit(lambda: test_pml(df_large, f), number=10)
</code></pre>
| 3 | 2016-07-27T00:18:38Z | 38,602,096 | <p>I would rearrange the list of columns, rather than removing and appending one of them:</p>
<pre><code>import pandas as pd
import numpy as np
df = pd.DataFrame(np.arange(8).reshape(2, 4), columns=list('abcd'))
def put_me_last(df, column):
return pd.concat([df.drop(column, axis=1), df[column]], axis=1)
def put_me_last_fast(df, column):
new_cols = [c for c in df.columns if c != column] + [column]
return df[new_cols]
def put_me_last_faster(df, column):
new_cols = [c for c in df.columns if c != column] + [column]
return df.reindex_axis(new_cols, axis='columns', copy=False)
</code></pre>
<p>Timings (in iPython):</p>
<pre><code>%timeit put_me_last(df, 'b')
# 1000 loops, best of 3: 741 µs per loop
%timeit put_me_last_fast(df, 'b')
# 1000 loops, best of 3: 295 µs per loop
%timeit put_me_last_faster(df, 'b')
# 1000 loops, best of 3: 239 µs per loop
%timeit put_me_last_faster(df, 'd') # not changing order
# 1000 loops, best of 3: 125 µs per loop
</code></pre>
<p>Note: you could use the line below to define new_cols, but it's about 80x slower than the one used above (2 µs vs 160 µs)</p>
<pre><code>new_cols = df.columns.drop(column).insert(-1, column)
</code></pre>
<p>Also note: if you often try to move a column to the end that is already there, you can cut the time for those cases to below 1 µs by adding this, as noted by @Carsten:</p>
<pre><code>if df.columns[-1] == column:
return df
</code></pre>
| 3 | 2016-07-27T00:57:32Z | [
"python",
"pandas"
] |
What is the quickest way to ensure a specific column is last (or first) in a dataframe | 38,601,841 | <p>given <code>df</code></p>
<pre><code>df = pd.DataFrame(np.arange(8).reshape(2, 4), columns=list('abcd'))
</code></pre>
<p><a href="http://i.stack.imgur.com/UXlIN.png" rel="nofollow"><img src="http://i.stack.imgur.com/UXlIN.png" alt="enter image description here"></a></p>
<p>Suppose I need column <code>'b'</code> to be at the end. I could do:</p>
<pre><code>df[['a', 'c', 'd', 'b']]
</code></pre>
<p><a href="http://i.stack.imgur.com/miBss.png" rel="nofollow"><img src="http://i.stack.imgur.com/miBss.png" alt="enter image description here"></a></p>
<p>But what is the most efficient way to ensure that a given column is at the end?</p>
<p>This is what I've been going with. What would others do?</p>
<pre><code>def put_me_last(df, column):
return pd.concat([df.drop(column, axis=1), df[column]], axis=1)
put_me_last(df, 'b')
</code></pre>
<p><a href="http://i.stack.imgur.com/miBss.png" rel="nofollow"><img src="http://i.stack.imgur.com/miBss.png" alt="enter image description here"></a></p>
<hr>
<h3>Timing Results</h3>
<p><strong>conclusion</strong>
mfripp is the winner. Seems as if <code>reindex_axis</code> is a large efficiency gain over <code>[]</code>. That is really good info.</p>
<p><a href="http://i.stack.imgur.com/C8T6N.png" rel="nofollow"><img src="http://i.stack.imgur.com/C8T6N.png" alt="enter image description here"></a></p>
<p><strong>code</strong></p>
<pre><code>from string import lowercase
df_small = pd.DataFrame(np.arange(8).reshape(2, 4), columns=list('abcd'))
df_large = pd.DataFrame(np.arange(1000000).reshape(10000, 100),
columns=pd.MultiIndex.from_product([list(lowercase[:-1]), ['One', 'Two', 'Three', 'Four']]))
def pir1(df, column):
return pd.concat([df.drop(column, axis=1), df[column]], axis=1)
def pir2(df, column):
if df.columns[-1] == column:
return df
else:
pos = df.columns.values.__eq__('b').argmax()
return df[np.roll(df.columns, len(df.columns) - 1 - pos)]
def pir3(df, column):
if df.columns[-1] == column:
return df
else:
pos = df.columns.values.__eq__('b').argmax()
cols = df.columns.values
np.concatenate([cols[:pos], cols[1+pos:], cols[[pos]]])
return df[np.concatenate([cols[:pos], cols[1+pos:], cols[[pos]]])]
def pir4(df, column):
if df.columns[-1] == column:
return df
else:
return df[np.roll(df.columns.drop(column).insert(0, column), -1)]
def carsten1(df, column):
cols = list(df)
if cols[-1] == column:
return df
else:
return pd.concat([df.drop(column, axis=1), df[column]], axis=1)
def carsten2(df, column):
cols = list(df)
if cols[-1] == column:
return df
else:
idx = cols.index(column)
new_cols = cols[:idx] + cols[idx + 1:] + [column]
return df[new_cols]
def mfripp1(df, column):
new_cols = [c for c in df.columns if c != column] + [column]
return df[new_cols]
def mfripp2(df, column):
new_cols = [c for c in df.columns if c != column] + [column]
return df.reindex_axis(new_cols, axis='columns', copy=False)
def ptrj1(df, column):
return df.reindex(columns=df.columns.drop(column).append(pd.Index([column])))
def shivsn1(df, column):
column_list=list(df)
column_list.remove(column)
column_list.append(column)
return df[column_list]
def merlin1(df, column):
return df[df.columns.drop(["b"]).insert(99999, 'b')]
list_of_funcs = [pir1, pir2, pir3, pir4, carsten1, carsten2, mfripp1, mfripp2, ptrj1, shivsn1]
def test_pml(df, pml):
for c in df.columns:
pml(df, c)
summary = pd.DataFrame([], [f.__name__ for f in list_of_funcs], ['Small', 'Large'])
for f in list_of_funcs:
summary.at[f.__name__, 'Small'] = timeit(lambda: test_pml(df_small, f), number=100)
summary.at[f.__name__, 'Large'] = timeit(lambda: test_pml(df_large, f), number=10)
</code></pre>
| 3 | 2016-07-27T00:18:38Z | 38,602,109 | <p>How about this one:</p>
<pre><code>df.reindex(columns=df.columns.drop(col).append(pd.Index([col])))
</code></pre>
<p>(<code>.append([col])</code> doesn't work - might be a bug. <strong>Edit</strong>: use of <code>.append(pd.Index([col])</code> is probably the safest option in append.)</p>
<p>Comment on testing: If you plan a test with <code>timeit</code>, try running it on a large df (like 1e4 rows or more) and probably with <code>-n1 -r1</code> to prevent caching.</p>
| 2 | 2016-07-27T00:59:12Z | [
"python",
"pandas"
] |
What is the quickest way to ensure a specific column is last (or first) in a dataframe | 38,601,841 | <p>given <code>df</code></p>
<pre><code>df = pd.DataFrame(np.arange(8).reshape(2, 4), columns=list('abcd'))
</code></pre>
<p><a href="http://i.stack.imgur.com/UXlIN.png" rel="nofollow"><img src="http://i.stack.imgur.com/UXlIN.png" alt="enter image description here"></a></p>
<p>Suppose I need column <code>'b'</code> to be at the end. I could do:</p>
<pre><code>df[['a', 'c', 'd', 'b']]
</code></pre>
<p><a href="http://i.stack.imgur.com/miBss.png" rel="nofollow"><img src="http://i.stack.imgur.com/miBss.png" alt="enter image description here"></a></p>
<p>But what is the most efficient way to ensure that a given column is at the end?</p>
<p>This is what I've been going with. What would others do?</p>
<pre><code>def put_me_last(df, column):
return pd.concat([df.drop(column, axis=1), df[column]], axis=1)
put_me_last(df, 'b')
</code></pre>
<p><a href="http://i.stack.imgur.com/miBss.png" rel="nofollow"><img src="http://i.stack.imgur.com/miBss.png" alt="enter image description here"></a></p>
<hr>
<h3>Timing Results</h3>
<p><strong>conclusion</strong>
mfripp is the winner. Seems as if <code>reindex_axis</code> is a large efficiency gain over <code>[]</code>. That is really good info.</p>
<p><a href="http://i.stack.imgur.com/C8T6N.png" rel="nofollow"><img src="http://i.stack.imgur.com/C8T6N.png" alt="enter image description here"></a></p>
<p><strong>code</strong></p>
<pre><code>from string import lowercase
df_small = pd.DataFrame(np.arange(8).reshape(2, 4), columns=list('abcd'))
df_large = pd.DataFrame(np.arange(1000000).reshape(10000, 100),
columns=pd.MultiIndex.from_product([list(lowercase[:-1]), ['One', 'Two', 'Three', 'Four']]))
def pir1(df, column):
return pd.concat([df.drop(column, axis=1), df[column]], axis=1)
def pir2(df, column):
if df.columns[-1] == column:
return df
else:
pos = df.columns.values.__eq__('b').argmax()
return df[np.roll(df.columns, len(df.columns) - 1 - pos)]
def pir3(df, column):
if df.columns[-1] == column:
return df
else:
pos = df.columns.values.__eq__('b').argmax()
cols = df.columns.values
np.concatenate([cols[:pos], cols[1+pos:], cols[[pos]]])
return df[np.concatenate([cols[:pos], cols[1+pos:], cols[[pos]]])]
def pir4(df, column):
if df.columns[-1] == column:
return df
else:
return df[np.roll(df.columns.drop(column).insert(0, column), -1)]
def carsten1(df, column):
cols = list(df)
if cols[-1] == column:
return df
else:
return pd.concat([df.drop(column, axis=1), df[column]], axis=1)
def carsten2(df, column):
cols = list(df)
if cols[-1] == column:
return df
else:
idx = cols.index(column)
new_cols = cols[:idx] + cols[idx + 1:] + [column]
return df[new_cols]
def mfripp1(df, column):
new_cols = [c for c in df.columns if c != column] + [column]
return df[new_cols]
def mfripp2(df, column):
new_cols = [c for c in df.columns if c != column] + [column]
return df.reindex_axis(new_cols, axis='columns', copy=False)
def ptrj1(df, column):
return df.reindex(columns=df.columns.drop(column).append(pd.Index([column])))
def shivsn1(df, column):
column_list=list(df)
column_list.remove(column)
column_list.append(column)
return df[column_list]
def merlin1(df, column):
return df[df.columns.drop(["b"]).insert(99999, 'b')]
list_of_funcs = [pir1, pir2, pir3, pir4, carsten1, carsten2, mfripp1, mfripp2, ptrj1, shivsn1]
def test_pml(df, pml):
for c in df.columns:
pml(df, c)
summary = pd.DataFrame([], [f.__name__ for f in list_of_funcs], ['Small', 'Large'])
for f in list_of_funcs:
summary.at[f.__name__, 'Small'] = timeit(lambda: test_pml(df_small, f), number=100)
summary.at[f.__name__, 'Large'] = timeit(lambda: test_pml(df_large, f), number=10)
</code></pre>
| 3 | 2016-07-27T00:18:38Z | 38,602,601 | <p>Starting with this:</p>
<pre><code> df.columns
Index([u'a', u'b', u'c', u'd'], dtype='object')
</code></pre>
<p><strong>Dont do this, looks like a bug.</strong> </p>
<pre><code> df.columns.drop(["b"]).insert(-1, 'b')
Index([u'a', u'c', u'b', u'd'], dtype='object')
df.columns.drop(["b"]).insert(-1, 'x')
Index([u'a', u'c', u'x', u'd'], dtype='object')
</code></pre>
<p><strong>WORK</strong> Around: </p>
<pre><code> df.columns.drop(["b"]).insert(99999, 'b')
Index([u'a', u'c', u'd', u'b'], dtype='object')
</code></pre>
| 0 | 2016-07-27T02:12:25Z | [
"python",
"pandas"
] |
What is the quickest way to ensure a specific column is last (or first) in a dataframe | 38,601,841 | <p>given <code>df</code></p>
<pre><code>df = pd.DataFrame(np.arange(8).reshape(2, 4), columns=list('abcd'))
</code></pre>
<p><a href="http://i.stack.imgur.com/UXlIN.png" rel="nofollow"><img src="http://i.stack.imgur.com/UXlIN.png" alt="enter image description here"></a></p>
<p>Suppose I need column <code>'b'</code> to be at the end. I could do:</p>
<pre><code>df[['a', 'c', 'd', 'b']]
</code></pre>
<p><a href="http://i.stack.imgur.com/miBss.png" rel="nofollow"><img src="http://i.stack.imgur.com/miBss.png" alt="enter image description here"></a></p>
<p>But what is the most efficient way to ensure that a given column is at the end?</p>
<p>This is what I've been going with. What would others do?</p>
<pre><code>def put_me_last(df, column):
return pd.concat([df.drop(column, axis=1), df[column]], axis=1)
put_me_last(df, 'b')
</code></pre>
<p><a href="http://i.stack.imgur.com/miBss.png" rel="nofollow"><img src="http://i.stack.imgur.com/miBss.png" alt="enter image description here"></a></p>
<hr>
<h3>Timing Results</h3>
<p><strong>conclusion</strong>
mfripp is the winner. Seems as if <code>reindex_axis</code> is a large efficiency gain over <code>[]</code>. That is really good info.</p>
<p><a href="http://i.stack.imgur.com/C8T6N.png" rel="nofollow"><img src="http://i.stack.imgur.com/C8T6N.png" alt="enter image description here"></a></p>
<p><strong>code</strong></p>
<pre><code>from string import lowercase
df_small = pd.DataFrame(np.arange(8).reshape(2, 4), columns=list('abcd'))
df_large = pd.DataFrame(np.arange(1000000).reshape(10000, 100),
columns=pd.MultiIndex.from_product([list(lowercase[:-1]), ['One', 'Two', 'Three', 'Four']]))
def pir1(df, column):
return pd.concat([df.drop(column, axis=1), df[column]], axis=1)
def pir2(df, column):
if df.columns[-1] == column:
return df
else:
pos = df.columns.values.__eq__('b').argmax()
return df[np.roll(df.columns, len(df.columns) - 1 - pos)]
def pir3(df, column):
if df.columns[-1] == column:
return df
else:
pos = df.columns.values.__eq__('b').argmax()
cols = df.columns.values
np.concatenate([cols[:pos], cols[1+pos:], cols[[pos]]])
return df[np.concatenate([cols[:pos], cols[1+pos:], cols[[pos]]])]
def pir4(df, column):
if df.columns[-1] == column:
return df
else:
return df[np.roll(df.columns.drop(column).insert(0, column), -1)]
def carsten1(df, column):
cols = list(df)
if cols[-1] == column:
return df
else:
return pd.concat([df.drop(column, axis=1), df[column]], axis=1)
def carsten2(df, column):
cols = list(df)
if cols[-1] == column:
return df
else:
idx = cols.index(column)
new_cols = cols[:idx] + cols[idx + 1:] + [column]
return df[new_cols]
def mfripp1(df, column):
new_cols = [c for c in df.columns if c != column] + [column]
return df[new_cols]
def mfripp2(df, column):
new_cols = [c for c in df.columns if c != column] + [column]
return df.reindex_axis(new_cols, axis='columns', copy=False)
def ptrj1(df, column):
return df.reindex(columns=df.columns.drop(column).append(pd.Index([column])))
def shivsn1(df, column):
column_list=list(df)
column_list.remove(column)
column_list.append(column)
return df[column_list]
def merlin1(df, column):
return df[df.columns.drop(["b"]).insert(99999, 'b')]
list_of_funcs = [pir1, pir2, pir3, pir4, carsten1, carsten2, mfripp1, mfripp2, ptrj1, shivsn1]
def test_pml(df, pml):
for c in df.columns:
pml(df, c)
summary = pd.DataFrame([], [f.__name__ for f in list_of_funcs], ['Small', 'Large'])
for f in list_of_funcs:
summary.at[f.__name__, 'Small'] = timeit(lambda: test_pml(df_small, f), number=100)
summary.at[f.__name__, 'Large'] = timeit(lambda: test_pml(df_large, f), number=10)
</code></pre>
| 3 | 2016-07-27T00:18:38Z | 38,605,142 | <p>It's not the fastest though:</p>
<pre><code>def put_me_last(df,column):
column_list=list(df)
column_list.remove(column)
column_list.append(column)
return df[column_list]
%timeit put_me_last(df,'b')
1000 loops, best of 3: 391 µs per loop
</code></pre>
| 1 | 2016-07-27T06:20:01Z | [
"python",
"pandas"
] |
Pyinstaller on Kali to create exe for Windows XP | 38,601,919 | <p>I am using Pyinstaller on Kali Linux 2 to create .exe to run on Windows XP.</p>
<p>So far, pyinstaller is successful at creating .exe that works on Kali Linux, but not Windows</p>
<p>Here is the python code</p>
<pre><code>import webbrowser
webbrowser.open('http://www.cnn.com')
</code></pre>
<p>This is the command I ran on Kali Linux</p>
<pre><code>~/Downloads/PyInstaller-3.2/pyinstaller.py --onefile --windowed --noupx open.py
</code></pre>
<p>When I open the resulting open.exe in Kali, it opens <code>www.cnn.com</code>. But if I email this attachment and open in Windows XP, it asks</p>
<p><a href="http://i.stack.imgur.com/BG0py.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/BG0py.jpg" alt="enter image description here"></a></p>
<p>When I save and try to execute, it says ..... How to troubleshoot this?</p>
<p><a href="http://i.stack.imgur.com/7aRpz.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/7aRpz.jpg" alt="enter image description here"></a></p>
<p>And when I click open is shows following. How to make it open with double-click?</p>
<p><a href="http://i.stack.imgur.com/7cqGg.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/7cqGg.jpg" alt="enter image description here"></a></p>
| -1 | 2016-07-27T00:28:45Z | 38,601,937 | <p>Windows Defender assumes that externally sourced executables, especially those without cryptographic signature, may be malware. Try clicking "Open."</p>
| 1 | 2016-07-27T00:31:05Z | [
"python",
"linux",
"windows",
"exe"
] |
Pyinstaller on Kali to create exe for Windows XP | 38,601,919 | <p>I am using Pyinstaller on Kali Linux 2 to create .exe to run on Windows XP.</p>
<p>So far, pyinstaller is successful at creating .exe that works on Kali Linux, but not Windows</p>
<p>Here is the python code</p>
<pre><code>import webbrowser
webbrowser.open('http://www.cnn.com')
</code></pre>
<p>This is the command I ran on Kali Linux</p>
<pre><code>~/Downloads/PyInstaller-3.2/pyinstaller.py --onefile --windowed --noupx open.py
</code></pre>
<p>When I open the resulting open.exe in Kali, it opens <code>www.cnn.com</code>. But if I email this attachment and open in Windows XP, it asks</p>
<p><a href="http://i.stack.imgur.com/BG0py.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/BG0py.jpg" alt="enter image description here"></a></p>
<p>When I save and try to execute, it says ..... How to troubleshoot this?</p>
<p><a href="http://i.stack.imgur.com/7aRpz.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/7aRpz.jpg" alt="enter image description here"></a></p>
<p>And when I click open is shows following. How to make it open with double-click?</p>
<p><a href="http://i.stack.imgur.com/7cqGg.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/7cqGg.jpg" alt="enter image description here"></a></p>
| -1 | 2016-07-27T00:28:45Z | 38,601,974 | <p>From the <a href="https://pyinstaller.readthedocs.io/en/stable/usage.html#supporting-multiple-operating-systems" rel="nofollow">PyInstaller documentation</a>:</p>
<blockquote>
<p>If you need to distribute your application for more than one OS, for example both Windows and Mac OS X, you must install PyInstaller on each platform and bundle your app separately on each.</p>
</blockquote>
<p>So, to make an app which runs on Windows, you have to create it using PyInstaller on Windows.</p>
| 3 | 2016-07-27T00:37:56Z | [
"python",
"linux",
"windows",
"exe"
] |
Pyinstaller on Kali to create exe for Windows XP | 38,601,919 | <p>I am using Pyinstaller on Kali Linux 2 to create .exe to run on Windows XP.</p>
<p>So far, pyinstaller is successful at creating .exe that works on Kali Linux, but not Windows</p>
<p>Here is the python code</p>
<pre><code>import webbrowser
webbrowser.open('http://www.cnn.com')
</code></pre>
<p>This is the command I ran on Kali Linux</p>
<pre><code>~/Downloads/PyInstaller-3.2/pyinstaller.py --onefile --windowed --noupx open.py
</code></pre>
<p>When I open the resulting open.exe in Kali, it opens <code>www.cnn.com</code>. But if I email this attachment and open in Windows XP, it asks</p>
<p><a href="http://i.stack.imgur.com/BG0py.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/BG0py.jpg" alt="enter image description here"></a></p>
<p>When I save and try to execute, it says ..... How to troubleshoot this?</p>
<p><a href="http://i.stack.imgur.com/7aRpz.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/7aRpz.jpg" alt="enter image description here"></a></p>
<p>And when I click open is shows following. How to make it open with double-click?</p>
<p><a href="http://i.stack.imgur.com/7cqGg.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/7cqGg.jpg" alt="enter image description here"></a></p>
| -1 | 2016-07-27T00:28:45Z | 38,602,272 | <p>Rafalmp is correct you must use a Windows machine to compile it. Alternatively you can use Wine, if you didn't have access to a Windows machine. </p>
<p>For more info please refer to <a href="https://github.com/pyinstaller/pyinstaller/wiki/FAQ" rel="nofollow">Pyinstaller FAQ</a></p>
| 2 | 2016-07-27T01:25:00Z | [
"python",
"linux",
"windows",
"exe"
] |
Ordering a Django queryset based on the sorting of a sorted set from redis | 38,602,115 | <p>I have a sorted set from redis. The sorted set contains both ids of objects and their sorting scores.</p>
<p>Next, I have a Django queryset, consisting of objects whose sorted ids were contained in the aforementioned redis sorted set. </p>
<p>I need to sort this Django queryset according to the placement of ids in the <em>redis sorted set</em>. What's the fastest way to accomplish this?</p>
<hr>
<p>I'm trying the following:</p>
<pre><code> dictionary = dict(sorted_set) #turning the sorted set into a dictionary
for pk, score in dictionary:
obj = queryset.get(id=pk) #get object with id equalling pk
score = object #assign the object to the 'score' value of this key-value
result = dictionary.values() #making a list of all values, that are now in sorted order
</code></pre>
<p>The for loop above fails for me with a <code>too many values to unpack</code> error - I'm still debugging it. Nevertheless, I also feel there are probably faster ways to do what I'm trying to do, hence I asked this question. Thanks in advance!</p>
| 1 | 2016-07-27T01:00:07Z | 38,602,462 | <p>Replace your for loop with:</p>
<pre><code>result = sorted(queryset, key=lambda item: dictionary[item.pk], reverse=True)
</code></pre>
<p>This will exception out if anything in the qs is not in the redis result - use <code>dictionary.get(item.pk, ...)</code> with some sane default instead of <code>dictionary[item.pk]</code> if that can happen.</p>
| 1 | 2016-07-27T01:53:33Z | [
"python",
"django",
"sorting",
"redis"
] |
How to install Numpy & pip3 for python3.x when they were installed in python2.7? Using Conda? | 38,602,185 | <p>I want to write program in python3 (3.5), hence I installed python3 next to the pre-installed python2 (2.7) on Mac OS X El Captian.</p>
<p>Since my terminal runs python2.7 by default and Numpy is already installed for it, I put <code>alias python=python3</code> and expected to be able to install Numpy for python3. when I type <code>pip install numpy</code>. This was the generated message:</p>
<pre><code>Requirement already satisfied (use --upgrade to upgrade): numpy in /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages
</code></pre>
<p>I also noticed that I have no <code>pip3</code> even though I am using python3: <code>python --version</code> returned <code>Python 3.5.2</code>, but <code>pip3 install numpy</code> got me <code>-bash: pip3: command not found</code>. </p>
<p>So my questions are:<br>
1) How to install Numpy for python3.x when Numpy is installed on python2.x?<br>
2) How to get pip3?<br>
3) Is it better to use virtual environments, such as Conda, instead of juggling between python2 and python3 on the system?</p>
<p>Thank you from a total n00b</p>
<p><strong>------------------- Update -------------------</strong> </p>
<p>Reinstalling python3 also fixed another problem in my case.<br>
When I ran <code>brew doctor</code>, one of the warning message I got was:</p>
<p><code>Warning: You have unlinked kegs in your Cellar Leaving kegs unlinked can lead to build-trouble and cause brews that depend on those kegs to fail to run properly once built. Run brew link on these: python â</code></p>
<p>This is a result of me running <code>brew unlink python</code> in order to fix </p>
<blockquote>
<p>"Python quit unexpectedly"</p>
</blockquote>
<p>when I launch Vim and also </p>
<blockquote>
<p>"The ycmd server SHUT DOWN"</p>
</blockquote>
<p>Both seem to relate to the YouCompleteMe autocomplete plugin which I downloaded for Python. </p>
<p>I got my idea of removing symlinks from <a href="https://github.com/Valloric/YouCompleteMe/issues/585" rel="nofollow">here</a> and <a href="https://github.com/Valloric/YouCompleteMe/issues/611" rel="nofollow">here</a><br>
However, Homebrew evidently did not like the absence of those 39 symlinks.</p>
<p>After uninstall (<code>brew uninstall python3</code>) and then re-install python3 (<code>brew install python3</code>) as Toby suggested, Homebrew gave me </p>
<pre><code>You can install Python packages with
pip3 install <package>
</code></pre>
<p>Then when I <code>pip3 install numpy</code> and <code>pip3 install scipy</code>, both executed successfully.</p>
<p>To my surprise, symlinks created during Python installation used to cause aforementioned error messages for Python and YouCompleteMe, but now I open python files using Vim without crash from a fresh Python installation, which definitely created the symlinks. </p>
<p><strong>------------------- Update2 ------------------</strong></p>
<p>After re-installing Anaconda2, the same YouCompleteMe error came back. I suspect Anaconda messed up symlinks.</p>
| 0 | 2016-07-27T01:10:42Z | 38,602,204 | <p>The simplest way on a Mac is with Homebrew:</p>
<p><a href="http://brew.sh/" rel="nofollow">http://brew.sh/</a></p>
<p>Install Homebrew, then run:</p>
<p><code>brew install python3 pip3</code></p>
<p>Edit --</p>
<p>Python3 includes pip3, but Homebrew occasionally has trouble linking to the correct versions, depending on what has been installed. Running the following command:</p>
<p><code>brew doctor</code></p>
<p>And if you see errors relating to python or unlinked kegs, try running:</p>
<p><code>brew uninstall python python3</code></p>
<p>And reinstalling after checking <code>brew doctor</code>.</p>
<p><a href="http://unix.stackexchange.com/questions/233519/pip3-linked-to-python-framework-instead-of-homebrew-usr-local-bin">http://unix.stackexchange.com/questions/233519/pip3-linked-to-python-framework-instead-of-homebrew-usr-local-bin</a></p>
| 1 | 2016-07-27T01:13:45Z | [
"python",
"python-2.7",
"python-3.x",
"pip",
"conda"
] |
How to install Numpy & pip3 for python3.x when they were installed in python2.7? Using Conda? | 38,602,185 | <p>I want to write program in python3 (3.5), hence I installed python3 next to the pre-installed python2 (2.7) on Mac OS X El Captian.</p>
<p>Since my terminal runs python2.7 by default and Numpy is already installed for it, I put <code>alias python=python3</code> and expected to be able to install Numpy for python3. when I type <code>pip install numpy</code>. This was the generated message:</p>
<pre><code>Requirement already satisfied (use --upgrade to upgrade): numpy in /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages
</code></pre>
<p>I also noticed that I have no <code>pip3</code> even though I am using python3: <code>python --version</code> returned <code>Python 3.5.2</code>, but <code>pip3 install numpy</code> got me <code>-bash: pip3: command not found</code>. </p>
<p>So my questions are:<br>
1) How to install Numpy for python3.x when Numpy is installed on python2.x?<br>
2) How to get pip3?<br>
3) Is it better to use virtual environments, such as Conda, instead of juggling between python2 and python3 on the system?</p>
<p>Thank you from a total n00b</p>
<p><strong>------------------- Update -------------------</strong> </p>
<p>Reinstalling python3 also fixed another problem in my case.<br>
When I ran <code>brew doctor</code>, one of the warning message I got was:</p>
<p><code>Warning: You have unlinked kegs in your Cellar Leaving kegs unlinked can lead to build-trouble and cause brews that depend on those kegs to fail to run properly once built. Run brew link on these: python â</code></p>
<p>This is a result of me running <code>brew unlink python</code> in order to fix </p>
<blockquote>
<p>"Python quit unexpectedly"</p>
</blockquote>
<p>when I launch Vim and also </p>
<blockquote>
<p>"The ycmd server SHUT DOWN"</p>
</blockquote>
<p>Both seem to relate to the YouCompleteMe autocomplete plugin which I downloaded for Python. </p>
<p>I got my idea of removing symlinks from <a href="https://github.com/Valloric/YouCompleteMe/issues/585" rel="nofollow">here</a> and <a href="https://github.com/Valloric/YouCompleteMe/issues/611" rel="nofollow">here</a><br>
However, Homebrew evidently did not like the absence of those 39 symlinks.</p>
<p>After uninstall (<code>brew uninstall python3</code>) and then re-install python3 (<code>brew install python3</code>) as Toby suggested, Homebrew gave me </p>
<pre><code>You can install Python packages with
pip3 install <package>
</code></pre>
<p>Then when I <code>pip3 install numpy</code> and <code>pip3 install scipy</code>, both executed successfully.</p>
<p>To my surprise, symlinks created during Python installation used to cause aforementioned error messages for Python and YouCompleteMe, but now I open python files using Vim without crash from a fresh Python installation, which definitely created the symlinks. </p>
<p><strong>------------------- Update2 ------------------</strong></p>
<p>After re-installing Anaconda2, the same YouCompleteMe error came back. I suspect Anaconda messed up symlinks.</p>
| 0 | 2016-07-27T01:10:42Z | 38,602,775 | <p>I would recommend using the Anaconda Python distribution.</p>
<p>The main reasons are as such:</p>
<ol>
<li>You will have a Python distribution that comes with <code>numpy</code> and the rest of the <a href="http://scipy.org" rel="nofollow">Scientific Python</a> stack.</li>
<li>The Anaconda Python will be installed under your home directory, with no need for <code>sudo</code>-ing to install other packages.</li>
<li><code>conda install [put_packagename_here]</code> works alongside <code>pip install [put_packagename_here]</code>; <code>conda install</code> is much 'cleaner' (IMHO, differing opinions are welcome).</li>
<li>If you have a Python 3 environment as your default, then <code>pip</code> works out-of-the-box without needing to remember to do <code>pip3</code>.</li>
<li><code>conda environments</code> are easier to manage than <code>virtualenv</code> environments, in my opinion. And yes, you can have Python 2 alongside Python 3.</li>
<li>I once messed up my system Python environment - the one that came with my Mac - and it broke iPhoto (back in the day). Since then, I became convinced of needing separate, atomic environments for different projects. </li>
</ol>
<p>I've detailed more reasons in a <a href="http://www.ericmajinglong.com/2014/09/23/5-great-things-about-the-anaconda-distribution/" rel="nofollow">personal blog post</a>.</p>
<p>Other distributions, of course, are all good, provided they give you what you need :).</p>
| 2 | 2016-07-27T02:34:37Z | [
"python",
"python-2.7",
"python-3.x",
"pip",
"conda"
] |
how to make x,y axis appear in an axes in python matplotlib | 38,602,216 | <p>I have a text file (which I extracted during run using np.savetxt function) _anchors.out</p>
<pre><code>-84 -40 99 55
-176 -88 191 103
-360 -184 375 199
-56 -56 71 71
-120 -120 135 135
-248 -248 263 263
-36 -80 51 95
-80 -168 95 183
-168 -344 183 359
</code></pre>
<p>These are 9 boxes centered around point 7.5. I can see the boxes using code below(qq.py) </p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches
b = np.loadtxt('_anchors.out','int')
fig1 = plt.figure()
ax1 = fig1.add_subplot(111, aspect='equal')
ax1.set_xbound(-400,400)
ax1.set_ybound(-400,400)
for x1,y1,x2,y2 in b:
ax1.add_patch(patches.Rectangle((x1,y1), x2-x1, y2-y1,fill=False))
fig1.show()
</code></pre>
<p>and the figure is <a href="http://i.stack.imgur.com/9WUiz.png" rel="nofollow"><img src="http://i.stack.imgur.com/9WUiz.png" alt="graph with no axis"></a><br>
But I want to see the X, and Y axis together(not the 'axes' in matplotlib term). I've searched some solution but it's not clear to me. How should I modify above code? (you can check it using ipython. run ipython, and inside type 'run qq.py')</p>
<p>What I want to see is below(X and Y axes added)<a href="http://i.stack.imgur.com/8w7Ro.png" rel="nofollow"><img src="http://i.stack.imgur.com/8w7Ro.png" alt="here"></a></p>
| 2 | 2016-07-27T01:14:51Z | 38,602,748 | <p>You can use this alternative that plots dashed lines:</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches
b = np.loadtxt('_anchors.out','int')
fig1 = plt.figure()
ax1 = fig1.add_subplot(111, aspect='equal')
ax1.set_xbound(-400,400)
ax1.set_ybound(-400,400)
for x1,y1,x2,y2 in b:
ax1.add_patch(patches.Rectangle((x1,y1), x2-x1, y2-y1,fill=False))
plt.plot((0, 0), (-400, 400), 'r--')
plt.plot((-400, 400), (0, 0), 'r--')
fig1.show()
</code></pre>
<p>Which outputs:
<a href="http://i.stack.imgur.com/gV86C.png" rel="nofollow"><img src="http://i.stack.imgur.com/gV86C.png" alt="enter image description here"></a></p>
| 2 | 2016-07-27T02:30:58Z | [
"python",
"matplotlib"
] |
how to make x,y axis appear in an axes in python matplotlib | 38,602,216 | <p>I have a text file (which I extracted during run using np.savetxt function) _anchors.out</p>
<pre><code>-84 -40 99 55
-176 -88 191 103
-360 -184 375 199
-56 -56 71 71
-120 -120 135 135
-248 -248 263 263
-36 -80 51 95
-80 -168 95 183
-168 -344 183 359
</code></pre>
<p>These are 9 boxes centered around point 7.5. I can see the boxes using code below(qq.py) </p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches
b = np.loadtxt('_anchors.out','int')
fig1 = plt.figure()
ax1 = fig1.add_subplot(111, aspect='equal')
ax1.set_xbound(-400,400)
ax1.set_ybound(-400,400)
for x1,y1,x2,y2 in b:
ax1.add_patch(patches.Rectangle((x1,y1), x2-x1, y2-y1,fill=False))
fig1.show()
</code></pre>
<p>and the figure is <a href="http://i.stack.imgur.com/9WUiz.png" rel="nofollow"><img src="http://i.stack.imgur.com/9WUiz.png" alt="graph with no axis"></a><br>
But I want to see the X, and Y axis together(not the 'axes' in matplotlib term). I've searched some solution but it's not clear to me. How should I modify above code? (you can check it using ipython. run ipython, and inside type 'run qq.py')</p>
<p>What I want to see is below(X and Y axes added)<a href="http://i.stack.imgur.com/8w7Ro.png" rel="nofollow"><img src="http://i.stack.imgur.com/8w7Ro.png" alt="here"></a></p>
| 2 | 2016-07-27T01:14:51Z | 38,603,189 | <pre><code>import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches
b = np.loadtxt('./_anchors.out','int')
fig1 = plt.figure()
ax1 = fig1.add_subplot(111, aspect='equal')
ax1.set_xbound(-400,400)
ax1.set_ybound(-400,400)
for x1,y1,x2,y2 in b:
ax1.add_patch(patches.Rectangle((x1,y1), x2-x1, y2-y1,fill=False))
# Move left y-axis and bottom x-axis to center of the figure
ax1.spines['left'].set_position('center')
ax1.spines['bottom'].set_position('center')
ax1.spines['left'].set_color('r')
ax1.spines['bottom'].set_color('r')
# Show ticks in the left and lower axes only
ax1.xaxis.set_tick_params(bottom='on', top='off', direction='inout', color='r')
ax1.yaxis.set_tick_params(left='on', right='off', direction='inout', color='r')
# Remove upper and right axes
ax1.spines['top'].set_visible(False)
ax1.spines['right'].set_visible(False)
plt.show()
</code></pre>
<p>Output:</p>
<p><a href="http://i.stack.imgur.com/E4UeD.png" rel="nofollow"><img src="http://i.stack.imgur.com/E4UeD.png" alt="enter image description here"></a></p>
<p>Actually you may set tick labels as you want.</p>
| 3 | 2016-07-27T03:25:49Z | [
"python",
"matplotlib"
] |
how to make x,y axis appear in an axes in python matplotlib | 38,602,216 | <p>I have a text file (which I extracted during run using np.savetxt function) _anchors.out</p>
<pre><code>-84 -40 99 55
-176 -88 191 103
-360 -184 375 199
-56 -56 71 71
-120 -120 135 135
-248 -248 263 263
-36 -80 51 95
-80 -168 95 183
-168 -344 183 359
</code></pre>
<p>These are 9 boxes centered around point 7.5. I can see the boxes using code below(qq.py) </p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches
b = np.loadtxt('_anchors.out','int')
fig1 = plt.figure()
ax1 = fig1.add_subplot(111, aspect='equal')
ax1.set_xbound(-400,400)
ax1.set_ybound(-400,400)
for x1,y1,x2,y2 in b:
ax1.add_patch(patches.Rectangle((x1,y1), x2-x1, y2-y1,fill=False))
fig1.show()
</code></pre>
<p>and the figure is <a href="http://i.stack.imgur.com/9WUiz.png" rel="nofollow"><img src="http://i.stack.imgur.com/9WUiz.png" alt="graph with no axis"></a><br>
But I want to see the X, and Y axis together(not the 'axes' in matplotlib term). I've searched some solution but it's not clear to me. How should I modify above code? (you can check it using ipython. run ipython, and inside type 'run qq.py')</p>
<p>What I want to see is below(X and Y axes added)<a href="http://i.stack.imgur.com/8w7Ro.png" rel="nofollow"><img src="http://i.stack.imgur.com/8w7Ro.png" alt="here"></a></p>
| 2 | 2016-07-27T01:14:51Z | 38,603,218 | <p>Following the documentation <a href="http://matplotlib.org/examples/pylab_examples/spine_placement_demo.html" rel="nofollow">here</a> you can achieve this with the following code:</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches
b = np.loadtxt('_anchors.out','int')
fig1 = plt.figure()
ax1 = fig1.add_subplot(111, aspect='equal')
ax1.set_xbound(-400,400)
ax1.set_ybound(-400,400)
for x1,y1,x2,y2 in b:
ax1.add_patch(patches.Rectangle((x1,y1), x2-x1, y2-y1,fill=False))
#Change spine position
ax1.spines['left'].set_position('center')
ax1.spines['right'].set_color('none')
ax1.spines['bottom'].set_position('center')
ax1.spines['top'].set_color('none')
ax1.spines['left'].set_smart_bounds(True)
ax1.spines['bottom'].set_smart_bounds(True)
ax1.xaxis.set_ticks_position('bottom')
ax1.yaxis.set_ticks_position('left')
#Show figure
fig1.show()
</code></pre>
<p>Giving:</p>
<p><a href="http://i.stack.imgur.com/XZwQe.png" rel="nofollow"><img src="http://i.stack.imgur.com/XZwQe.png" alt="enter image description here"></a></p>
| 3 | 2016-07-27T03:28:56Z | [
"python",
"matplotlib"
] |
python tornado json render to html script | 38,602,219 | <p>I want to render json file to html script part. In the tornado part, No1 is sendering json data to html. And, No2 part is received the json data from No1. However this code is not working. I found that html script doesn't allow the form of {{ }}. How I send the json data to part of html ?</p>
<p>[ python - tornado part ]</p>
<pre><code>import tornado.web
import tornado.httpserver
import tornado.ioloop
import os.path
from tornado.options import define, options
define("port", default=3000, help="run on the given port", type=int)
class Application(tornado.web.Application):
def __init__(self):
base_dir = os.path.dirname(__file__)
settings = {
}
tornado.web.Application.__init__(self, [
tornado.web.url(r"/", MainHandler, name="main"),
], **settings)
class MainHandler(tornado.web.RequestHandler):
def get(self):
data = {"name":"John Johnson","street":"Oslo West 16","phone":"555 1234567"}
self.render("index.html", data=data) #No1
def main():
tornado.options.parse_command_line()
Application().listen(options.port)
tornado.ioloop.IOLoop.instance().start()
if __name__ == "__main__":
main()
</code></pre>
<p>[ html part ]</p>
<pre><code><!DOCTYPE html>
<html>
<body>
<h2>JSON Object Creation in JavaScript</h2>
<p id="demo"></p>
<script>
/* var text = '{"name":"John Johnson","street":"Oslo West 16","phone":"555 1234567"}'; */
var text = '{{data}}'; /*No2*/
var obj = JSON.parse(text);
document.getElementById("demo").innerHTML =
obj.name + "<br>" +
obj.street + "<br>" +
obj.phone;
</script>
</body>
</html>
</code></pre>
| 0 | 2016-07-27T01:15:07Z | 38,602,647 | <p>The {{ }} in your index.html template will be autoescaped for html. You want raw output because in this case you're outputting javascript rather than html. You also want to make sure you're actually letting python convert your data object to correctly formatted json.</p>
<p>Import the json library and add a call to json.dumps to get correctly formatted JSON:</p>
<pre><code>import tornado.web
import tornado.httpserver
import tornado.ioloop
import os.path
import json
from tornado.options import define, options
define("port", default=3000, help="run on the given port", type=int)
class Application(tornado.web.Application):
def __init__(self):
base_dir = os.path.dirname(__file__)
settings = {
}
tornado.web.Application.__init__(self, [
tornado.web.url(r"/", MainHandler, name="main"),
], **settings)
class MainHandler(tornado.web.RequestHandler):
def get(self):
data = {"name":"John Johnson","street":"Oslo West 16","phone":"555 1234567"}
self.render("index.html", data=json.dumps(data))
def main():
tornado.options.parse_command_line()
Application().listen(options.port)
tornado.ioloop.IOLoop.instance().start()
if __name__ == "__main__":
main()
</code></pre>
<p>And use raw to prevent the html auto-escaping output in your template:</p>
<pre><code><!DOCTYPE html>
<html>
<body>
<h2>JSON Object Creation in JavaScript</h2>
<p id="demo"></p>
<script>
/* var text = '{"name":"John Johnson","street":"Oslo West 16","phone":"555 1234567"}'; */
var text = '{% raw data %}';
var obj = JSON.parse(text);
document.getElementById("demo").innerHTML =
obj.name + "<br>" +
obj.street + "<br>" +
obj.phone;
</script>
<body>
</body>
</html>
</code></pre>
| 1 | 2016-07-27T02:17:34Z | [
"javascript",
"python",
"html",
"json",
"tornado"
] |
python tornado json render to html script | 38,602,219 | <p>I want to render json file to html script part. In the tornado part, No1 is sendering json data to html. And, No2 part is received the json data from No1. However this code is not working. I found that html script doesn't allow the form of {{ }}. How I send the json data to part of html ?</p>
<p>[ python - tornado part ]</p>
<pre><code>import tornado.web
import tornado.httpserver
import tornado.ioloop
import os.path
from tornado.options import define, options
define("port", default=3000, help="run on the given port", type=int)
class Application(tornado.web.Application):
def __init__(self):
base_dir = os.path.dirname(__file__)
settings = {
}
tornado.web.Application.__init__(self, [
tornado.web.url(r"/", MainHandler, name="main"),
], **settings)
class MainHandler(tornado.web.RequestHandler):
def get(self):
data = {"name":"John Johnson","street":"Oslo West 16","phone":"555 1234567"}
self.render("index.html", data=data) #No1
def main():
tornado.options.parse_command_line()
Application().listen(options.port)
tornado.ioloop.IOLoop.instance().start()
if __name__ == "__main__":
main()
</code></pre>
<p>[ html part ]</p>
<pre><code><!DOCTYPE html>
<html>
<body>
<h2>JSON Object Creation in JavaScript</h2>
<p id="demo"></p>
<script>
/* var text = '{"name":"John Johnson","street":"Oslo West 16","phone":"555 1234567"}'; */
var text = '{{data}}'; /*No2*/
var obj = JSON.parse(text);
document.getElementById("demo").innerHTML =
obj.name + "<br>" +
obj.street + "<br>" +
obj.phone;
</script>
</body>
</html>
</code></pre>
| 0 | 2016-07-27T01:15:07Z | 38,602,913 | <p>The key point is that string will be autoescaped by template engine. So we need to decode it before parsing it as a json.</p>
<p><code>{% raw %}</code> directive mentioned by @clockwatcher is one solution. But it may cause error if the variable <code>text</code> is double-quoted since <code>json.dumps(data)</code> will use double quotation marks in its output. </p>
<p>Therefore, a possible better solution is to unescape <code>text</code>.</p>
<pre class="lang-py prettyprint-override"><code>import tornado.web
import tornado.httpserver
import tornado.ioloop
import os.path
import json
from tornado.options import define, options
define("port", default=3000, help="run on the given port", type=int)
class Application(tornado.web.Application):
def __init__(self):
base_dir = os.path.dirname(__file__)
settings = {
}
tornado.web.Application.__init__(self, [
tornado.web.url(r"/", MainHandler, name="main"),
], **settings)
class MainHandler(tornado.web.RequestHandler):
def get(self):
data = {"name":"John Johnson","street":"Oslo West 16","phone":"555 1234567"}
self.render("index.html", data=json.dumps(data))
def main():
tornado.options.parse_command_line()
Application().listen(options.port)
tornado.ioloop.IOLoop.instance().start()
if __name__ == "__main__":
main()
</code></pre>
<pre><code><!DOCTYPE html>
<html>
<body>
<h2>JSON Object Creation in JavaScript</h2>
<p id="demo"></p>
<script>
String.prototype.unescapeHtml = function () {
var temp = document.createElement("div");
temp.innerHTML = this;
var result = temp.childNodes[0].nodeValue;
temp.removeChild(temp.firstChild);
return result;
}
var text = '{{data}}';
var obj = JSON.parse(text.unescapeHtml());
document.getElementById("demo").innerHTML =
obj.name + "<br>" +
obj.street + "<br>" +
obj.phone;
</script>
</body>
</html>
</code></pre>
<p>The snippet of function <code>unescapeHTML</code> comes from <a href="https://paulschreiber.com/blog/2008/09/20/javascript-how-to-unescape-html-entities/" rel="nofollow">JavaScript: how to unescape HTML entities</a>.</p>
| 0 | 2016-07-27T02:51:20Z | [
"javascript",
"python",
"html",
"json",
"tornado"
] |
Python- checking a number to see if it's a prime number by using divisors | 38,602,221 | <p>I have to write a program that checks if a number is a prime number by going through divisors in the range(1,num). (For ex. if the input is 5, the program will check if 2 is a divisor, then 3, then 4). Can someone explain how I can put the last expression in my program (the "this is a prime number" print function), so that it appears only after the "else" function in the "for" loop and not the "if div == 0:" statements? Thank you!</p>
<pre><code>while True:
num = int(input("Enter a positive number to see if it's a prime number: "))
if num > 1:
break
elif num == 1:
print("1 is technically not a prime number.")
else:
print("Number cannot be negative- try again.")
for num1 in range(2,num):
div = num%num1
if div == 0:
print(num1,"is a divisor of",num,"... stopping.")
print(num,"is not a prime number.")
break
else:
print(num1,"is NOT a divisor of",num,"... continuing")
print(num,"is a prime number!")
</code></pre>
| 0 | 2016-07-27T01:15:13Z | 38,602,259 | <p>There are many ways to do this:</p>
<h2>Set a flag!</h2>
<pre><code>is_prime = True # a boolean flag
for num1 in range(2,num):
div = num%num1
if div == 0:
print(num1,"is a divisor of",num,"... stopping.")
print(num,"is not a prime number.")
is_prime = False
break
else:
print(num1,"is NOT a divisor of",num,"... continuing")
if is_prime:
print(num,"is a prime number!")
</code></pre>
<h2>Use <code>for-else</code> !</h2>
<pre><code>for num1 in range(2,num):
div = num%num1
if div == 0:
print(num1,"is a divisor of",num,"... stopping.")
print(num,"is not a prime number.")
is_prime = False
break
else:
print(num1,"is NOT a divisor of",num,"... continuing")
else:
print(num,"is a prime number!") # will execute only when for-loop ends
</code></pre>
| 1 | 2016-07-27T01:22:16Z | [
"python"
] |
Python- checking a number to see if it's a prime number by using divisors | 38,602,221 | <p>I have to write a program that checks if a number is a prime number by going through divisors in the range(1,num). (For ex. if the input is 5, the program will check if 2 is a divisor, then 3, then 4). Can someone explain how I can put the last expression in my program (the "this is a prime number" print function), so that it appears only after the "else" function in the "for" loop and not the "if div == 0:" statements? Thank you!</p>
<pre><code>while True:
num = int(input("Enter a positive number to see if it's a prime number: "))
if num > 1:
break
elif num == 1:
print("1 is technically not a prime number.")
else:
print("Number cannot be negative- try again.")
for num1 in range(2,num):
div = num%num1
if div == 0:
print(num1,"is a divisor of",num,"... stopping.")
print(num,"is not a prime number.")
break
else:
print(num1,"is NOT a divisor of",num,"... continuing")
print(num,"is a prime number!")
</code></pre>
| 0 | 2016-07-27T01:15:13Z | 38,602,270 | <p>Python's <code>for</code> expression has <a href="https://docs.python.org/3/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops" rel="nofollow">an optional <code>else</code> clause</a>:</p>
<blockquote>
<p>Loop statements may have an else clause; it is executed when the loop terminates through exhaustion of the list (with for) or when the condition becomes false (with while), but not when the loop is terminated by a break statement.</p>
</blockquote>
<p>So your code should look like this:</p>
<pre><code>while True:
num = int(input("Enter a positive number to see if it's a prime number: "))
if num > 1:
break
elif num == 1:
print("1 is technically not a prime number.")
else:
print("Number cannot be negative- try again.")
for num1 in range(2,num):
div = num%num1
if div == 0:
print(num1,"is a divisor of",num,"... stopping.")
print(num,"is not a prime number.")
break
else:
print(num1,"is NOT a divisor of",num,"... continuing")
else:
print(num,"is a prime number!")
</code></pre>
| 1 | 2016-07-27T01:24:36Z | [
"python"
] |
Python- checking a number to see if it's a prime number by using divisors | 38,602,221 | <p>I have to write a program that checks if a number is a prime number by going through divisors in the range(1,num). (For ex. if the input is 5, the program will check if 2 is a divisor, then 3, then 4). Can someone explain how I can put the last expression in my program (the "this is a prime number" print function), so that it appears only after the "else" function in the "for" loop and not the "if div == 0:" statements? Thank you!</p>
<pre><code>while True:
num = int(input("Enter a positive number to see if it's a prime number: "))
if num > 1:
break
elif num == 1:
print("1 is technically not a prime number.")
else:
print("Number cannot be negative- try again.")
for num1 in range(2,num):
div = num%num1
if div == 0:
print(num1,"is a divisor of",num,"... stopping.")
print(num,"is not a prime number.")
break
else:
print(num1,"is NOT a divisor of",num,"... continuing")
print(num,"is a prime number!")
</code></pre>
| 0 | 2016-07-27T01:15:13Z | 38,602,279 | <p>Given that you have already covered a division by 1, all you have to do is count if there is only one more divisor (the number itself). So to keep your code structure I added a counter.</p>
<pre><code>while True:
num = int(input("Enter a positive number to see if it's a prime number: "))
if num > 1:
break
elif num == 1:
print("1 is technically not a prime number.")
else:
print("Number cannot be negative- try again.")
for num1 in range(2,num):
div = num%num1
count = 0
if div == 0:
print(num1,"is a divisor of",num,"... stopping.")
print(num,"is not a prime number.")
break
else:
count += 1
print(num1,"is NOT a divisor of",num,"... continuing")
if count == 1:
print(num,"is a prime number!")
</code></pre>
| 0 | 2016-07-27T01:25:59Z | [
"python"
] |
Python- checking a number to see if it's a prime number by using divisors | 38,602,221 | <p>I have to write a program that checks if a number is a prime number by going through divisors in the range(1,num). (For ex. if the input is 5, the program will check if 2 is a divisor, then 3, then 4). Can someone explain how I can put the last expression in my program (the "this is a prime number" print function), so that it appears only after the "else" function in the "for" loop and not the "if div == 0:" statements? Thank you!</p>
<pre><code>while True:
num = int(input("Enter a positive number to see if it's a prime number: "))
if num > 1:
break
elif num == 1:
print("1 is technically not a prime number.")
else:
print("Number cannot be negative- try again.")
for num1 in range(2,num):
div = num%num1
if div == 0:
print(num1,"is a divisor of",num,"... stopping.")
print(num,"is not a prime number.")
break
else:
print(num1,"is NOT a divisor of",num,"... continuing")
print(num,"is a prime number!")
</code></pre>
| 0 | 2016-07-27T01:15:13Z | 38,602,325 | <p>I added one line sys.exit()</p>
<pre><code>while True:
num = int(input("Enter a positive number to see if it's a prime number: "))
if num > 1:
break
elif num == 1:
print("1 is technically not a prime number.")
else:
print("Number cannot be negative- try again.")
for num1 in range(2,num):
div = num%num1
if div == 0:
print(num1,"is a divisor of",num,"... stopping.")
print(num,"is not a prime number.")
sys.exit()
else:
print(num1,"is NOT a divisor of",num,"... continuing")
print(num,"is a prime number!")
</code></pre>
| 0 | 2016-07-27T01:34:01Z | [
"python"
] |
text game if check1 and check2 and check3 statment | 38,602,286 | <p>So this is the beginning of a simple text game im working on.
When I run the program it will run through them multiple times before it can get to done. Not just one for each like I want. But I still want it to pick them at random, so I'm not sure if there is a better way to do this? Could someone tell me what I did wrong? </p>
<pre><code>import random
from collections import defaultdict
Blist = ["hash browns", "eggs", "cheese", "sausage"]
Dictionary = {"a":1,"b":1,"c":1,"d":1}
Tup = (1,2,3,4,5)
check1 = False
check2 = False
check3 = False
def question():
answer = ((Blist), (Dictionary), (Tup))
new = (random.choice(answer))
print(new)
print("which is this?")
print("a List, Dictionary, or Tuple?")
x = str(input('what is it?\n'))
if check1 == True and check2 == True and check3 == True:
multiL()
else:
if x == 'list' and new == Blist:
global check1
check1 = True
print("that is correct, this is a list")
question()
if x == 'dictionary' and new == Dictionary:
global check2
check2 = True
print("that is correct, this is a dictonary")
question()
if x == 'tuple' and new == Tup:
global check3
check3 = True
print("that is correct, this is a tuple")
question()
if x == 're':
multiL()
else:
print("that is not one of the choices, try again?\n")
question()
def multiL():
print("done")
question()
</code></pre>
| 0 | 2016-07-27T01:26:49Z | 38,602,369 | <p>You can move the part </p>
<pre><code>awnser = ((Blist), (Dictionary), (Tup))
</code></pre>
<p>outside the <em>question</em> function.</p>
<p>Then in the if where you check if it is the correct answer, remove the possibility from awnser fx:</p>
<pre><code> if x == 'list' and newawn == Blist:
global check1
check1 = True
print("that is correct, this is a list")
awnser = ((Dictionary), (Tup)) #New line, now with tuple.
question()
</code></pre>
<p>When the tuple is empty, all 3 possibilities have been done. You can fx end with.</p>
<pre><code>Try:
newawn = (random.choice(awnser))
Except IndexError:
print("done")
return
</code></pre>
<p>P.S. It is spelled answer.</p>
| 0 | 2016-07-27T01:41:27Z | [
"python",
"python-3.x"
] |
text game if check1 and check2 and check3 statment | 38,602,286 | <p>So this is the beginning of a simple text game im working on.
When I run the program it will run through them multiple times before it can get to done. Not just one for each like I want. But I still want it to pick them at random, so I'm not sure if there is a better way to do this? Could someone tell me what I did wrong? </p>
<pre><code>import random
from collections import defaultdict
Blist = ["hash browns", "eggs", "cheese", "sausage"]
Dictionary = {"a":1,"b":1,"c":1,"d":1}
Tup = (1,2,3,4,5)
check1 = False
check2 = False
check3 = False
def question():
answer = ((Blist), (Dictionary), (Tup))
new = (random.choice(answer))
print(new)
print("which is this?")
print("a List, Dictionary, or Tuple?")
x = str(input('what is it?\n'))
if check1 == True and check2 == True and check3 == True:
multiL()
else:
if x == 'list' and new == Blist:
global check1
check1 = True
print("that is correct, this is a list")
question()
if x == 'dictionary' and new == Dictionary:
global check2
check2 = True
print("that is correct, this is a dictonary")
question()
if x == 'tuple' and new == Tup:
global check3
check3 = True
print("that is correct, this is a tuple")
question()
if x == 're':
multiL()
else:
print("that is not one of the choices, try again?\n")
question()
def multiL():
print("done")
question()
</code></pre>
| 0 | 2016-07-27T01:26:49Z | 38,602,572 | <p>You can move your first line within your function outside of the function. For now, make it a list:</p>
<pre><code>awnser = [(Blist), (Dictionary), (Tup)]
def question():
...
</code></pre>
<p>Then choose one of them at random within the function:</p>
<pre><code>def question():
newawn = (random.choice(awnser))
</code></pre>
<p>When one is chosen, you can now delete the appropriate selection from the list to avoid repetition:</p>
<pre><code>if x == 'list' and newawn == Blist:
global check1
check1 = True
print("that is correct, this is a list")
awnser.remove(Blist)
question()
</code></pre>
<p>You can use <code>awnser.remove()</code> to remove specific items from a list, such as in this case.</p>
| 0 | 2016-07-27T02:08:52Z | [
"python",
"python-3.x"
] |
text game if check1 and check2 and check3 statment | 38,602,286 | <p>So this is the beginning of a simple text game im working on.
When I run the program it will run through them multiple times before it can get to done. Not just one for each like I want. But I still want it to pick them at random, so I'm not sure if there is a better way to do this? Could someone tell me what I did wrong? </p>
<pre><code>import random
from collections import defaultdict
Blist = ["hash browns", "eggs", "cheese", "sausage"]
Dictionary = {"a":1,"b":1,"c":1,"d":1}
Tup = (1,2,3,4,5)
check1 = False
check2 = False
check3 = False
def question():
answer = ((Blist), (Dictionary), (Tup))
new = (random.choice(answer))
print(new)
print("which is this?")
print("a List, Dictionary, or Tuple?")
x = str(input('what is it?\n'))
if check1 == True and check2 == True and check3 == True:
multiL()
else:
if x == 'list' and new == Blist:
global check1
check1 = True
print("that is correct, this is a list")
question()
if x == 'dictionary' and new == Dictionary:
global check2
check2 = True
print("that is correct, this is a dictonary")
question()
if x == 'tuple' and new == Tup:
global check3
check3 = True
print("that is correct, this is a tuple")
question()
if x == 're':
multiL()
else:
print("that is not one of the choices, try again?\n")
question()
def multiL():
print("done")
question()
</code></pre>
| 0 | 2016-07-27T01:26:49Z | 38,602,796 | <p>You can do it by putting the types in a list and removing each one when it is correctly identified. The logic as a while can be simplified by using a loop and not having <code>question()</code> call itself recursively. You also don't need those global <code>check#</code> variables because you can just see there is any left in the list of typesâif not, it means each has been correctly identified.</p>
<pre><code>import random
Blist = ["hash browns", "eggs", "cheese", "sausage"]
Dictionary = {"a": 1, "b": 1, "c": 1, "d": 1}
Tup = (1, 2, 3, 4, 5)
def question():
choices = [Blist, Dictionary, Tup]
while choices: # any left?
choice = random.choice(choices) # pick a remaining one
print()
print(choice)
correct_answer = False
answer = input('what is this?\na List, Dictionary, or Tuple?\n')
answer = answer.lower()
if answer == 'list' and choice == Blist:
print("that is correct, this is a list")
correct_answer = True
elif answer == 'dictionary' and choice == Dictionary:
print("that is correct, this is a dictonary")
correct_answer = True
elif answer == 'tuple' and choice == Tup:
print("that is correct, this is a tuple")
correct_answer = True
elif answer == 're':
break
else:
print("that is not one of the choices, try again?\n")
if correct_answer:
choices.remove(choice) # remove it from list of choices
multiL()
def multiL():
print("done")
question()
</code></pre>
| 0 | 2016-07-27T02:36:38Z | [
"python",
"python-3.x"
] |
Pandas Slicing by given row AND columns indices | 38,602,288 | <p>I have the following dataframe:</p>
<pre><code>df1 = pd.DataFrame(np.random.randn(4,2),columns=["A","B"], index=["mon","tue","wed","thu"])
df1
A B
mon -1.903218 0.084362
tue -0.071207 -1.324411
wed -0.866212 -0.311787
thu -0.267956 0.802968
</code></pre>
<p>If I do the following slicing operation I get:</p>
<pre><code>df1.ix[["mon","tue"],["A","B"]]
A B
mon -1.903218 0.084362
tue -0.071207 -1.324411
</code></pre>
<p>which I suppose was intended but what I was hoping to get was just <code>[-1.903218, -1.324411]</code>. i.e. I want combined row and col indices instead of slice the rows and columns seperately.</p>
<p>Any thoughts? </p>
| 1 | 2016-07-27T01:26:59Z | 38,602,314 | <p>Instead of:</p>
<pre><code>df1.ix[["mon","tue"],["A","B"]]
</code></pre>
<p>Try:</p>
<pre><code>df1['A']['mon']
df1['B']['tue']
</code></pre>
<p>This will give you:</p>
<ul>
<li>the value located at column A, index mon</li>
<li>the value located at column B, index tue</li>
</ul>
<p>Based on this, ou can create a function to print the output as you wish. </p>
<p>For example:</p>
<pre><code>def locateDay(df, columns, rows):
#doSomething
df1[columns[0]][rows[0]]
df1[columns[1]][rows[1]]
</code></pre>
| 1 | 2016-07-27T01:32:10Z | [
"python",
"pandas"
] |
Pandas Slicing by given row AND columns indices | 38,602,288 | <p>I have the following dataframe:</p>
<pre><code>df1 = pd.DataFrame(np.random.randn(4,2),columns=["A","B"], index=["mon","tue","wed","thu"])
df1
A B
mon -1.903218 0.084362
tue -0.071207 -1.324411
wed -0.866212 -0.311787
thu -0.267956 0.802968
</code></pre>
<p>If I do the following slicing operation I get:</p>
<pre><code>df1.ix[["mon","tue"],["A","B"]]
A B
mon -1.903218 0.084362
tue -0.071207 -1.324411
</code></pre>
<p>which I suppose was intended but what I was hoping to get was just <code>[-1.903218, -1.324411]</code>. i.e. I want combined row and col indices instead of slice the rows and columns seperately.</p>
<p>Any thoughts? </p>
| 1 | 2016-07-27T01:26:59Z | 38,602,380 | <p>You probably want a <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#the-lookup-method" rel="nofollow"><code>lookup</code> method</a></p>
<pre><code>df1.lookup(["mon", "tue"], ["A", "B"])
Out[42]: array([-1.903218, -1.324411])
</code></pre>
| 4 | 2016-07-27T01:42:33Z | [
"python",
"pandas"
] |
Can open a program in IDLE but not in Terminal,Atom etc | 38,602,360 | <p>Hi I'm new to python and pygame but I am using Atom but I can't solve this problem. When I open my script in IDLE it works but I can't make it work on Atom (specifically terminal-plus) and Terminal. My error message is </p>
<pre><code>Traceback (most recent call last):
File "cargame.py", line 32, in <module>
carImg = pygame.image.load('racecar.png')
pygame.error: Failed loading libpng.dylib: dlopen(libpng.dylib, 2): image not found
</code></pre>
<p>so can anyone help?</p>
| 2 | 2016-07-27T01:40:18Z | 38,602,396 | <p>Perhaps the reason why pygame can't load the image is because it has no context of where the module is being loaded from. Make sure the module (<em>essentially the file where your source code exists</em>), and image file exist in the same environment on disk (<em>the same folder</em>). Otherwise pass an absolute path to the load function and see if the image can be located.</p>
| 1 | 2016-07-27T01:44:42Z | [
"python",
"pygame"
] |
Unicode-Ascii mixed string in python | 38,602,376 | <p>I have a string that is stored in DB as:</p>
<pre><code>FB (\u30a8\u30a2\u30eb\u30fc)
</code></pre>
<p>when I load this row from python code, I am unable to format it correctly.</p>
<pre><code># x = load that string
print x # returns u'FB (\\u30a8\\u30a2\\u30eb\\u30fc)'
</code></pre>
<p>Notice two "\" This messes up the unicode chars on frontend
Instead of showing the foreign chars, html shows it as \u30a8\u30a2\u30eb\u30fc</p>
<p>However, if I load append some characters to convert it into a json format and load the json, I get the expected result.</p>
<pre><code>s = '{"a": "%s"}'%x
json.loads(s)['a']
#prints u'FB (\u30a8\u30a2\u30eb\u30fc)'
</code></pre>
<p>Notice the difference between this result (which shows up correctly on frontend) and directly printing x (which has extra ).
So though this hacky solution works, I want a cleaner solution.
I played around a lot with x.encode('utf-8') etc, but none has worked yet.</p>
<p>Thank you!</p>
| 1 | 2016-07-27T01:42:08Z | 38,603,534 | <pre><code>raw_string = '\u30a8\u30a2\u30eb\u30fc'
string = ''.join([unichr(int(r, 16)) for r in raw_string.split('\\u') if r])
print(string)
</code></pre>
<p>A way to solve this, expecting a better answer.</p>
| 0 | 2016-07-27T04:04:44Z | [
"python",
"string",
"unicode"
] |
Unicode-Ascii mixed string in python | 38,602,376 | <p>I have a string that is stored in DB as:</p>
<pre><code>FB (\u30a8\u30a2\u30eb\u30fc)
</code></pre>
<p>when I load this row from python code, I am unable to format it correctly.</p>
<pre><code># x = load that string
print x # returns u'FB (\\u30a8\\u30a2\\u30eb\\u30fc)'
</code></pre>
<p>Notice two "\" This messes up the unicode chars on frontend
Instead of showing the foreign chars, html shows it as \u30a8\u30a2\u30eb\u30fc</p>
<p>However, if I load append some characters to convert it into a json format and load the json, I get the expected result.</p>
<pre><code>s = '{"a": "%s"}'%x
json.loads(s)['a']
#prints u'FB (\u30a8\u30a2\u30eb\u30fc)'
</code></pre>
<p>Notice the difference between this result (which shows up correctly on frontend) and directly printing x (which has extra ).
So though this hacky solution works, I want a cleaner solution.
I played around a lot with x.encode('utf-8') etc, but none has worked yet.</p>
<p>Thank you!</p>
| 1 | 2016-07-27T01:42:08Z | 38,605,537 | <p>Since you already have a Unicode string, encode it back to ASCII and decode it with the <code>unicode_escape</code> codec:</p>
<pre><code>>>> s = u'FB (\\u30a8\\u30a2\\u30eb\\u30fc)'
>>> s
u'FB (\\u30a8\\u30a2\\u30eb\\u30fc)'
>>> print s
FB (\u30a8\u30a2\u30eb\u30fc)
>>> s.encode('ascii').decode('unicode_escape')
u'FB (\u30a8\u30a2\u30eb\u30fc)'
>>> print s.encode('ascii').decode('unicode_escape')
FB (ã¨ã¢ã«ã¼)
</code></pre>
| 3 | 2016-07-27T06:43:08Z | [
"python",
"string",
"unicode"
] |
Bad Color String Error in Python Using Turtle | 38,602,434 | <p>In my python program I am reading from a file and storing the contents in a list. I checked each index of the list so I know it was stored correctly.
I am then passing a specific index to a class which contains the color blue.
Whenever it gets to the <code>turtle.color</code>I get an error <strong>bad color string: "blue"</strong></p>
<p>For example: <code>
Team = Rainbow(str(sequence[0]),str(sequence[1]), str(sequence[2])) //index 2 (str(sequence[2])) contains "blue"</code></p>
<p>The I have a class </p>
<pre><code>class Rainbow:
def __init__(self, Rname, Rteam, Rcolor):
self.name = Rname
self.team = Rteam
self.color = Rcolor
self.Rturtle = turtle.Turtle()
self.Rturtle.color(self.color)//here is where I get the error
</code></pre>
<p>I made sure everything is imported correctly and did some research on the this error and only got issues with bad sequence. Also, if I pass <code>Team = Rainbow("Jay","Blue Jays","blue")</code>I do not get the error.</p>
<p>I was wondering if someone would be able to help</p>
| 0 | 2016-07-27T01:50:52Z | 38,602,814 | <p>It might be because your colour string also contains unwanted white spaces. Change the 3rd line to <code>self.color = Rcolor.strip()</code> for example to see if it fixes the problem.</p>
| 1 | 2016-07-27T02:39:49Z | [
"python",
"python-3.x",
"colors",
"turtle-graphics"
] |
How to perform a OLS regression on dynamic data frame and estimate the slope coefficient? | 38,602,446 | <p>I have a data frame like below and it's structure is not fixed, it can have different number of column at different moment.</p>
<pre><code> A_Name B_Info Value_Yn Value_Yn-1 Value_Yn-2 ...... Value_Y1
0 AA X1 0.9 0.8 0.7 ...... 0.1
1 BB Y1 0.1 0.2 0.3 ...... 0.9
2 CC Z1 -0.9 -0.8 -0.7 ...... -0.1
3 DD L1 -0.1 -0.2 -0.3 ...... -0.9
</code></pre>
<p>I want to perform a linear regression for each row where values of X and Y are as </p>
<pre><code>X = [n, n-1, n-2, .....2, 1]
Y = [Value_Yn, Value_Yn-1, Value_Yn-2.......Value_Y2, Value_Y1]
</code></pre>
<p>Here 'n' is number of column that will be prefixed with 'Value_'</p>
<p>Let's assume that n = 9 </p>
<p>I will have value of </p>
<p>For Row 0</p>
<pre><code>X = [9, 8, 7, 6, 5, 4, 3, 2, 1]
Y = [0.9, 0.8, 0.7, 0.6, 0.5, 0.4, 0.3, 0.2, 0.1]
</code></pre>
<p>For Row 1</p>
<pre><code>X = [9, 8, 7, 6, 5, 4, 3, 2, 1]
Y = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]
</code></pre>
<p>Similarly for other rows...</p>
<p>I want output in this format... </p>
<pre><code> A_Name B_Info Intercept Slope_Coefficent
0 AA X1 0 0.1
1 BB Y1 1 -0.1
2 CC Z1 0 -0.1
3 DD L1 -1 0.1
</code></pre>
<p>Data-set is large and doing it by looping is not the correct way...</p>
| 2 | 2016-07-27T01:51:55Z | 38,604,192 | <p>This problem can be solved with numpy and linear algebra. The basic idea is that because you are reusing the same x values over and over again, we can reuse intermediate computations.</p>
<h2><b>The derivation.</b></h2>
<p>Linear regression is usually solved like this: </p>
<ol>
<li>Given a dataset (x_1, y_1) ... (x_n, y_n), we solve a least squares
problem of the form A x = b.</li>
<li>A is a n x 2 matrix with x-values as one column, and ones in the second, the vector b contains y values, and x has the slope and intercept.</li>
<li>We multiply both sides by A transpose, obtaining A^T A x= A^T b, a 2-d system that is solvable for the slope and intercept.</li>
</ol>
<p>Suppose your dataframe has k rows. You're trying to do least squares k times for the same x-values but different y-values. This translates to solving the underlying Least Squares problem k times with the same A and different b's.</p>
<p>We can exploit this in two ways. The first is to compute A^T A only once. The second, and the result of most of the speedup, is to <strong>simultaneously</strong> solve all k least squares problems at once using matrix multiplication. The idea is to stick all k b's in as the columns of a matrix B. Then, replace little b with big B on the right hand side, and do all the same matrix multiplications. You'll end up with a matrix X whose columns are in correspondence with the columns of B.</p>
<p>Note that B is the transpose of the matrix whose columns are Y_1, Y_2, ... Y_n. So it's the transpose of your dataframe.</p>
<p>In other words, X = (A^T A)^(-1) A^T B, where B is the transpose of your data frame. If the math isn't clear, here's my code (using dummy data). Please let me know if something doesn't work. </p>
<pre><code>import numpy as np
import numpy.linalg as la
n = 3
k= 10
#replace this with your data matrix whose columns are the Y's
yvals = np.arange(k*n).reshape(k,n)
xvals = np.arange(1,n+1)
print "X values:", xvals
print "Y Values:"
print yvals
A = np.zeros((n,2))
A[:,0] = xvals
A[:,1] = 1
Q = A.T.dot(A)
#slopes are the first column, intercepts are the second
res = la.inv(Q).dot(A.T.dot(yvals.T)).T
print res
</code></pre>
<p>The output:</p>
<pre><code>X values: [1 2 3]
Y Values:
[[ 0 1 2]
[ 3 4 5]
[ 6 7 8]
[ 9 10 11]
[12 13 14]
[15 16 17]
[18 19 20]
[21 22 23]
[24 25 26]
[27 28 29]]
Result:
[[ 1. -1.]
[ 1. 2.]
[ 1. 5.]
[ 1. 8.]
[ 1. 11.]
[ 1. 14.]
[ 1. 17.]
[ 1. 20.]
[ 1. 23.]
[ 1. 26.]]
</code></pre>
<p>This should be quite fast due to vectorization and asymptotic speedups from matrix multiplication.</p>
| 2 | 2016-07-27T05:12:04Z | [
"python",
"numpy",
"pandas",
"regression"
] |
Python - NameError: name 'PROTOCOL_SSLv3' is not defined, when using gevent | 38,602,466 | <p>So I had a Flask app on one machine in a virtualenv (raspberry pi running raspbian) and everything worked just fine, however when I ported it to another raspberry pi, also running raspbian, and set up a new virtualenv to the exact same specifications, running the app throws this:</p>
<p>The Flask app is a socket-io chat app, that uses ajax and stuff.</p>
<pre><code>Traceback (most recent call last):
File "application.py", line 10, in <module>
from flask.ext.socketio import SocketIO, emit
File "/home/host/chat-server/venv/local/lib/python2.7/site-packages/flask/exthook.py", line 62, in load_module
__import__(realname)
File "/home/host/chat-server/venv/local/lib/python2.7/site-packages/flask_socketio/__init__.py", line 2, in <module>
monkey.patch_all()
File "/home/host/chat-server/venv/local/lib/python2.7/site-packages/gevent/monkey.py", line 185, in patch_all
patch_socket(dns=dns, aggressive=aggressive)
File "/home/host/chat-server/venv/local/lib/python2.7/site-packages/gevent/monkey.py", line 124, in patch_socket
from gevent import socket
File "/home/host/chat-server/venv/local/lib/python2.7/site-packages/gevent/socket.py", line 659, in <module>
from gevent.ssl import sslwrap_simple as ssl, SSLError as sslerror, SSLSocket as SSLType
File "/home/host/chat-server/venv/local/lib/python2.7/site-packages/gevent/ssl.py", line 386, in <module>
def get_server_certificate(addr, ssl_version=PROTOCOL_SSLv3, ca_certs=None):
NameError: name 'PROTOCOL_SSLv3' is not defined
Exception KeyError: KeyError(3061183472L,) in <module 'threading' from '/usr/lib/python2.7/threading.pyc'> ignored
</code></pre>
<p>The process of setting up the venv was as follows,</p>
<pre><code>virtualenv venv
source venv/bin/activate
pip install -r requirements.txt
</code></pre>
<p>requirements.txt looks like,</p>
<pre><code>Flask==0.10.1
Flask-SocketIO==0.3.7
Jinja2==2.7.2
MarkupSafe==0.23
Werkzeug==0.9.4
gevent==1.0.1
gevent-socketio==0.3.6
gevent-websocket==0.9.3
greenlet==0.4.2
ipython==2.1.0
itsdangerous==0.24
pyreadline==2.0
</code></pre>
<p>and when running <code>venv/bin/pip freeze</code>, both machines give the exact same packages and versions.</p>
<p>BTW, my application.py is as follows, although I don't think it's part of the problem, since it works fine on my first machine (yes, I know it's sloppy, but it was an experiment).</p>
<pre><code>from flask.ext.socketio import SocketIO, emit
from flask import Flask, render_template, url_for, copy_current_request_context, request, session, redirect
from random import random
from time import sleep
import json, pickle, os, binascii, pickler
app = Flask(__name__)
app.config['SECRET_KEY'] = binascii.b2a_hex(os.urandom(16))
app.config['DEBUG'] = True
app.config['PICKLE_RESET'] = "KGxwMAou"
app.config['BAD_NAMES'] = ["wg4568"]
app.config['SECRET_PASSWORD'] = "thepassword"
#turn the flask app into a socketio app
socketio = SocketIO(app)
class Reciever():
def __init__(self):
self.messages = pickler.load("messages")
def send(self, user, message):
if len(message):
self.messages.insert(0, (user, message))
pickler.save(self.messages, "messages")
socketio.emit('newmsg', {'content': message, 'user': user}, namespace='/msg')
return "Sent from " + user + " that reads, " + message
else:
return "Message was blank, not sent"
def render(self):
# if not session["VIEW"]:
# return '<p id="alert"><strong>' + self.messages[0][0] + ': </strong>' + self.messages[0][1] + '</p>'
# else:
if 1:
html = ""
for msg in self.messages[:session["VIEW"]]:
if msg[0] == "ALERT":
html += '<p id="alert"><strong>' + msg[0] + ': </strong>' + msg[1] + '</p>'
else:
html += '<p><strong>' + msg[0] + ': </strong>' + msg[1] + '</p>'
return html
rec = Reciever()
@app.before_request
def before_request():
try: session["VIEW"]
except KeyError: session["VIEW"] = 0
try: session["USERNAME"]
except KeyError: session["USERNAME"] = "AnonUser-" + binascii.b2a_hex(os.urandom(4))
# if not request.url.split("/")[-1:][0] == "send":
# rec.send("ALERT", session["USERNAME"] + " has joined the room")
@app.route('/user_newid')
def user_newid():
session["USERNAME"] = "AnonUser-" + binascii.b2a_hex(os.urandom(4))
return redirect("/")
@app.route('/user_setid', methods=["POST"])
def user_setname():
username = request.form["username"]
canbypass = False
if username.split("-")[-1:][0] == app.config["SECRET_PASSWORD"]:
canbypass = True
username = username.split("-")[0]
if not username in app.config['BAD_NAMES'] or canbypass:
session["USERNAME"] = username
return redirect("/")
@app.route('/send', methods=["POST"])
def send():
user = request.form["user"]
content = request.form["content"]
return rec.send(user, content)
@app.route('/', methods=["GET", "POST"])
def index():
if request.args.get("viewall"): session["VIEW"] += 10
else: session["VIEW"] = 0
print session["VIEW"]
return render_template('index.html', old=rec.render(), username=session["USERNAME"])
@socketio.on('connect', namespace='/msg')
def test_connect():
print('Client connected')
@socketio.on('disconnect', namespace='/msg')
def test_disconnect():
# rec.send("ALERT", session["USERNAME"] + " has left the room",)
print('Client disconnected')
if __name__ == '__main__':
socketio.run(app, host="0.0.0.0")
</code></pre>
<p>Does anyone have any clue what is going on here, I am completely stumped.</p>
| 0 | 2016-07-27T01:54:02Z | 39,496,050 | <p>I solved this problem by replacing PROTOCOL_SSLv3 = PROTOCOL_SSLv23 , thank to answer of <strong>mgogoulos</strong> , link here: <a href="https://github.com/mistio/mist.io/issues/434" rel="nofollow">https://github.com/mistio/mist.io/issues/434</a></p>
| 0 | 2016-09-14T17:04:20Z | [
"python",
"flask",
"socket.io",
"virtualenv",
"gevent"
] |
Why doesn't Spyder obey my IPython config file? | 38,602,507 | <p>This used to work, but now it doesn't, in IPython 4.2.0 and Spyder 2.3.9 from Anaconda. Argh.</p>
<p>If I get the IPython config it looks correct, as though it read the file correctly:</p>
<pre><code>get_ipython().config
Out[1]:
{'IPCompleter': {'greedy': True},
'IPKernelApp': {'exec_lines': ['%pylab qt']},
'InlineBackendConfig': {},
'InteractiveShell': {'xmode': 'Plain'},
'InteractiveShellApp': {'exec_lines': ['from __future__ import division',
'from __future__ import print_function',
'from __future__ import with_statement',
'from numpy import set_printoptions',
'set_printoptions(suppress=True, precision=4)',
'from sympy import init_printing',
'init_printing(forecolor="White")'],
'pylab': 'auto'},
'StoreMagics': {'autorestore': True},
'ZMQInteractiveShell': {'autocall': 0, 'banner1': ''}}
</code></pre>
<p>So it's supposed to have future division and numpy suppression, but it actually doesn't:</p>
<pre><code>division
Out[1]: _Feature((2, 2, 0, 'alpha', 2), (3, 0, 0, 'alpha', 0), 8192)
4/5
Out[2]: 0
np.get_printoptions()
Out[3]:
{'edgeitems': 3,
'formatter': None,
'infstr': 'inf',
'linewidth': 75,
'nanstr': 'nan',
'precision': 8,
'suppress': False,
'threshold': 1000}
eps = np.finfo(float).eps; x = np.arange(4.); x**2 - (x + eps)**2
Out[4]:
array([ -4.93038066e-32, -4.44089210e-16, 0.00000000e+00,
0.00000000e+00])
</code></pre>
<p>This is what it should do:</p>
<pre><code>from __future__ import division
division
Out[2]: _Feature((2, 2, 0, 'alpha', 2), (3, 0, 0, 'alpha', 0), 8192)
4/5
Out[3]: 0.8
np.set_printoptions(suppress=True)
eps = np.finfo(float).eps; x = np.arange(4.); x**2 - (x + eps)**2
Out[5]: array([-0., -0., 0., 0.])
np.get_printoptions()
Out[6]:
{'edgeitems': 3,
'formatter': None,
'infstr': 'inf',
'linewidth': 75,
'nanstr': 'nan',
'precision': 8,
'suppress': True,
'threshold': 1000}
</code></pre>
<p>Regular IPython works correctly (<code>C:\Anaconda2\python.exe C:\Anaconda2\cwp.py C:\Anaconda2 "C:/Anaconda2/python.exe" "C:/Anaconda2/Scripts/ipython-script.py"</code>) </p>
<p>Jupyter QTConsole works correctly (<code>C:\Anaconda2\pythonw.exe C:\Anaconda2\cwp.py C:\Anaconda2 "C:/Anaconda2/pythonw.exe" "C:/Anaconda2/Scripts/jupyter-qtconsole-script.py"</code>)</p>
| 13 | 2016-07-27T02:00:38Z | 39,629,910 | <p>im not sure what is the problem either
I was having the same issue</p>
<p>but mine was fixed when I uninstalled anaconda with EVERYTHING including its python bit
granted I saved the settings and profile and stuff</p>
<p>and reinstalled</p>
<p>Hope that helps, if its an option at all</p>
| 0 | 2016-09-22T03:46:58Z | [
"python",
"numpy",
"ipython",
"anaconda",
"spyder"
] |
Python: Shorten concatenation by using inline conditionals | 38,602,574 | <p>If the title is a bit obscure, an example of what I would like to do is:</p>
<p><code>print("Status: " + if serverIsOnline: "Online" else: "Offline")</code></p>
<p>I know this is improper, but what I am trying to do is check if <code>serverIsOnline</code> is <code>True</code> then print <code>Status: Online</code> else <code>Status: Offline</code>. I know it's possibe, I have seen it done, but I can't remember how it was done.</p>
<p>This is a shorter equivalent of:</p>
<pre><code>if serverIsOnline:
print("Status: Online")
else:
print("Status: Offline")
</code></pre>
<p>Could someone please refresh me?</p>
| 0 | 2016-07-27T02:08:54Z | 38,602,588 | <p>Python allows inline <code>if/else</code> as long as an <code>else</code> is specified (<code>if</code> only is a SyntaxError). Most Python programmers refer to this as its ternary:</p>
<pre><code>>>> server_online = True
>>> print('Status: ' + ('Online' if server_online else 'Offline'))
Status: Online
>>> server_online = False
>>> print('Status: ' + ('Online' if server_online else 'Offline'))
Status: Offline
>>> print('Status: ' + 'Online' if server_online)
File "<stdin>", line 1
print('Status: ' + 'Online' if server_online)
^
SyntaxError: invalid syntax
</code></pre>
| 1 | 2016-07-27T02:10:53Z | [
"python",
"python-3.x",
"if-statement",
"printing",
"concatenation"
] |
Python: Shorten concatenation by using inline conditionals | 38,602,574 | <p>If the title is a bit obscure, an example of what I would like to do is:</p>
<p><code>print("Status: " + if serverIsOnline: "Online" else: "Offline")</code></p>
<p>I know this is improper, but what I am trying to do is check if <code>serverIsOnline</code> is <code>True</code> then print <code>Status: Online</code> else <code>Status: Offline</code>. I know it's possibe, I have seen it done, but I can't remember how it was done.</p>
<p>This is a shorter equivalent of:</p>
<pre><code>if serverIsOnline:
print("Status: Online")
else:
print("Status: Offline")
</code></pre>
<p>Could someone please refresh me?</p>
| 0 | 2016-07-27T02:08:54Z | 38,602,589 | <p>What you're looking for is a <a href="http://book.pythontips.com/en/latest/ternary_operators.html" rel="nofollow">conditional expression</a> (<em>also known as a 'ternary' expression, usually with a</em> <code>?</code> <em>operator, used by many other languages</em>).</p>
<pre><code>print("Status: " + "Online" if serverIsOnline else "Offline")
</code></pre>
<p>Syntax: <code>True if condition else False</code></p>
| 4 | 2016-07-27T02:11:03Z | [
"python",
"python-3.x",
"if-statement",
"printing",
"concatenation"
] |
How do I fix the "image "pyimage10" doesn't exist" error, and why does it happen? | 38,602,594 | <p>I am making a tkiner application and that shows a user a page with some basic information and a picture before allowing them to click a button to view live Bitcoin price data. However, when I added the image to the 'start up' page, I got this error from my IDE:</p>
<pre><code> BTC_img_label = tk.Label(self, image=BTC_img)
File "C:\Python34\lib\tkinter\__init__.py", line 2609, in __init__
Widget.__init__(self, master, 'label', cnf, kw)
File "C:\Python34\lib\tkinter\__init__.py", line 2127, in __init__
(widgetName, self._w) + extra + self._options(cnf))
_tkinter.TclError: image "pyimage10" doesn't exist
</code></pre>
<p>I believe that these are the lines of code that are causing my error (they are the same lines that add the image to the 'start up' page):</p>
<pre><code>BTC_img = tk.PhotoImage(file='bitcoin.png')
BTC_img_label = tk.Label(self, image=BTC_img)
BTC_img_label.image = BTC_img
BTC_img_label.grid(row=2, column=0)
</code></pre>
<p>I also noticed that the icon that I set does not show in the GUI window when the program is run, only the default Tkinter feather icon. Here's my icon setting code if anyone is interested (though I'm pretty sure it's not causing my error):</p>
<pre><code>tk.Tk.iconbitmap(self, default='main.ico')
</code></pre>
<p>And yes, for anyone wondering, I did import tkinter as tk, so that is not my error. If anyone could also tell me why this error happens, I would be very interested: I haven't seen a lot of other examples of this happening, and the ones I have seen had no mention to my icon problem. Hope somebody can figure this out!</p>
| 1 | 2016-07-27T02:11:40Z | 38,603,572 | <p>You can not load a <strong>.png</strong> format with tkinter. You rather need to use the <a href="http://www.pythonware.com/products/pil/" rel="nofollow">PIL</a> library for that:</p>
<pre><code>import PIL
image = PIL.Image.open("bitcoin.png")
BTC_img = PIL.ImageTk.PhotoImage(image)
BTC_img_label = tk.Label(self, image=BTC_img)
BTC_img_label.image = BTC_img
BTC_img_label.grid(row=2, column=0)
</code></pre>
<p><strong>EDIT:</strong></p>
<p>Please, create a <code>test.py</code> file and run this EXACT code:</p>
<pre><code>import tkinter as tk
from PIL import Image, ImageTk
root = tk.Tk()
image = Image.open("bitcoin.png")
photo = ImageTk.PhotoImage(image)
label = tk.Label(root, image=photo)
label.image = photo
label.grid(row=2, column=0)
#Start the program
root.mainloop()
</code></pre>
<p>Tell me if you get an error or not.</p>
| 1 | 2016-07-27T04:10:04Z | [
"python",
"image-processing",
"tkinter"
] |
UnicodeEncodeError: 'latin-1' codec can't encode characters in position 0-5: ordinal not in range(256) | 38,602,628 | <p>everyone!
I use python3(pycharm),and my codes are like these:</p>
<pre><code># -*- coding: utf-8 -*-
import numpy
c=numpy.loadtxt('test.csv',dtype="str_",delimiter=',',usecols=(6,),unpack=True)
</code></pre>
<p>when I have some Chinese words in test.csv,I got a error like this:</p>
<pre><code>UnicodeEncodeError: 'latin-1' codec can't encode characters in position 0-5: ordinal not in range(256)
</code></pre>
<p>I have tried to encode the file,like this:</p>
<pre><code>c=numpy.loadtxt('test.csv'.encode('utf-8'),dtype="str_",skiprows=0,delimiter=',',usecols=(6,),unpack=True)
</code></pre>
<p>And then,I got another error:</p>
<pre><code>IndexError: list index out of range
</code></pre>
<p>Besides,the Chinese words in the file are longer than 64.</p>
<p>I have waste a lot of time on this,Please give me a handï¼</p>
| 0 | 2016-07-27T02:15:12Z | 38,603,675 | <pre><code>with open('test.csv', encoding='utf-8') as fh:
numpy.loadtxt(fh, dtype="str_", delimiter=',', usecols=(6,), unpack=True)
</code></pre>
| 0 | 2016-07-27T04:23:21Z | [
"python"
] |
UnicodeEncodeError: 'latin-1' codec can't encode characters in position 0-5: ordinal not in range(256) | 38,602,628 | <p>everyone!
I use python3(pycharm),and my codes are like these:</p>
<pre><code># -*- coding: utf-8 -*-
import numpy
c=numpy.loadtxt('test.csv',dtype="str_",delimiter=',',usecols=(6,),unpack=True)
</code></pre>
<p>when I have some Chinese words in test.csv,I got a error like this:</p>
<pre><code>UnicodeEncodeError: 'latin-1' codec can't encode characters in position 0-5: ordinal not in range(256)
</code></pre>
<p>I have tried to encode the file,like this:</p>
<pre><code>c=numpy.loadtxt('test.csv'.encode('utf-8'),dtype="str_",skiprows=0,delimiter=',',usecols=(6,),unpack=True)
</code></pre>
<p>And then,I got another error:</p>
<pre><code>IndexError: list index out of range
</code></pre>
<p>Besides,the Chinese words in the file are longer than 64.</p>
<p>I have waste a lot of time on this,Please give me a handï¼</p>
| 0 | 2016-07-27T02:15:12Z | 38,603,745 | <p>When we read the Chinese character to numpy, the data type cannot be a simple string because it treats the character as ASCII which is not long enough to hold the UTF-8 character.</p>
<p>So what I have done here is to let numpy knows we are reading a 4-byte character instead which is sufficient to hold an unicode character.</p>
<p>I have used the following sample data for testing:</p>
<pre><code>1,2,3,4,5,6,7
ä¸,äº,ä¸,å,äº,å
,ä¸
</code></pre>
<p>Here is the code I have used:</p>
<pre><code># -*- coding: utf-8 -*-
import numpy
c=numpy.genfromtxt('test.csv',dtype="S4",delimiter=',',usecols=(6,),unpack=True)
for txt in c:
print(txt.decode("utf-8"))
</code></pre>
<p>You can further check the below links to learn more:<br>
1. <a href="http://stackoverflow.com/questions/5290182/how-many-bytes-does-one-unicode-character-take">How many bytes does one Unicode character take?</a><br>
2. <a href="http://docs.scipy.org/doc/numpy/reference/arrays.dtypes.html" rel="nofollow">Numpy Data type objects</a></p>
| 0 | 2016-07-27T04:29:51Z | [
"python"
] |
confused value scope in python | 38,602,718 | <p>Hi I have staring programming with c and I conld'nt understand value scope in python.</p>
<p>here is my code</p>
<pre><code>class ScenarioEnvironment():
def __init__(self):
print(self)
class report():
config = ScenarioEnvironment()
def __init__(self):
self.config = ScenarioEnvironment()
</code></pre>
<p>what happens passing config and config at init()?</p>
<p>and I wonder the value scope which config will be class valuable?</p>
| 1 | 2016-07-27T02:27:29Z | 38,602,809 | <p>Since your question seems a bit ambiguous, I'll just comment/fix your code:</p>
<pre><code>class ScenarioEnvironment():
def __init__(self,x):
self.x = x # Assigning instance variable x to constructor parameter x.
print(self) # You're printing the object instance.
class report():
# Static variable shared amongst all classes.
config = ScenarioEnvironment(None) # Assigned to new instance of ScenarioEnvironment.
def __init__(self):
# No argument, must pass one (None).
# self.config is to a new ScenarioEnvironment instance.
self.config = ScenarioEnvironment(None)
</code></pre>
<p>Lets try out the classes.<br>
<br><strong>Output:</strong></p>
<pre><code>s = ScenarioEnvironment(None)
r = report()
>>> <__main__.ScenarioEnvironment instance at 0x026F4238>
>>> <__main__.ScenarioEnvironment instance at 0x026F4300>
>>> <__main__.ScenarioEnvironment instance at 0x026F4350>
</code></pre>
| 1 | 2016-07-27T02:39:15Z | [
"python"
] |
confused value scope in python | 38,602,718 | <p>Hi I have staring programming with c and I conld'nt understand value scope in python.</p>
<p>here is my code</p>
<pre><code>class ScenarioEnvironment():
def __init__(self):
print(self)
class report():
config = ScenarioEnvironment()
def __init__(self):
self.config = ScenarioEnvironment()
</code></pre>
<p>what happens passing config and config at init()?</p>
<p>and I wonder the value scope which config will be class valuable?</p>
| 1 | 2016-07-27T02:27:29Z | 38,602,876 | <p>You need to know the differences between class attribute and instance object attribute.
Maybe these codes will help you:</p>
<pre><code>class TestConfig1(object):
config = 1
def __init__(self):
self.config = 2
class TestConfig2(object):
config = 1
def __init__(self):
self.config2 = 2
if __name__ == "__main__":
print TestConfig1.config
t = TestConfig1()
print t.config
t2 = TestConfig2()
print t2.config
print t2.config2
</code></pre>
<p>more you can see the python blog.<a href="http://www.cnblogs.com/worldisimple/archive/2012/04/20/2460632.html" rel="nofollow">click here</a></p>
| 2 | 2016-07-27T02:46:16Z | [
"python"
] |
Conditional URL scraping with Scrapy | 38,602,790 | <p>I am trying to use Scrapy on a site which I do not know the URL structure of.</p>
<p>I would like to:</p>
<ul>
<li><p><strong>only</strong> extract data from pages which contain Xpath "//div[@class="product-view"]".</p></li>
<li><p>extract print (in CSV) the URL, the name and price Xpaths</p></li>
</ul>
<p>When I run the below script, all I get is a random list of URL's</p>
<p><code>scrapy crawl dmoz>test.txt</code></p>
<pre><code>from scrapy.selector import HtmlXPathSelector
from scrapy.spider import BaseSpider
from scrapy.http import Request
DOMAIN = 'site.com'
URL = 'http://%s' % DOMAIN
class MySpider(BaseSpider):
name = "dmoz"
allowed_domains = [DOMAIN]
start_urls = [
URL
]
def parse(self, response):
for url in response.xpath('//a/@href').extract():
if not ( url.startswith('http://') or url.startswith('https://') ):
url= URL + url
if response.xpath('//div[@class="product-view"]'):
url = response.extract()
name = response.xpath('//div[@class="product-name"]/h1/text()').extract()
price = response.xpath('//span[@class="product_price_details"]/text()').extract()
yield Request(url, callback=self.parse)
print url
</code></pre>
| 0 | 2016-07-27T02:36:04Z | 38,606,431 | <p>What you are lookin here is for <a href="http://doc.scrapy.org/en/latest/topics/spiders.html?#crawlspider" rel="nofollow">scrapy.spiders.Crawlspider</a>. </p>
<p>However you almost got it with your own approach. Here's the fixed version.</p>
<pre><code>from scrapy.linkextractors import LinkExtractor
def parse(self, response):
# parse this page
if response.xpath('//div[@class="product-view"]'):
item = dict()
item['url'] = response.url
item['name'] = response.xpath('//div[@class="product-name"]/h1/text()').extract_first()
item['price'] = response.xpath('//span[@class="product_price_details"]/text()').extract_first()
yield item # return an item with your data
# other pages
le = LinkExtractor() # linkextractor is smarter than xpath '//a/@href'
for link in le.extract_links(response):
yield Request(link.url) # default callback is already self.parse
</code></pre>
<p>Now you can simply run <code>scrapy crawl myspider -o results.csv</code> and scrapy will output csv of your items. Though keep an eye on the log and the stats bit at the end especially, that's how you know if something went wrong</p>
| 1 | 2016-07-27T07:24:37Z | [
"python",
"xpath",
"scrapy"
] |
Python sorting dictionary | 38,602,843 | <p>I want to sort the following <strong>dictionary</strong> by the keys <code>score</code>, which is an array.</p>
<pre><code>student = {"name" : [["Peter"], ["May"], ["Sharon"]],
"score" : [[1,5,3], [3,2,6], [5,9,2]]}
</code></pre>
<p>For a better representation:</p>
<pre><code>Peter ---- [1,5,3]
May ---- [3,2,6]
Sharon ---- [5,9,2]
</code></pre>
<p>Here I want to use the <strong>second element</strong> of <code>score</code> to sort the <code>name</code> into a list.</p>
<p>The expected result is:</p>
<pre><code>name_list = ("May ", "Peter", "Sharon")
</code></pre>
<p>I have tried to use </p>
<p><code>sorted_x = sorted(student.items(), key=operator.itemgetter(1))</code></p>
<p>and</p>
<pre><code>for x in sorted(student, key=lambda k: k['score'][1]):
name_list.append(x['name'])
</code></pre>
<p>but both dont work.</p>
| 0 | 2016-07-27T02:42:31Z | 38,602,969 | <p>First zip the students name and score use <code>zip</code>.</p>
<pre><code>zip(student["name"], student["score"])
</code></pre>
<p>you will get better representation:</p>
<pre><code>[(['May'], [3, 2, 6]),
(['Peter'], [1, 5, 3]),
(['Sharon'], [5, 9, 2])]
</code></pre>
<p>then sort this list and get the student name:</p>
<pre><code>In [10]: [ i[0][0] for i in sorted(zip(student["name"], student["score"]), key=lambda x: x[1][1])]
Out[10]: ['May', 'Peter', 'Sharon']
</code></pre>
<p>Know about the sorted buildin function first: <a href="https://docs.python.org/2/howto/sorting.html#sortinghowto" rel="nofollow">https://docs.python.org/2/howto/sorting.html#sortinghowto</a></p>
| 3 | 2016-07-27T02:58:31Z | [
"python"
] |
Python sorting dictionary | 38,602,843 | <p>I want to sort the following <strong>dictionary</strong> by the keys <code>score</code>, which is an array.</p>
<pre><code>student = {"name" : [["Peter"], ["May"], ["Sharon"]],
"score" : [[1,5,3], [3,2,6], [5,9,2]]}
</code></pre>
<p>For a better representation:</p>
<pre><code>Peter ---- [1,5,3]
May ---- [3,2,6]
Sharon ---- [5,9,2]
</code></pre>
<p>Here I want to use the <strong>second element</strong> of <code>score</code> to sort the <code>name</code> into a list.</p>
<p>The expected result is:</p>
<pre><code>name_list = ("May ", "Peter", "Sharon")
</code></pre>
<p>I have tried to use </p>
<p><code>sorted_x = sorted(student.items(), key=operator.itemgetter(1))</code></p>
<p>and</p>
<pre><code>for x in sorted(student, key=lambda k: k['score'][1]):
name_list.append(x['name'])
</code></pre>
<p>but both dont work.</p>
| 0 | 2016-07-27T02:42:31Z | 38,602,997 | <p>This would probably work for you:</p>
<pre><code>student = {
"name": [["Peter"], ["May"], ["Sharon"]],
"score": [[1,5,3], [3,2,6], [5,9,2]]
}
# pair up the names and scores
# this gives one tuple for each student:
# the first item is their name as a 1-item list
# the second item is their list of scores
pairs = zip(student['name'], student['score'])
# sort the tuples by the second score:
pairs_sorted = sorted(
pairs,
key=lambda t: t[1][1]
)
# get the names, in order
names = [n[0] for n, s in pairs_sorted]
print names
# ['May', 'Peter', 'Sharon']
</code></pre>
| 1 | 2016-07-27T03:03:00Z | [
"python"
] |
Python sorting dictionary | 38,602,843 | <p>I want to sort the following <strong>dictionary</strong> by the keys <code>score</code>, which is an array.</p>
<pre><code>student = {"name" : [["Peter"], ["May"], ["Sharon"]],
"score" : [[1,5,3], [3,2,6], [5,9,2]]}
</code></pre>
<p>For a better representation:</p>
<pre><code>Peter ---- [1,5,3]
May ---- [3,2,6]
Sharon ---- [5,9,2]
</code></pre>
<p>Here I want to use the <strong>second element</strong> of <code>score</code> to sort the <code>name</code> into a list.</p>
<p>The expected result is:</p>
<pre><code>name_list = ("May ", "Peter", "Sharon")
</code></pre>
<p>I have tried to use </p>
<p><code>sorted_x = sorted(student.items(), key=operator.itemgetter(1))</code></p>
<p>and</p>
<pre><code>for x in sorted(student, key=lambda k: k['score'][1]):
name_list.append(x['name'])
</code></pre>
<p>but both dont work.</p>
| 0 | 2016-07-27T02:42:31Z | 38,603,098 | <p>If you want to use dictionaries, I suggest using <code>OrderedDict</code>:</p>
<pre><code>name = ["Peter", "May", "Sharon"]
score = [[1,5,3], [3,2,6], [5,9,2]]
d = {n: s for (n, s) in zip(name, score)}
from collections import OrderedDict
ordered = OrderedDict(sorted(d.items(), key=lambda t: t[1][1]))
list(ordered) # to retrieve the names
</code></pre>
<p>But, if not, the following would be a simpler approach:</p>
<pre><code>name = ["Peter", "May", "Sharon"]
score = [[1,5,3], [3,2,6], [5,9,2]]
d = [(n, s) for (n, s) in zip(name, score)]
ordered = sorted(d, key=lambda t: t[1][1])
names_ordered = [item[0] for item in ordered]
</code></pre>
| 0 | 2016-07-27T03:14:31Z | [
"python"
] |
Max Drawdown with Minimum Window Length | 38,602,884 | <p>For a given time series of floats, it is pretty easy to calculate an unconstrained maximum drawdown in <code>O(n)</code> time, where max drawdown is defined as </p>
<pre><code>\min_{i,j, i<j}(x_j - x_i)
</code></pre>
<p>In python, we the calculation is <code>min(x - numpy.expanding_max(x))</code>, but to get a <code>O(n)</code> algo write it explicitly:</p>
<pre><code>def max_drawdown(s):
drawdn = 0
m,M = s[0],s[0]
t1,t2 = 0,0
T1,T2 = 0,0
for i,v in enumerate(s):
if (v < m):
if (v-m) < drawdn:
drawdn = v-m
t2 = i
T1,T2 = t1,t2
else:
m = v
t1 = i
return T1,T2,drawdn
</code></pre>
<p>Is there an <code>O(n)</code> algorithm for a max_drawdown that is constrained to have window duration > min_length? In this case I want \min_{i,j, (j-i) > min_length}(x_j - x_i).</p>
<p>Note that this is not a "rolling drawdown" calculation as in <a href="http://stackoverflow.com/questions/21058333/compute-rolling-maximum-drawdown-of-pandas-series">Compute *rolling* maximum drawdown of pandas Series</a>. </p>
| 1 | 2016-07-27T02:47:28Z | 38,612,201 | <p>The modifications are quite small compared to your <code>max_drawdown</code> function. The current algorithm can be written in pseudocode </p>
<pre><code>Iterate over list
if (current_element > maximum)
maximum = current_element
if (current element - maximum < drawdn)
drawdn = current_element-maximum
</code></pre>
<p>Now instead of searching the <code>max_drawdown</code> at same index we search for the maximum value we need to have a distance of <code>min_length</code> with those indexes. In Python this becomes:</p>
<pre><code>def max_drawdown_min_lenght(s,min_length):
min_length += 1 #this is for i-j > l (not i-j >= l)
drawdn = 0
m = s[0]
t1 = 0
T1,T2 = 0,0
for i in range(len(s)-min_length):
if (s[i] >= m): #do we have new maximum?
m = s[i]
t1 = i
if (s[i+min_length]-m) < drawdn:#do we have new max drawdown?
drawdn = s[i+min_length]-m
T1,T2 = t1,i+min_length
return T1,T2,drawdn
</code></pre>
| 1 | 2016-07-27T11:52:57Z | [
"python",
"algorithm"
] |
Python - listing prime numbers from 1 to 1000 including 1 | 38,602,892 | <p>This program is for listing all the prime numbers between 1 and 1000, but my teacher would like me to include 1 in the results. </p>
<p>I tried to change it to say <code>if num >= 1:</code> and <code>for i in range(1,num)</code>, but then when I ran it, the only result was <code>1 is a prime number!</code>. Thanks!</p>
<pre><code>for num in range(1,1001):
if num > 1:
for i in range(2,num):
if (num % i) == 0:
break
else:
print(num,"is a prime number!")
</code></pre>
| 0 | 2016-07-27T02:48:29Z | 38,603,027 | <p>You should not write <code>for i in range(1, num):</code>, because <code>(any number) % 1 == 0</code>. <code>if num >= 1:</code> can also be removed, because it's always true.</p>
<p>Try the following code:</p>
<pre><code>for num in range(1, 1001):
for i in range(2, num):
if num % i == 0:
break
else:
print num, 'is a prime number'
</code></pre>
<p>And remember, technically speaking, <code>1</code> isn't a prime number.</p>
| 1 | 2016-07-27T03:05:50Z | [
"python"
] |
Python - listing prime numbers from 1 to 1000 including 1 | 38,602,892 | <p>This program is for listing all the prime numbers between 1 and 1000, but my teacher would like me to include 1 in the results. </p>
<p>I tried to change it to say <code>if num >= 1:</code> and <code>for i in range(1,num)</code>, but then when I ran it, the only result was <code>1 is a prime number!</code>. Thanks!</p>
<pre><code>for num in range(1,1001):
if num > 1:
for i in range(2,num):
if (num % i) == 0:
break
else:
print(num,"is a prime number!")
</code></pre>
| 0 | 2016-07-27T02:48:29Z | 38,605,733 | <p>Leave your code as is and above the main for loop add:</p>
<pre><code>print("1 is a prime number")
</code></pre>
| 0 | 2016-07-27T06:53:19Z | [
"python"
] |
In PyQt4 how do i initiate a window | 38,602,951 | <p>Hello I am a student that is experimenting with GUI's and I was working in python making a simple log-in form and as I made the base layout I encountered an error where I could not solve the variables. This is the code: </p>
<pre><code>try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig)
def main():
app = QtGui.QApplication(sys.argv)
w = Ui_Dialog(__init__)
w.show()
sys.exit(app.exec_())
class Ui_Dialog(object):
def __init__(self, parent=None):
QtGui.QMainWindow.__init__(self, parent)
self.addWidgets()
self.setupUi(self)
def setupUi(self, Dialog):
Dialog.setObjectName(_fromUtf8("Dialog"))
Dialog.resize(380, 272)
Dialog.setMinimumSize(QtCore.QSize(380, 272))
Dialog.setMaximumSize(QtCore.QSize(380, 272))
self.buttonBox = QtGui.QDialogButtonBox(Dialog)
self.buttonBox.setGeometry(QtCore.QRect(30, 240, 341, 32))
self.buttonBox.setOrientation(QtCore.Qt.Horizontal)
self.buttonBox.setStandardButtons(QtGui.QDialogButtonBox.Cancel|QtGui.QDialogButtonBox.Ok)
self.buttonBox.setCenterButtons(True)
self.buttonBox.setObjectName(_fromUtf8("buttonBox"))
self.user_name = QtGui.QTextEdit(Dialog)
self.user_name.setGeometry(QtCore.QRect(110, 50, 221, 31))
self.user_name.setAutoFillBackground(False)
self.user_name.setObjectName(_fromUtf8("user_name"))
self.user_pass = QtGui.QTextEdit(Dialog)
self.user_pass.setGeometry(QtCore.QRect(110, 120, 221, 31))
self.user_pass.setAutoFillBackground(False)
self.user_pass.setObjectName(_fromUtf8("user_pass"))
self.label = QtGui.QLabel(Dialog)
self.label.setGeometry(QtCore.QRect(20, 60, 81, 21))
self.label.setObjectName(_fromUtf8("label"))
self.label_2 = QtGui.QLabel(Dialog)
self.label_2.setGeometry(QtCore.QRect(20, 120, 81, 21))
self.label_2.setObjectName(_fromUtf8("label_2"))
self.retranslateUi(Dialog)
QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL(_fromUtf8("accepted()")), Dialog.accept)
QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL(_fromUtf8("rejected()")), Dialog.reject)
QtCore.QMetaObject.connectSlotsByName(Dialog)
def retranslateUi(self, Dialog):
Dialog.setWindowTitle(_translate("Dialog", "Dialog", None))
self.label.setText(_translate("Dialog", "USER NAME", None))
self.label_2.setText(_translate("Dialog", "PASSWORD", None))
if __name__ == "__main__":
main()
</code></pre>
<p>sorry if the alignment is off i am not used to having to use stack overflow but the code results in the following output:</p>
<pre><code>Traceback (most recent call last):
File "C:\Users\todd7\Desktop\PY_auth\design.py", line 75, in <module>
main()
File "C:\Users\todd7\Desktop\PY_auth\design.py", line 28, in main
w = Ui_Dialog(__init__)
NameError: name '__init__' is not defined
</code></pre>
<p>and i am not sure how to fix the issue.</p>
| 0 | 2016-07-27T02:56:57Z | 38,638,767 | <p>Try making your <code>__init__</code> function in your <code>Ui_Dialog</code> class this:</p>
<pre><code>def __init__(self, window, parent=None):
self.addWidgets()
self.setupUi(self)
window.show()
</code></pre>
<p>Then, in your <code>main()</code> function, </p>
<pre><code>def main():
app = QtGui.QApplication(sys.argv)
w = Ui_Dialog(QtGui.QMainWindow())
sys.exit(app.exec_())
</code></pre>
| 0 | 2016-07-28T14:03:06Z | [
"python",
"user-interface",
"pyqt4"
] |
Python Class Method Error -- unbound requires instance | 38,602,963 | <p>I'm calling </p>
<pre><code>Hardware.gpio_active(True)
</code></pre>
<p>This is my Hardware class:</p>
<pre><code>import os
import glob
import time
import RPi.GPIO as GPIO
#class to manage hardware -- sensors, pumps, etc
class Hardware(object):
#global vars for sensor
base_dir = '/sys/bus/w1/devices/'
device_folder = glob.glob(base_dir + '28*')[0]
device_file = device_folder + '/w1_slave'
#global var for program
temp_unit = 'F' #temperature unit, choose C for Celcius or F for F for Farenheit
gpio_pin = 17
#function to enable GPIO
@classmethod
def gpio_active(active):
#system params for sensor
if active is True:
os.system('modprobe w1-gpio')
os.system('modprobe w1-therm')
GPIO.setmode(GPIO.BCM)
GPIO.setup(Hardware.gpio_pin, GPIO.OUT)
print 'activating GPIO'
else:
print 'deactivating GPIO'
GPIO.cleanup()
</code></pre>
<p>I get this error:</p>
<blockquote>
<p>TypeError: unbound method gpio_active() must be called with Hardware
instance as first argument (got bool instance instead)</p>
</blockquote>
<p>I don't want to pass an instance -- I want <code>gpio_active()</code> to basically act as a function but retain accessibility to static class variables. I thought this is what <code>@classmethod</code> was for. I get the same error with <code>@staticmethod</code>.</p>
<p>What am I misunderstanding?</p>
| 0 | 2016-07-27T02:58:05Z | 38,602,987 | <p>Just replace <code>def gpio_active(active)</code> to <code>def gpio_active(cls, active)</code>.</p>
<p>Read more about <code>@classmethod</code> here: <a href="https://julien.danjou.info/blog/2013/guide-python-static-class-abstract-methods" rel="nofollow">https://julien.danjou.info/blog/2013/guide-python-static-class-abstract-methods</a></p>
| 1 | 2016-07-27T03:01:26Z | [
"python",
"class",
"static-methods"
] |
Python Class Method Error -- unbound requires instance | 38,602,963 | <p>I'm calling </p>
<pre><code>Hardware.gpio_active(True)
</code></pre>
<p>This is my Hardware class:</p>
<pre><code>import os
import glob
import time
import RPi.GPIO as GPIO
#class to manage hardware -- sensors, pumps, etc
class Hardware(object):
#global vars for sensor
base_dir = '/sys/bus/w1/devices/'
device_folder = glob.glob(base_dir + '28*')[0]
device_file = device_folder + '/w1_slave'
#global var for program
temp_unit = 'F' #temperature unit, choose C for Celcius or F for F for Farenheit
gpio_pin = 17
#function to enable GPIO
@classmethod
def gpio_active(active):
#system params for sensor
if active is True:
os.system('modprobe w1-gpio')
os.system('modprobe w1-therm')
GPIO.setmode(GPIO.BCM)
GPIO.setup(Hardware.gpio_pin, GPIO.OUT)
print 'activating GPIO'
else:
print 'deactivating GPIO'
GPIO.cleanup()
</code></pre>
<p>I get this error:</p>
<blockquote>
<p>TypeError: unbound method gpio_active() must be called with Hardware
instance as first argument (got bool instance instead)</p>
</blockquote>
<p>I don't want to pass an instance -- I want <code>gpio_active()</code> to basically act as a function but retain accessibility to static class variables. I thought this is what <code>@classmethod</code> was for. I get the same error with <code>@staticmethod</code>.</p>
<p>What am I misunderstanding?</p>
| 0 | 2016-07-27T02:58:05Z | 38,602,998 | <p>You can use a <code>staticmethod</code>:</p>
<pre><code>@staticmethod
def gpio_active(active):
...
</code></pre>
<p>But it looks like you should be using a <code>classmethod</code> so you have access to other static/class methods for that class, or access to the class-level variables:</p>
<pre><code>@classmethod
def gpio_active(cls, active):
...
</code></pre>
<p>Then replace <code>Hardware.gpio_pin</code> with <code>cls.gpio_pin</code></p>
| 1 | 2016-07-27T03:03:06Z | [
"python",
"class",
"static-methods"
] |
Getting a value from DataFrame based on other column value (PySpark) | 38,602,973 | <p>I have a Spark dataframe which I want to get the statistics</p>
<pre><code>stats_df = df.describe(['mycol'])
stats_df.show()
+-------+------------------+
|summary| mycol|
+-------+------------------+
| count| 300|
| mean| 2243|
| stddev| 319.419860456123|
| min| 1400|
| max| 3100|
+-------+------------------+
</code></pre>
<p>How do I extract the values of <code>min</code> and <code>max</code> in <code>mycol</code> using the <code>summary</code> <code>min</code> <code>max</code> column values? How do I do it by number index?</p>
| 0 | 2016-07-27T02:59:00Z | 38,605,754 | <p>Ok let's consider the following example : </p>
<pre><code>from pyspark.sql.functions import rand, randn
df = sqlContext.range(1, 1000).toDF('mycol')
df.describe().show()
# +-------+-----------------+
# |summary| mycol|
# +-------+-----------------+
# | count| 999|
# | mean| 500.0|
# | stddev|288.5307609250702|
# | min| 1|
# | max| 999|
# +-------+-----------------+
</code></pre>
<p>If you want to access the row concerning stddev, per example, you'll just need to convert it into an RDD, collect it and convert it into a dictionary as following :</p>
<pre><code>stats = dict(df.describe().map(lambda r : (r.summary,r.mycol)).collect())
print(stats['stddev'])
# 288.5307609250702
</code></pre>
| 1 | 2016-07-27T06:54:42Z | [
"python",
"apache-spark",
"dataframe",
"pyspark",
"spark-dataframe"
] |
Print without unneeded Spaces | 38,602,982 | <p>I have just started out with Python, and am using Idle.</p>
<p>I put in:</p>
<pre><code>print("Professor Redwood: Right! So your name is",name,"!")
</code></pre>
<p>And got this in the console:</p>
<pre><code>Professor Redwood: Right! So your name is Chase !
</code></pre>
<p>Notice the spaces around the name <code>"Chase"</code>. I can't figure out how to get rid of these spaces. I looked up this question, and went to <a href="http://stackoverflow.com/questions/24692694/unwanted-blank-space-after-variable">this page</a>. I could not understand what the answer meant, so I need some help with it.</p>
<p>(Please note that I have already set the variable.)</p>
| 0 | 2016-07-27T03:00:20Z | 38,603,003 | <p>By default, the Python <code>print</code> function uses a separation set to a single space when printing arguments; you can easily override this by defining <code>sep=''</code> (i.e empty space):</p>
<pre><code>print("Professor Redwood: Right! So your name is",name,"!", sep='')
</code></pre>
<p>Which will now <code>print</code>:</p>
<pre><code>Professor Redwood: Right! So your name isChase!
</code></pre>
<hr>
<p>For Python <code>2.x</code> you could either use <code>from __future__ import print_function</code> and if that doesn't suit you for some undisclosed reason, use <code>join</code> to explicitly join on the empty string:</p>
<pre><code>print "".join(["Professor Redwood: Right! So your name is",name,"!"])
</code></pre>
<p>or, use <code>.format</code> as the other answer suggests:</p>
<pre><code>print "Professor Redwood: Right! So your name is{0}!".format(name)
</code></pre>
| 4 | 2016-07-27T03:03:29Z | [
"python"
] |
Print without unneeded Spaces | 38,602,982 | <p>I have just started out with Python, and am using Idle.</p>
<p>I put in:</p>
<pre><code>print("Professor Redwood: Right! So your name is",name,"!")
</code></pre>
<p>And got this in the console:</p>
<pre><code>Professor Redwood: Right! So your name is Chase !
</code></pre>
<p>Notice the spaces around the name <code>"Chase"</code>. I can't figure out how to get rid of these spaces. I looked up this question, and went to <a href="http://stackoverflow.com/questions/24692694/unwanted-blank-space-after-variable">this page</a>. I could not understand what the answer meant, so I need some help with it.</p>
<p>(Please note that I have already set the variable.)</p>
| 0 | 2016-07-27T03:00:20Z | 38,603,036 | <p>Another option using string concatenation:</p>
<pre><code>print("Professor Redwood: Right! So your name is"+ name + "!")
</code></pre>
<p>You could also do the following using string formatting</p>
<pre><code>print("Professor Redwood: Right! So your name is {0} !".format(name))
</code></pre>
| 3 | 2016-07-27T03:07:16Z | [
"python"
] |
Print without unneeded Spaces | 38,602,982 | <p>I have just started out with Python, and am using Idle.</p>
<p>I put in:</p>
<pre><code>print("Professor Redwood: Right! So your name is",name,"!")
</code></pre>
<p>And got this in the console:</p>
<pre><code>Professor Redwood: Right! So your name is Chase !
</code></pre>
<p>Notice the spaces around the name <code>"Chase"</code>. I can't figure out how to get rid of these spaces. I looked up this question, and went to <a href="http://stackoverflow.com/questions/24692694/unwanted-blank-space-after-variable">this page</a>. I could not understand what the answer meant, so I need some help with it.</p>
<p>(Please note that I have already set the variable.)</p>
| 0 | 2016-07-27T03:00:20Z | 38,603,080 | <p>What you're trying to do is concatenate strings which isn't exactly what commas in the <code>print</code> statement do. Instead, concatenation can be achieved several ways, the most common of which is to use the <code>+</code> operator.</p>
<pre><code>print("Professor Redwood: Right! So your name is " + name + "!")
</code></pre>
<p>or you can concatenate into a variable and print that. This is especially useful if you're concatenating lots of different strings or you want to reuse the string several times.</p>
<pre><code>sentence = "Professor Redwood: Right! So your name is " + name + "!"
print sentence
</code></pre>
<p>or you can use string formatting. This has the benefit of usually looking cleaner and allowing special variable types such as decimals or currency to be formatted correctly.</p>
<pre><code>print "Professor Redwood: Right! So your name is %s!" % name
print "Professor %s: Right! So your name is %s!" % (prof_name, name)
print "Professor Redwood: Right! So your name is {0}!".format(name)
</code></pre>
<p>Note that in Python 2, the print statement does not require brackets around the string. In Python 3 they are required.</p>
| 1 | 2016-07-27T03:12:38Z | [
"python"
] |
Verify all character sequences exist in a string (Python 2+) | 38,603,046 | <p>So to verify a string is a subset of another, with python, you can either use the <code>set/frozensets</code> class and the <code>issubset</code> method - only works for single characters, or you can use a regular expression, which would basically be multiple lookahead assertions from the start of the line. I want to use the regex option.</p>
<p>Without doing it the way below (using iterating through the strings and manually making lookahead assertions which may make a huge string given the big data I will be working with, is there another way to construct this lookahead in a more concise/straight-forward manner? The other item is that I will not be working with single characters only. So the number of lookahead assertions required could get really large.</p>
<pre><code>import re
userInput = raw_input()
listOfChars = 'asdfgei'
myRegexString = ''
for i in listOfChars:
myRegexString = myRegexString+'(?=.*'+i+')'
myRegexCompiled = re.compile(myRegexString)
if myRegexCompiled.(userInput):
print True
</code></pre>
| 1 | 2016-07-27T03:08:39Z | 38,603,152 | <p>So let's say you have two strings -- <code>userInput</code>, which might be very large, and <code>listOfChars</code>, which is relatively small. You want to check whether each element of <code>listOfChars</code> exists in <code>userInput</code>, without converting <code>userInput</code> into a <code>set</code>.</p>
<p>There's no need to use regexes for this -- it'll be faster to just do it this way:</p>
<pre><code>userInput = raw_input()
listOfChars = 'asdfgei'
def containsSubset(large, small):
for element in set(small): # Convert to a set to remove dupes
if not large.contains(element):
return False
return True
return containsSubset(userInput, listOfChars)
</code></pre>
<p>This will be O(M * N), where M is the size of <code>userInput</code> and N is the size of <code>listOfChars</code>.</p>
| 0 | 2016-07-27T03:20:52Z | [
"python",
"regex"
] |
Verify all character sequences exist in a string (Python 2+) | 38,603,046 | <p>So to verify a string is a subset of another, with python, you can either use the <code>set/frozensets</code> class and the <code>issubset</code> method - only works for single characters, or you can use a regular expression, which would basically be multiple lookahead assertions from the start of the line. I want to use the regex option.</p>
<p>Without doing it the way below (using iterating through the strings and manually making lookahead assertions which may make a huge string given the big data I will be working with, is there another way to construct this lookahead in a more concise/straight-forward manner? The other item is that I will not be working with single characters only. So the number of lookahead assertions required could get really large.</p>
<pre><code>import re
userInput = raw_input()
listOfChars = 'asdfgei'
myRegexString = ''
for i in listOfChars:
myRegexString = myRegexString+'(?=.*'+i+')'
myRegexCompiled = re.compile(myRegexString)
if myRegexCompiled.(userInput):
print True
</code></pre>
| 1 | 2016-07-27T03:08:39Z | 38,603,156 | <p>If you want to verify that all character sequences in a collection are present in a given string, use <code>all()</code> with a generator expression:</p>
<pre><code>answer = all(word in string for word in bag)
</code></pre>
| 3 | 2016-07-27T03:21:25Z | [
"python",
"regex"
] |
Why my CreateAPIView does not show Product and store category field? | 38,603,154 | <p>I am designing an API for listing stores and create store. I could list store but while designing for creating store I am not getting product and store category field inspite of calling all Product and Store category serializer in Store Serializer.</p>
<p><strong>My shortened models look like</strong></p>
<pre><code>class Merchant(models.Model):
user = models.ForeignKey(User)
phone = models.PositiveIntegerField(null=True,blank=True)
class Store(models.Model):
merchant = models.ForeignKey(Merchant)
name_of_legal_entity = models.CharField(max_length=250)
class Product(models.Model):
store = models.ForeignKey(Store)
image = models.ForeignKey('ProductImage',blank=True,null=True)
name_of_product = models.CharField(max_length=120)
class ProductImage(models.Model):
image = models.ImageField(upload_to='products/images/')
class StoreCategory(models.Model):
product = models.ForeignKey(Product,null=True, on_delete=models.CASCADE,related_name="store_category")
store_category = models.CharField(choices=STORE_CATEGORIES, default='GROCERY', max_length=10)
</code></pre>
<p><strong>Serializer.py</strong></p>
<pre><code>class ProductImageSerializer(ModelSerializer):
class Meta:
model = ProductImage
fields = ( 'id','imageName', )
class ProductSerializers(ModelSerializer):
image = ProductImageSerializer(many=False,read_only=True)
class Meta:
model = Product
fields=('id','image','name_of_product','description','price','active',)
class StoreCategorySerializer(ModelSerializer):
product = ProductSerializers(read_only=True)
class Meta:
model = StoreCategory
class StoreSerializer(ModelSerializer):
# url = HyperlinkedIdentityField(view_name='stores_detail_api')
store_categories = StoreCategorySerializer(many=True)
merchant = MerchantSerializer(read_only=True)
class Meta:
model = Store
fields=("id",
"merchant",
"store_categories",
"name_of_legal_entity",
"pan_number",
"registered_office_address",
"name_of_store",
)
</code></pre>
<p><strong>Views.py</strong></p>
<pre><code>class StoreCreateAPIView(CreateAPIView):
queryset = Store.objects.all()
serializer_class = StoreSerializer
parser_classes = (FormParser,MultiPartParser,)
def put(self, request, filename, format=None):
print('first put works')
file_obj = request.data['file']
print ('file_obj',file_obj)
return Response(status=204)
def perform_create(self, serializer):
print('then perform works')
serializer.save(user=self.request.user)
</code></pre>
<p>Here is the screenshot of how it looks</p>
<p><a href="http://i.stack.imgur.com/Smfzs.png" rel="nofollow"><img src="http://i.stack.imgur.com/Smfzs.png" alt="enter image description here"></a></p>
<p>Why it is not showing Merchant, Product and Store Category in the form?</p>
| 1 | 2016-07-27T03:21:03Z | 38,604,280 | <p>Remove <code>read_only=True</code> from the serializers that you wanna create entry of.
Like:</p>
<pre><code>product = ProductSerializers(read_only=True)
</code></pre>
<p>should be </p>
<pre><code>product = ProductSerializers()
</code></pre>
<p><code>read_only</code> will prevent it from written therefore i wont be in the outcome.</p>
| 2 | 2016-07-27T05:19:10Z | [
"python",
"django",
"api",
"python-3.x",
"django-rest-framework"
] |
Assign model method's return value to model attribute | 38,603,292 | <p>I have a class similar to this:</p>
<pre><code>class X(models.Model):
def hello(self):
return "Humpty Dumpty"
name = (hello,)
age = models.IntegerField()
</code></pre>
<p>now when I run in the console: <code>y.name</code> being <code>y</code> an instance, I get the following:</p>
<blockquote>
<p>(property object at 0x0000000004FDCBD8,)</p>
</blockquote>
<p>What am I doing wrong here?</p>
<p>I tried using the <code>@property</code> above the method but it didn't work.</p>
<p>I'd like to get "Humpty Dumpty" when I access <code>y.name</code>. So the method would assign it's value to the attribute.</p>
| -1 | 2016-07-27T03:36:40Z | 38,603,359 | <p>That's invalid syntax. You need to do something like this:</p>
<pre><code>class X:
def __init__(self):
self.name = self.hello()
def hello(self):
return "Humpty Dumpty"
test = X()
print(test.name) # prints "Humpty Dumpty"
</code></pre>
| 0 | 2016-07-27T03:45:09Z | [
"python",
"django"
] |
Assign model method's return value to model attribute | 38,603,292 | <p>I have a class similar to this:</p>
<pre><code>class X(models.Model):
def hello(self):
return "Humpty Dumpty"
name = (hello,)
age = models.IntegerField()
</code></pre>
<p>now when I run in the console: <code>y.name</code> being <code>y</code> an instance, I get the following:</p>
<blockquote>
<p>(property object at 0x0000000004FDCBD8,)</p>
</blockquote>
<p>What am I doing wrong here?</p>
<p>I tried using the <code>@property</code> above the method but it didn't work.</p>
<p>I'd like to get "Humpty Dumpty" when I access <code>y.name</code>. So the method would assign it's value to the attribute.</p>
| -1 | 2016-07-27T03:36:40Z | 38,603,371 | <p>If you just want to get the function called on attribute access, define name as property and provide your function <code>foo</code> to it:</p>
<pre><code>name = property(hello)
</code></pre>
<p>This will set the <code>fget</code> inside the property to your function <code>hello</code>. </p>
<pre><code>y = X()
y.name
'Humpty Dumpty'
</code></pre>
<p>Take note, there's a pretty good <a href="https://docs.python.org/3/howto/descriptor.html" rel="nofollow">tutorial on descriptors</a> in the Python Official docs.</p>
| 2 | 2016-07-27T03:46:13Z | [
"python",
"django"
] |
Applying iterative function to every group in pandas DataFrame | 38,603,344 | <p>I have large pandas DataFrame with following format: </p>
<pre><code> prod_id timestamp text
150523 0006641040 9.393408e+08 text_1
150500 0006641040 9.408096e+08 text_2
150499 0006641041 1.009325e+09 text_3
150508 0006641041 1.018397e+09 text_4
150524 0006641042 1.025482e+09 text_5
</code></pre>
<p>DataFrame is sorted by prod_id and timestamp. What I am trying to do, is to enumerate counter for every prod_id based on a timestamp from earliest to latest. For example, I am trying to achieve something like this: </p>
<pre><code> prod_id timestamp text enum
150523 0006641040 9.393408e+08 text_1 1
150500 0006641040 9.408096e+08 text_2 2
150499 0006641041 1.009325e+09 text_3 1
150508 0006641041 1.018397e+09 text_4 2
150524 0006641042 1.025482e+09 text_5 1
</code></pre>
<p>I can do this iteratively quite easily by going through each row and increasing counter, but is there a way to do this in a more functional programming fashion? </p>
<p>Thanks</p>
| 2 | 2016-07-27T03:42:52Z | 38,603,385 | <p><strong>UPDATE:</strong></p>
<pre><code>In [324]: df
Out[324]:
prod_id timestamp text
150523 6641040 9.393408e+08 text_1
150500 6641040 9.408096e+08 text_2
150501 6641040 9.408096e+08 text_3
150499 6641041 1.009325e+09 text_3
150508 6641041 1.018397e+09 text_4
150524 6641042 1.025482e+09 text_5
In [325]: df['enum'] = df.groupby(['prod_id'])['timestamp'].cumcount() + 1
In [326]: df
Out[326]:
prod_id timestamp text enum
150523 6641040 9.393408e+08 text_1 1
150500 6641040 9.408096e+08 text_2 2
150501 6641040 9.408096e+08 text_3 3
150499 6641041 1.009325e+09 text_3 1
150508 6641041 1.018397e+09 text_4 2
150524 6641042 1.025482e+09 text_5 1
</code></pre>
<p><strong>OLD answer:</strong></p>
<pre><code>In [314]: df['enum'] = df.groupby(['prod_id'])['timestamp'].rank().astype(int)
In [315]: df
Out[315]:
prod_id timestamp text enum
150523 6641040 9.393408e+08 text_1 1
150500 6641040 9.408096e+08 text_2 2
150499 6641041 1.009325e+09 text_3 1
150508 6641041 1.018397e+09 text_4 2
150524 6641042 1.025482e+09 text_5 1
</code></pre>
| 3 | 2016-07-27T03:46:57Z | [
"python",
"pandas",
"dataframe",
"functional-programming"
] |
historical stock price ten days before holidays for the past twenty years | 38,603,360 | <p>even though still as a noob, I have been enthusiastically learning Python for a while and here's a project I'm working on. I need to collect historical stock price ten days before US public holidays in the past twenty years and here's what I've done: (I used pandas_datareader and holidays here)</p>
<pre><code>start=datetime.datetime(1995,1,1)
end=datetime.datetime(2015,12,31)
history_price=web.get_data_yahoo('SPY', start, end)
us_holidays=holidays.UnitedStates()
test=[]
for i in dates:
if i in us_holidays:
test.append((history_price['Adj Close'].ix[pd.date_range(end=i, periods=11, freq='B')]))
test
</code></pre>
<p>And the result is like this: </p>
<pre><code>Freq: B, Name: Adj Close, dtype: float64, 1995-02-06 32.707565
1995-02-07 32.749946
1995-02-08 32.749946
1995-02-09 32.749946
1995-02-10 32.792328
1995-02-13 32.802975
1995-02-14 32.845356
1995-02-15 33.025457
1995-02-16 32.983076
1995-02-17 32.855933
1995-02-20 NaN
</code></pre>
<p>The length of the list "test" is 233. My question is: how can I convert this list into a dictionary with the holidays being the keys and the stock prices being values under each key. </p>
<p>Thank you in advance for your guidance. </p>
| 2 | 2016-07-27T03:45:11Z | 38,603,568 | <p>This uses a dictionary and list comprehension to generate a set of ten U.S. workdays preceding each holiday. The stock prices for those days are then stored in a dictionary (keyed on holiday) as a list of prices, most recent first (h-1) and oldes last (h-10).</p>
<pre><code>from pandas.tseries.holiday import USFederalHolidayCalendar
from pandas.tseries.offsets import CustomBusinessDay
holidays = USFederalHolidayCalendar().holidays(start='1995-1-1', end='2015-12-31')
bday_us = CustomBusinessDay(calendar=USFederalHolidayCalendar())
start = '1995-01-01'
end = '2015-12-31'
days = 10
dates = {holiday: [holiday - bday_us * n for n in range(1, days + 1)]
for holiday in USFederalHolidayCalendar().holidays(start=start, end=end)}
>>> dates
{...
Timestamp('2015-12-25 00:00:00'): [
Timestamp('2015-12-24 00:00:00'),
Timestamp('2015-12-23 00:00:00'),
Timestamp('2015-12-22 00:00:00'),
Timestamp('2015-12-21 00:00:00'),
Timestamp('2015-12-18 00:00:00'),
Timestamp('2015-12-17 00:00:00'),
Timestamp('2015-12-16 00:00:00'),
Timestamp('2015-12-15 00:00:00'),
Timestamp('2015-12-14 00:00:00'),
Timestamp('2015-12-11 00:00:00')]}
result = {holiday: history_price.ix[dates[holiday]].values for holiday in dates}
>>> result
{...
Timestamp('2015-12-25 00:00:00'):
array([ 203.56598 , 203.902497, 201.408393, 199.597201, 197.964166,
201.55487 , 204.673725, 201.722125, 199.626485, 198.622952])}
</code></pre>
| 0 | 2016-07-27T04:09:38Z | [
"python",
"dictionary",
"yahoo-finance"
] |
Getting error in taking command line arguments in python | 38,603,427 | <p>I am using windows with python2.7. My program is quite simple. Taking an input via command line and checking if it is '5'. </p>
<p>Code:</p>
<pre><code>import unittest
import sys
a=sys.argv[1]
print a
class TestCase(unittest.TestCase):
"""My tests"""
def test_is_number_is_five(self):
self.assertEqual('5',a)
if __name__ == '__main__':
unittest.main()
</code></pre>
<p>And running it using:</p>
<pre><code>>>python test.py 5
</code></pre>
<p>I am getting this error:</p>
<pre><code>Traceback (most recent call last):
File "C:\Python27\lib\unittest\main.py", line 94, in __init__
self.parseArgs(argv)
File "C:\Python27\lib\unittest\main.py", line 149, in parseArgs
self.createTests()
File "C:\Python27\lib\unittest\main.py", line 158, in createTests
self.module)
File "C:\Python27\lib\unittest\loader.py", line 130, in loadTestsFromNames
suites = [self.loadTestsFromName(name, module) for name in names]
File "C:\Python27\lib\unittest\loader.py", line 100, in loadTestsFromName
parent, obj = obj, getattr(obj, part)
AttributeError: 'module' object has no attribute '5'
</code></pre>
| 1 | 2016-07-27T03:53:50Z | 38,603,516 | <p><a href="https://docs.python.org/2/library/unittest.html#unittest.main" rel="nofollow"><code>unittest.main()</code></a> will obtain a list of tests to run from the command line. Hence it is trying to find a test named <code>5</code> in your module, but it fails because there is no such test.</p>
<p>To work around the problem you can pass your own <code>argv</code> values to <code>unittest.main()</code>:</p>
<pre><code>if __name__ == '__main__':
unittest.main(argv=sys.argv[:1])
</code></pre>
<p>This passes only the first argument, which is the script file name. It does, however, break some the functionality of <code>unittest.main()</code> should you want to pass test names on the command line.</p>
| 3 | 2016-07-27T04:03:01Z | [
"python"
] |
There is some advantage in accessing a text file in binary mode? | 38,603,477 | <p>We have a text file with several lines. The lines could end in CR+LF or LF. Each line have several fields separated by a field_separator (one or more characters). </p>
<p><strong>Sample 1:</strong></p>
<pre><code>field_separator = '\n'
with open('data.txt','r') as f:
for line in f:
line = line.split(field_separator)
for element in line:
print(element)
</code></pre>
<p><strong>Sample 2:</strong></p>
<pre><code>field_separator = b'\n'
with open('data.txt','br') as f:
for line in f:
if line.endswith(b'\n'):
line = line[0:-1]
line = line.split(field_separator)
for element in line:
print(element)
</code></pre>
<p><strong>Question:</strong> There is some adventage in access the text file in binary mode (sample 2 vs sample 1)?</p>
| 1 | 2016-07-27T03:58:13Z | 38,603,894 | <p>If you need to preserve the line ending style, you <em>must</em> use binary mode. Text mode will always translate line endings to be consistent.</p>
<p>If you're using Python 3 and you don't know the character encoding mode of the file, you can use binary mode to read the file without triggering decode errors. Decoding the bytes into Unicode strings becomes your responsibility.</p>
| 4 | 2016-07-27T04:44:21Z | [
"python",
"file-io"
] |
PyInstaller/Py2exe - include os.system call with third party scripts in single file compilation | 38,603,480 | <p>I'm using tkinter and pyinstaller/py2exe (either one would be fine), to create an executable as a single file from my python script. I can create the executable, and it runs as desired when not using the bundle option with py2exe or -F option with pyinstaller. I'm running third party python scripts within my code with os.system(), and can simply place these scripts in the 'dist' dir after it is created in order for it to work. The command has several parameters: input file, output file, number of threads..etc, so I'm unsure how to add this into my code using import. Unfortunately, this is on Windows, so some colleagues can use the GUI, and would like to have the single executable to distribute. </p>
<p>**EDIT:**I can get it to bundle into a single executable, and provide the scripts along with the exe. The issue still however, is with <code>os.system("python script.py -1 inputfile -n numbthreads -o outputfile..")</code> when running the third party scripts within my code. I had a colleague test the executable with the scripts provided with it, however at this point they need to have python installed, which is unacceptable since there will be multiple users.</p>
| 2 | 2016-07-27T03:59:09Z | 38,665,906 | <p>After a couple of days of some tests, I was able to figure out how to work around this problem. Instead of <code>os.system</code>, I am using <code>subprocess.call("script.py arg1 arg2 ..., shell=True)</code> for each script I need to run. Also, I used <code>chmod +x</code> (in linux) before transferring the scripts to windows to ensure they're an executable (someone can hopefully tell me if this was really necessary). Then without having to install python a colleague was able to run the program, after I compiled it as a single file with pyInstaller. I was also able to do the same thing with blast executables (where the user did not have to install blast locally - if the exe also accompanied the distribution of the script). This avoided having to call bipython ncbiblastncommandline and the install. </p>
| 0 | 2016-07-29T19:04:19Z | [
"python",
"import",
"py2exe",
"pyinstaller",
"os.system"
] |
How to remove lines in a text file containing three columns based on a number in the third column? | 38,603,497 | <p>I am new to coding this kind of problem, I am open to the simplest tool or solution. None of the tools I know how to use seem to be able to open the file. I would prefer to avoid excel as I would like to eventually batch the process. I have tried for some time and been unable to do this simple task automatically. I am sure there is a simple solution. </p>
<p>I simply want to find the instances where <code>column 3</code> below the <code>__</code> contains something other than 3, where it contains something other than 3 remove the line.</p>
<p>Here is an example of my data contained in a text file with an extension that is not <code>.txt</code>:</p>
<pre><code> 0.0004882812500000 136
0.000000 5850 __
4.674316 1307778 3
9.699219 2707354 3
14.932617 4165002 3
20.051270 5590690 3
24.809082 6915874 3
24.815430 6917642 2
29.786621 8302258 3
35.123535 9788738 3
35.123535 9788738 3
40.535645 11296162 1
</code></pre>
<p>I need to remove the lines that do not contain a 3 in the third column. I am new to programming so I am open to suggestions of simplest tool. I attempted Python, but my knowledge is too limited.<br>
I also tried Notepad++ with a search and replace, and I have added the <code>Python</code> add-on, but I don't know where to start.</p>
<p>Apologies if I have posted this wrong.</p>
| 0 | 2016-07-27T04:01:19Z | 38,603,660 | <p><strong>It is not clear whether you need a scripted answer to rerun the process or can use a manual process to do the manipulation</strong> (re-read your post and see that you would like to eventually script this out...regex should still give you a starting point even if you move past notepad++), but here is a quick and dirty scenario using Notepad++ assuming that your sample data is representative (2-digit numbers in the 3rd column will take another element in regex):</p>
<ol>
<li>In notepad++ with your data showing, do 'Mark' (ctrl-H, then tab for 'Mark')</li>
<li>Select Search Mode 'Regular Expression' and check 'bookmark line'</li>
<li>Use the following regex: ^\s{0,1}(\S+\s+){2}[012456789]$</li>
<li>Click 'Mark All'</li>
<li>Menu 'Search' / Bookmark / Cut Bookmarked Lines</li>
</ol>
<p>Regex meaning:</p>
<ul>
<li>From start of line (the caret)</li>
<li>Match zero or one space characters</li>
<li>Then (2) instances of one or more non-space characters followed by one or more space characters</li>
<li>Then any digit which is not a '3'</li>
<li>and anchored to the end of the line (with the $), which may be overkill :)</li>
</ul>
<p>Hope this helps.</p>
| 0 | 2016-07-27T04:21:17Z | [
"python",
"text",
"notepad++",
"batch-processing"
] |
How to remove lines in a text file containing three columns based on a number in the third column? | 38,603,497 | <p>I am new to coding this kind of problem, I am open to the simplest tool or solution. None of the tools I know how to use seem to be able to open the file. I would prefer to avoid excel as I would like to eventually batch the process. I have tried for some time and been unable to do this simple task automatically. I am sure there is a simple solution. </p>
<p>I simply want to find the instances where <code>column 3</code> below the <code>__</code> contains something other than 3, where it contains something other than 3 remove the line.</p>
<p>Here is an example of my data contained in a text file with an extension that is not <code>.txt</code>:</p>
<pre><code> 0.0004882812500000 136
0.000000 5850 __
4.674316 1307778 3
9.699219 2707354 3
14.932617 4165002 3
20.051270 5590690 3
24.809082 6915874 3
24.815430 6917642 2
29.786621 8302258 3
35.123535 9788738 3
35.123535 9788738 3
40.535645 11296162 1
</code></pre>
<p>I need to remove the lines that do not contain a 3 in the third column. I am new to programming so I am open to suggestions of simplest tool. I attempted Python, but my knowledge is too limited.<br>
I also tried Notepad++ with a search and replace, and I have added the <code>Python</code> add-on, but I don't know where to start.</p>
<p>Apologies if I have posted this wrong.</p>
| 0 | 2016-07-27T04:01:19Z | 38,617,493 | <p>If you're looking to do this in python here is a starting point:</p>
<pre><code>linesWith3 = [] # Store lines with 3 in last column
with open("file.txt", "r") as f: # Open file
for line in f.readlines():
cols = line.split() # Split into array of columns
if "3" in cols[2]:
linesWith3.append(line) # Store line
with open("file2.txt", "w") as f: # Write array to file
for line in linesWith3:
f.write(line+'\n')
</code></pre>
| 0 | 2016-07-27T15:35:32Z | [
"python",
"text",
"notepad++",
"batch-processing"
] |
Python -- how do I give a string value after I read the file | 38,603,522 | <p>I'm new to this community and this computer language. Recently I'm working on some practice and a question has bugged me for several days. Here is the question:
Read file test.txt(index: "CDEF","ABC","FIJK") in python, and re-align it into "ABC","CDEF","FIJK" , and given each character a value based on alphabet order(eg, "ABC" = 1+2+3=6), at last print the value of the index
(eg, A+B+C=6,"ABC"at first place represents 1, so the value of"ABC"is 6, the value of "CDEF" is 18*2=36(2 represents second place of the list) "FIJK" is 36*3=108)print out 150(6+36+108) </p>
<p>I don't have code right now. I'm thinking of if I do it with dictionary key. But is there any brilliant way to do it or if the file today isn't the index above. Should I do it in loop? </p>
| 2 | 2016-07-27T04:03:42Z | 38,603,637 | <p>You could use a nested comprehension:</p>
<pre><code>>>> lst = ["ABC", "CDEF", "FIJK"]
>>> sum((idx + 1) * sum(ord(letter) - 64 for letter in item) for idx, item in enumerate(lst))
150
</code></pre>
<p>If you want to use a regular for loop with an accumulator:</p>
<pre><code>total_sum = 0
for idx, item in enumerate(lst):
total_sum += (idx + 1) * sum(ord(letter) - 64 for letter in item)
print(total_sum)
</code></pre>
<p><code>ord("A")</code> gives you the ascii value of a character. For <code>"A"</code> it is <code>65</code>. This is why I'm subtracting <code>64</code> in the example. So <code>(ord(letter) - 64 for letter in item)</code> generates a number for each character in the string <code>"ABC"</code>, for example, and then sum adds them up. This value is then accumulated into <code>total_sum</code>, which will contain <code>6</code> after the first iteration of the <code>for</code> loop.</p>
| 0 | 2016-07-27T04:18:54Z | [
"python",
"linux",
"python-2.7",
"ipython"
] |
Python -- how do I give a string value after I read the file | 38,603,522 | <p>I'm new to this community and this computer language. Recently I'm working on some practice and a question has bugged me for several days. Here is the question:
Read file test.txt(index: "CDEF","ABC","FIJK") in python, and re-align it into "ABC","CDEF","FIJK" , and given each character a value based on alphabet order(eg, "ABC" = 1+2+3=6), at last print the value of the index
(eg, A+B+C=6,"ABC"at first place represents 1, so the value of"ABC"is 6, the value of "CDEF" is 18*2=36(2 represents second place of the list) "FIJK" is 36*3=108)print out 150(6+36+108) </p>
<p>I don't have code right now. I'm thinking of if I do it with dictionary key. But is there any brilliant way to do it or if the file today isn't the index above. Should I do it in loop? </p>
| 2 | 2016-07-27T04:03:42Z | 38,607,152 | <p>First, let's assume that you have a file called <code>sample.txt</code> containing the following:</p>
<pre><code>CDEF
ABC
FIJK
</code></pre>
<p><strong>SCRIPT</strong></p>
<p>Here is the script to accomplish what (I think) you are after:</p>
<pre><code>with open('so.txt', 'r') as file:
lines = [x.replace('\n', '') for x in file.readlines()]
print "lines: ", lines
lines.sort()
print "lines sorted: ", lines
sums = [sum([ord(letter.lower()) - 96 for letter in line]) for line in lines]
print "sums: ", sums
products = [x * (sums.index(x) + 1) for x in sums]
print "products: ", products
total = sum(products)
print "total: ", total
</code></pre>
<p><strong>OUTPUT</strong></p>
<p>The output of the above code:</p>
<pre><code>lines: ['CDEF', 'ABC', 'FIJK']
lines sorted: ['ABC', 'CDEF', 'FIJK']
sums: [6, 18, 36]
products: [6, 36, 108]
total: 150
</code></pre>
<p><strong>EXPLANATION</strong></p>
<p>(1) Open <code>so.txt</code> as a read-only file, and store it as a variable: <code>file</code>.</p>
<pre><code>with open('so.txt', 'r') as file:
</code></pre>
<p>(2) Take each line in <code>file</code> and remove any linebreaks and turn it into a list.</p>
<pre><code> lines = [x.replace('\n', '') for x in file.readlines()]
</code></pre>
<p>(3) Sort the list.</p>
<pre><code> lines.sort()
</code></pre>
<p>(4) This one is a little tricky as it is doing a few things.</p>
<pre><code> sums = [sum([ord(letter.lower()) - 96 for letter in line]) for line in lines]
</code></pre>
<p>So, let's break it up into two components:</p>
<pre><code> sums = [<do_something_here with line> for line in lines]
</code></pre>
<p>That code is called a <a href="https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions" rel="nofollow">list comprehension</a>. It is creating a new list with each element of the <code>lines</code> list, and doing something. It is roughly equivalent to:</p>
<pre><code> sums = []
for line in lines:
sums.append(<do_something_here with line>)
</code></pre>
<p>So, having the <code>line</code> variable (which would be a string), we can treat that also as a list and iterate over it in another list comprehension:</p>
<pre><code> [ord(letter.lower()) - 96 for letter in line]
</code></pre>
<p>For each <code>letter</code> in the <code>line</code> string, it converts it to lower case, makes it an ASCII ordinal, and subtracts <code>96</code> to get it to start with <code>a == 1</code>. You can see a list of <a href="http://www.ascii-code.com/" rel="nofollow">all ASCII numbers here</a>.</p>
<p>Finally, having a list that is now character strings converted into numbers, we apply <code>sum()</code> to that list.</p>
<p>We now have:</p>
<pre><code>[6, 18, 36]
</code></pre>
<p>(5) We take that list of the <code>sums</code> and provide <em>another</em> list comprehension. This time, the goal is to take each number, and multiply it by its <code>index</code>. You can get the index of an element by calling <code>list.index(element)</code>. As follows:</p>
<pre><code> products = [x * (sums.index(x) + 1) for x in sums]
</code></pre>
<p>(6) Finally, all we have to do is sum that last list we made using the <code>sum()</code> method again.</p>
<pre><code> total = sum(products)
</code></pre>
<p>I hope I answered the question you were after.</p>
| 1 | 2016-07-27T08:00:48Z | [
"python",
"linux",
"python-2.7",
"ipython"
] |
Using regex with fileinput gives error in Python | 38,603,532 | <p>Here is my code that I am using to replace some text in a file:</p>
<pre><code>for line in fileinput.input(the_file,inplace=True):
sys.stdout.write(line.re.sub('Begin.*?end', new_data))
</code></pre>
<p>This gives me the following error:</p>
<blockquote>
<p>AttributeError: 'str' object has no attribute 're'</p>
</blockquote>
<p>I thought that maybe I can use the <code>re.sub</code>part directly like this:</p>
<pre><code>sys.stdout.write(re.sub('Begin.*?end', new_data))
</code></pre>
<p>but that gave me the error:</p>
<blockquote>
<p>TypeError: sub() missing 1 required positional argument: 'string'</p>
</blockquote>
<p>How can I use regex with <code>fileinput</code> in Python to properly search and replace text?</p>
| 1 | 2016-07-27T04:04:35Z | 38,603,564 | <p>Just do</p>
<pre><code>sys.stdout.write(re.sub('Begin.*?end', new_data, line))
</code></pre>
<p>The signature for <a href="https://docs.python.org/3.5/library/re.html#re.sub" rel="nofollow"><code>re.sub</code></a> is <code>re.sub(pattern, repl, string, count=0, flags=0)</code></p>
| 1 | 2016-07-27T04:08:58Z | [
"python",
"regex",
"python-3.x",
"python-3.5"
] |
Regex failing to search a string | 38,603,611 | <p>I am trying to do a regex search for <code>Location:</code> and get its location as follows,can anyone help to figure out why it doesn't print the location,expected output is shown below?</p>
<pre><code>output = """
Build: BOOT.FAN.1.2-00179-M1234LAB-1
Location: \\location\builds678\INTEGRATION\BOOT.FAN.1.2-00179-M1234LAB-1
Comments: Build completed, labeled, and marked for retention.
Status: Approved [Approved for Testing]
BuildDate: 07/14/2016 17:54:54
"""
match=re.search(r'Location:\s*(\w*)',output)
print match.group(1)
</code></pre>
<p>EXPECTED OUTPUT:-</p>
<pre><code>\\location\builds678\INTEGRATION\BOOT.FAN.1.2-00179-M1234LAB-1
</code></pre>
| 0 | 2016-07-27T04:15:11Z | 38,603,754 | <p>Your string appears to contain special characters such as backspace (<code>\b</code>). You probably need to escape the backslashes, or use a raw string:</p>
<pre><code>output = r"""
Build: BOOT.FAN.1.2-00179-M1234LAB-1
Location: \\location\builds678\INTEGRATION\BOOT.FAN.1.2-00179-M1234LAB-1
Comments: Build completed, labeled, and marked for retention.
Status: Approved [Approved for Testing]
BuildDate: 07/14/2016 17:54:54
"""
</code></pre>
<p>Also there are a few other characters in the target string that will not be matched by just <code>\w</code>: <code>\</code>, <code>.</code> and <code>-</code> as per your example, possibly more. Try this pattern:</p>
<pre><code>match = re.search(r'Location:\s+([\w\\\.-]+)',output)
print match.group(1)
</code></pre>
<p>Also you could simply match all characters to the end of the line:</p>
<pre><code>match = re.search(r'Location:\s+(.+)',output)
print match.group(1)
</code></pre>
| 1 | 2016-07-27T04:30:36Z | [
"python"
] |
Cannot run robotframework-hub | 38,603,653 | <p>I followed the installation instructions here <a href="https://github.com/boakley/robotframework-hub" rel="nofollow">robotframework-hub</a> and after running this command <code>python -m rfhub</code>
I get the following error <code>/Library/Frameworks/Python.framework/Versions/2.7/Resources/Python.app/Contents/MacOS/Python: No module named libdocpkg; 'rfhub' is a package and cannot be directly executed</code>. I tried looking for 'libdocpkg' to install with pip but no luck. Has anyone installed this successfully?</p>
| 0 | 2016-07-27T04:20:27Z | 38,617,948 | <p>The issue was that I had a folder called 'robot' where I placed all my robot scripts. Once I renamed that folder the hub worked like a charm. Thank you @Bryan Oakley for the clues provided.</p>
| 1 | 2016-07-27T15:57:52Z | [
"python",
"robotframework"
] |
Django: trying to understand how the queryset attribute works in class-based generic views | 38,603,768 | <p>When using class-based generic views in Django, having a <code>queryset</code> attribute means to "restrict" the collection of object the view will operate on, right? </p>
<blockquote>
<p>If queryset is provided, that queryset will be used as the source of objects. (<a href="https://docs.djangoproject.com/en/1.9/ref/class-based-views/mixins-single-object/#django.views.generic.detail.SingleObjectMixin.get_object" rel="nofollow">Django's get_object()</a>)</p>
</blockquote>
<p>Model:</p>
<pre><code>from django.db import models
class Person(models.Model):
full_name = models.CharField(max_length=30)
is_active = False
</code></pre>
<p>View: </p>
<pre><code>from django.views.generic import DetailView
from books.models import Person
class PersonDetail(DetailView):
queryset = Person.objects.filter(is_active=True)
</code></pre>
<p>The <code>queryset</code> above makes sure to only consider objects with <code>is_active=true</code>.</p>
<p>But how does this works internally? </p>
<p>For example: Does Django appends a SQL condition <code>AND is_active=TRUE</code> to every query in the view? </p>
<p>Ok that last example seems pretty stupid but I hope you get the idea of my question. Thank you. </p>
| 0 | 2016-07-27T04:31:51Z | 38,626,819 | <p>Yes, this is exactly what happens. Your queryset is used as the base queryset by the view's <code>get_object</code> method. It then applies an <a href="https://github.com/django/django/blob/master/django/views/generic/detail.py#L38" rel="nofollow">additional filter</a> to get a specific object (e.g., by ID):</p>
<pre><code>queryset = queryset.filter(pk=pk)
</code></pre>
<p>Of course, the view needs a single object, not a queryset, so it then does:</p>
<pre><code>obj = queryset.get()
</code></pre>
<p>Which will either return a single object, or a <code>DoesNotExist</code> or <code>MultipleObjectsReturned</code> exception. <code>DoesNotExist</code> results in a 404. <code>MultipleObjectsReturned</code> is unhandled and will propagate to your code.</p>
| 2 | 2016-07-28T03:53:44Z | [
"python",
"django",
"generics"
] |
Trying to find the 1000th prime number | 38,603,777 | <p>I am trying to write a script in python to find the 1000th prime number. I don't understand why this isn't working here. Basically while the mod is less than the square root of the number and still has a remainder, the mod goes up by one. This should continue until the mod equals the square root of the number. Then the check should remain at 0 and the number should be prime. Every time I try to run the script it tells me theres a system error.</p>
<pre><code>import math
b=2
count=2
next_odd=3
next_prime=1
check = 0
while count<=10:
while b<float(math.sqrt(next_odd)):
if next_odd%b>0:
b+=1
if next_odd%b == 0:
check+=1
if check > 0:
next_prime=next_odd
next_odd+=2
print(next_prime)
b=2
count+=1`
</code></pre>
| 1 | 2016-07-27T04:32:58Z | 38,604,053 | <p>I understand what you are trying to do, but unfortunately there were too many things wrong with your program. Here is a working version. I made minimal changes. Hopefully you can compare the below version with your own and see where you went wrong.</p>
<pre><code>import math
count=2
next_odd=3
next_prime=1
while count<=1000:
b=1
check = 0
while b<float(math.sqrt(next_odd)):
b+=1
if next_odd%b == 0:
check+=1
if check == 0:
next_prime=next_odd
print(next_prime)
count+=1
next_odd+=2
</code></pre>
<p>With the above program, 1000th prime can be successfully determined to be 7919.</p>
| 2 | 2016-07-27T04:58:49Z | [
"python",
"primes"
] |
Trying to find the 1000th prime number | 38,603,777 | <p>I am trying to write a script in python to find the 1000th prime number. I don't understand why this isn't working here. Basically while the mod is less than the square root of the number and still has a remainder, the mod goes up by one. This should continue until the mod equals the square root of the number. Then the check should remain at 0 and the number should be prime. Every time I try to run the script it tells me theres a system error.</p>
<pre><code>import math
b=2
count=2
next_odd=3
next_prime=1
check = 0
while count<=10:
while b<float(math.sqrt(next_odd)):
if next_odd%b>0:
b+=1
if next_odd%b == 0:
check+=1
if check > 0:
next_prime=next_odd
next_odd+=2
print(next_prime)
b=2
count+=1`
</code></pre>
| 1 | 2016-07-27T04:32:58Z | 38,604,072 | <p>(first, I assume the tick on the end of your code is a typo in your stack overflow post, not the code itself)</p>
<p>Consider what happens when <code>next_odd</code> is prime. This block:</p>
<pre><code>while b<float(math.sqrt(next_odd)):
if next_odd%b>0:
b+=1
if next_odd%b == 0:
check+=1
</code></pre>
<p>will increment <code>b</code> up until the square root of <code>next_odd</code> without ever incrementing <code>check</code>. That means that <code>if check > 0:</code> won't pass, and thus <code>count</code> never increments, and you then you just spin around in the <code>
while count<=10:</code>, skipping both <code>if</code> blocks because their conditions are false. </p>
<p>In other words, you don't actually say what to do when <code>next_odd</code> is prime. This is also an example of why <code>while</code> shouldn't really be used when all you want to do is increment through numbers (which is what you're using it for here). Try something like this:</p>
<pre><code>max_num = 10000 # or whatever
for odd in range(3, max_num, 2):
factor_count = 0
for factor in range(2, math.floor(math.sqrt(max_num)) + 1):
if odd % factor == 0:
factor_count += 1
if factor_count == 0:
print(odd)
</code></pre>
<p>A couple points about this code:</p>
<ul>
<li>There's no (non-constant) variables in the global scope. That makes it much easier to reason about how the script's state changes over time.</li>
<li>The use of for-loops over while-loops guarantees that our script won't get caught in an infinite loop due to an erroneous (or unaccounted for) condition.</li>
<li>The use of for-loops means that we don't have to worry about incrementing all of the variables ourselves, which dramatically reduces the amount of state that we have to manage.</li>
</ul>
<p>Hope that helps!</p>
<p>Oh, note that there are much more efficient ways to compute primes also. See <a href="https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes" rel="nofollow">https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes</a></p>
| 2 | 2016-07-27T05:01:00Z | [
"python",
"primes"
] |
KeyError exception type Django template tag | 38,603,924 | <p>I am trying to implement a template tag into my django project, and I a Key Error. I believe the has to do with getting context in the template tag under load_menu.py.</p>
<pre><code>Exception Type: KeyError
Exception Value:'request'
Error during template rendering
In template C:\Users\Eric Franzen\PycharmProjects\MySite\templates\app\TikSys\tiksys_home.html, error at line 0
request
1 {% extends 'app/TikSys/tiksysbase.html' %}
2 {% block content %}
3 <div class="body-container">
4 {% include "app/TikSys/sidenavbar.html" %}
5 <div class="col-md-10 ">
6 <div class="jumbotron">
7 <h1>Welcome to TikSys!</h1>
8 <p>Please Sign In</p>
9 </div>
10 </div>
</code></pre>
<p>Traceback</p>
<pre><code>...
File "C:\Users\Eric Franzen\PycharmProjects\MySite\Site\views.py", line 43, in tiksys_home
return render(request, 'app/TikSys/tiksys_home.html', {})
...
File "C:\Users\Eric Franzen\PycharmProjects\MySite\Site\templatetags\load_menu.py", line 10, in menu
request = context['request']
</code></pre>
<p><strong>Site/templatetags/load_menu.py</strong></p>
<pre><code>from django import template
from Site.models import *
register = template.Library()
@register.inclusion_tag('app/TikSys/sidenavbar.html', takes_context=True)
def menu(context):
request = context['request']
um = UserMunicipal.objects.filter(userID=request.user).values('municipalID')
m = Municipal.objects.filter(id=um)
return {'menus': m}
</code></pre>
<p><strong>app/TikSys/sidenavbar.html</strong></p>
<pre><code><div class="col-md-2 NavBar">
{% load load_menu %}
{% menu %}
{% for item in menus %}
<ul class="nav nav-pills nav-stacked">
<li>{{ item.name }} </li>
</ul>
{% endfor %}
</div>
</code></pre>
<p><strong>views.py</strong></p>
<pre><code>from django.shortcuts import render
# Create your views here.
from django.http import HttpResponse
from django.template import Context, loader
from django.views.generic import TemplateView
from Site.forms import UserForm, UserProfileForm
from django.http import *
from django.shortcuts import render_to_response, redirect
from django.template import RequestContext
from django.contrib.auth.decorators import login_required
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth import get_user_model
from .models import Notification, UserMunicipal, Municipal
@login_required(login_url='/login/')
def tiksys_home(request):
return render(request, 'app/TikSys/tiksys_home.html', {})
</code></pre>
| 0 | 2016-07-27T04:47:09Z | 38,604,239 | <p>You are loading the tag, in the same template that is rendering the tag. This is why there is no context anymore.</p>
<p>The template that the tag renders <code>app/TikSys/sidenavbar.html</code>, should only have this:</p>
<pre><code><div class="col-md-2 NavBar">
{% for item in menus %}
<ul class="nav nav-pills nav-stacked">
<li>{{ item.name }} </li>
</ul>
{% endfor %}
</div>
</code></pre>
<p>In the main template (where you need the menu), you add - at the top <code>{% load load_menu %}</code>, and then where you want the menu, you add <code>{% menu %}</code>, like this:</p>
<pre><code>{% load load_menu %}
{% extends 'app/TikSys/tiksysbase.html' %}
{% block content %}
<div class="body-container">
{% menu %}
<div class="col-md-10 ">
<div class="jumbotron">
<h1>Welcome to TikSys!</h1>
<p>Please Sign In</p>
</div>
</div>
</code></pre>
| 1 | 2016-07-27T05:16:25Z | [
"python",
"django"
] |
Python ; IF word in line and word2 not in line | 38,603,955 | <p>Apologies for being a noob here , as i am a newbie in this </p>
<p>i have been trying to write a code which could find a certain words in line and then match from 2nd list of words to see if 2nd word exist in the same line.
only print line only if first word exist not both in a line; here is the snippet and example</p>
<pre><code>keywords =("a","b","c","d")
keywords2 = ("e","f","g")
a = ("a is a ", "a is not e","b is b", "b is not f")
for key2 in keywords2:
for key in keywords:
for line in a:
if key2 not in line:
if key in line:
print(key+" Found in --> ")
print (line)
</code></pre>
<p>the output required is </p>
<pre><code>a is a
b is b
</code></pre>
<p>while we have </p>
<pre><code>a Found in -->
a is a
b Found in -->
b is b
b Found in -->
b is not f
a Found in -->
a is a
a Found in -->
a is not e
b Found in -->
b is b
a Found in -->
a is a
a Found in -->
a is not e
b Found in -->
b is b
b Found in -->
b is not f
</code></pre>
<p>i have tried few ways to implement the loop but to no use </p>
| 1 | 2016-07-27T04:49:28Z | 38,604,104 | <p>Does this work for you?</p>
<pre><code>keywords =("a","b","c","d")
keywords2 = ("e","f","g")
lines = ("a is a ", "a is not e","b is b", "b is not f")
for keyword in keywords:
for line in lines:
if keyword in line:
keyword2_exist = False
for keyword2 in keywords2:
if keyword2 in line:
keyword2_exist = True
if not keyword2_exist:
print(line)
</code></pre>
| 0 | 2016-07-27T05:03:02Z | [
"python",
"if-statement"
] |
Python ; IF word in line and word2 not in line | 38,603,955 | <p>Apologies for being a noob here , as i am a newbie in this </p>
<p>i have been trying to write a code which could find a certain words in line and then match from 2nd list of words to see if 2nd word exist in the same line.
only print line only if first word exist not both in a line; here is the snippet and example</p>
<pre><code>keywords =("a","b","c","d")
keywords2 = ("e","f","g")
a = ("a is a ", "a is not e","b is b", "b is not f")
for key2 in keywords2:
for key in keywords:
for line in a:
if key2 not in line:
if key in line:
print(key+" Found in --> ")
print (line)
</code></pre>
<p>the output required is </p>
<pre><code>a is a
b is b
</code></pre>
<p>while we have </p>
<pre><code>a Found in -->
a is a
b Found in -->
b is b
b Found in -->
b is not f
a Found in -->
a is a
a Found in -->
a is not e
b Found in -->
b is b
a Found in -->
a is a
a Found in -->
a is not e
b Found in -->
b is b
b Found in -->
b is not f
</code></pre>
<p>i have tried few ways to implement the loop but to no use </p>
| 1 | 2016-07-27T04:49:28Z | 38,604,172 | <p>@joon answers with an answer in the style of your question; here's a couple of other ideas:</p>
<p>Loop over the <em>lines</em> first, because the code should work like the question "should I print this line?" for each line.</p>
<pre><code>keywords = ("a","b","c","d")
keywords2 = ("e","f","g")
a = ("a is a ", "a is not e", "b is b", "b is not f")
for line in a:
for k in keywords:
if k in line:
for k2 in keywords2:
if k2 in line:
break
else:
print(line)
</code></pre>
<p>Try online: <a href="https://repl.it/CgW8" rel="nofollow">https://repl.it/CgW8</a></p>
<p>For/else is a Python idea, but it's a bit weird - if the loop ends normally, <code>else:</code> will run and print the line. If the loop breaks, <code>else:</code> will not run and will not print the line.</p>
<p>But a more idiomatic answer would be to make use of <code>any()</code> which returns True if anything in a list is True, and False otherwise:</p>
<pre><code>keywords =("a","b","c","d")
keywords2 = ("e","f","g")
a = ("a is a ", "a is not e","b is b", "b is not f")
for line in a:
if any(k in line for k in keywords):
if not any(k2 in line for k2 in keywords2):
print(line)
</code></pre>
<p>Try online: <a href="https://repl.it/CgW9" rel="nofollow">https://repl.it/CgW9</a></p>
| 1 | 2016-07-27T05:09:42Z | [
"python",
"if-statement"
] |
Python ; IF word in line and word2 not in line | 38,603,955 | <p>Apologies for being a noob here , as i am a newbie in this </p>
<p>i have been trying to write a code which could find a certain words in line and then match from 2nd list of words to see if 2nd word exist in the same line.
only print line only if first word exist not both in a line; here is the snippet and example</p>
<pre><code>keywords =("a","b","c","d")
keywords2 = ("e","f","g")
a = ("a is a ", "a is not e","b is b", "b is not f")
for key2 in keywords2:
for key in keywords:
for line in a:
if key2 not in line:
if key in line:
print(key+" Found in --> ")
print (line)
</code></pre>
<p>the output required is </p>
<pre><code>a is a
b is b
</code></pre>
<p>while we have </p>
<pre><code>a Found in -->
a is a
b Found in -->
b is b
b Found in -->
b is not f
a Found in -->
a is a
a Found in -->
a is not e
b Found in -->
b is b
a Found in -->
a is a
a Found in -->
a is not e
b Found in -->
b is b
b Found in -->
b is not f
</code></pre>
<p>i have tried few ways to implement the loop but to no use </p>
| 1 | 2016-07-27T04:49:28Z | 38,604,194 | <p>If I understand correctly, you want only "lines" that have a value from <code>keywords</code>, but not <code>keywords2</code>. In that case simply do:</p>
<pre><code>for line in a:
if [x for x in keywords if x in line] and not [x for x in keywords2 if x in line]:
print line
</code></pre>
<p><code>[x for x in keywords if x in line]</code> loops through all items in <code>keywords</code> and adds them to the list if they are in <code>line</code>.</p>
<p><code>[x for x in keywords2 if x in line]</code> loops through all items in <code>keywords2</code> and adds them to the list if they are in <code>line</code>.</p>
<p>An empty list is considered False and you want the <code>keywords</code> list to not be empty and the <code>keywords2</code> list to be empty.</p>
| 2 | 2016-07-27T05:12:26Z | [
"python",
"if-statement"
] |
Python ; IF word in line and word2 not in line | 38,603,955 | <p>Apologies for being a noob here , as i am a newbie in this </p>
<p>i have been trying to write a code which could find a certain words in line and then match from 2nd list of words to see if 2nd word exist in the same line.
only print line only if first word exist not both in a line; here is the snippet and example</p>
<pre><code>keywords =("a","b","c","d")
keywords2 = ("e","f","g")
a = ("a is a ", "a is not e","b is b", "b is not f")
for key2 in keywords2:
for key in keywords:
for line in a:
if key2 not in line:
if key in line:
print(key+" Found in --> ")
print (line)
</code></pre>
<p>the output required is </p>
<pre><code>a is a
b is b
</code></pre>
<p>while we have </p>
<pre><code>a Found in -->
a is a
b Found in -->
b is b
b Found in -->
b is not f
a Found in -->
a is a
a Found in -->
a is not e
b Found in -->
b is b
a Found in -->
a is a
a Found in -->
a is not e
b Found in -->
b is b
b Found in -->
b is not f
</code></pre>
<p>i have tried few ways to implement the loop but to no use </p>
| 1 | 2016-07-27T04:49:28Z | 38,604,261 | <p>This could probably work better for you:</p>
<pre><code>import re
keywords =("a","b","c","d")
keywords2 = ("e","f","g")
pattern = re.compile(r'^(\w+)\s+is\s+(?:not\s+)?(\w+)')
for line in ("a is a", "a is not e","b is b", "b is not f"):
for key1, key2 in pattern.findall(line):
if key1 in keywords and key2 not in keywords2:
print (line)
</code></pre>
<p>From what I understand, there are two keywords in the strings; each in the form <code>key is [not] key2</code>, and you are looking to print only those lines where <code>key</code> is in <code>keywords</code> and <code>key2</code> is not in <code>keywords2</code>. That is essentially what the above solution does</p>
| 0 | 2016-07-27T05:17:48Z | [
"python",
"if-statement"
] |
Python ; IF word in line and word2 not in line | 38,603,955 | <p>Apologies for being a noob here , as i am a newbie in this </p>
<p>i have been trying to write a code which could find a certain words in line and then match from 2nd list of words to see if 2nd word exist in the same line.
only print line only if first word exist not both in a line; here is the snippet and example</p>
<pre><code>keywords =("a","b","c","d")
keywords2 = ("e","f","g")
a = ("a is a ", "a is not e","b is b", "b is not f")
for key2 in keywords2:
for key in keywords:
for line in a:
if key2 not in line:
if key in line:
print(key+" Found in --> ")
print (line)
</code></pre>
<p>the output required is </p>
<pre><code>a is a
b is b
</code></pre>
<p>while we have </p>
<pre><code>a Found in -->
a is a
b Found in -->
b is b
b Found in -->
b is not f
a Found in -->
a is a
a Found in -->
a is not e
b Found in -->
b is b
a Found in -->
a is a
a Found in -->
a is not e
b Found in -->
b is b
b Found in -->
b is not f
</code></pre>
<p>i have tried few ways to implement the loop but to no use </p>
| 1 | 2016-07-27T04:49:28Z | 38,604,428 | <p>You should learn some functional programming, Try this:</p>
<pre><code>keywords =("a","b","c","d")
keywords2 = ("e","f","g")
a = ("a is a ", "a is not e","b is b", "b is not f")
for line in a:
if not any(map(lambda x: x in line, keywords2)):
if any(map(lambda x: x in line, keywords)):
print line
</code></pre>
| 0 | 2016-07-27T05:30:22Z | [
"python",
"if-statement"
] |
Weird behavior with numpy arrays of arrays in typing | 38,604,045 | <p>Why is the first array being converted entirely to string type, while the individual types of the second array remain the same? How would I force the first array (<code>np.array([np.array([1,2,3]), np.array(["a", "bb", "ccc"])])</code>) to consist of a <code>dtype = np.int64</code> array and a <code>dtype = np.str_</code> array? I tried setting <code>dtype = object</code> for the entire array, but this caused the dtypes of the individual arrays to also change to object.</p>
<pre><code>>>> import numpy as np
>>> np.array([np.array([1,2,3]), np.array(["a", "bb", "ccc"])])
array([['1', '2', '3'],
['a', 'bb', 'ccc']],
dtype='<U21')
>>> np.array([np.array([1,2,3, 4]), np.array(["a", "bb", "ccc"])])
array([array([1, 2, 3, 4]), array(['a', 'bb', 'ccc'],
dtype='<U3')], dtype=object)
</code></pre>
| 2 | 2016-07-27T04:58:21Z | 38,604,226 | <p>The reason is that if the sub-arrays have compatible shapes, numpy creates an extra dimension for their shared shape. This is the case in your first example, and if you check the <code>shape</code> of that object you will see it is <code>(2, 3)</code>. In your second example the sub-array shapes cannot be reconciled so you get a 1D array of shape <code>(2,)</code>.</p>
<p>As far as I know there is no way to force <code>nd.array</code> to create the array as dtype object without propagating that change to the sub-arrays. It is a somewhat strange thing to want, since most of the benefits of numpy arrays will be limited or eliminated. You can do it by, for instance, pre-creating the array and populating it afterwards:</p>
<pre><code>x = np.zeros((2,), dtype=object)
x[0] = np.array([1,2,3])
x[1] = np.array(["a", "bb", "ccc"])
>>> x
array([array([1, 2, 3]), array([u'a', u'bb', u'ccc'],
dtype='<U3')], dtype=object)
>>> x[0].dtype
dtype('int32')
>>> x[1].dtype
dtype('<U3')
</code></pre>
| 1 | 2016-07-27T05:15:14Z | [
"python",
"numpy"
] |
Weird behavior with numpy arrays of arrays in typing | 38,604,045 | <p>Why is the first array being converted entirely to string type, while the individual types of the second array remain the same? How would I force the first array (<code>np.array([np.array([1,2,3]), np.array(["a", "bb", "ccc"])])</code>) to consist of a <code>dtype = np.int64</code> array and a <code>dtype = np.str_</code> array? I tried setting <code>dtype = object</code> for the entire array, but this caused the dtypes of the individual arrays to also change to object.</p>
<pre><code>>>> import numpy as np
>>> np.array([np.array([1,2,3]), np.array(["a", "bb", "ccc"])])
array([['1', '2', '3'],
['a', 'bb', 'ccc']],
dtype='<U21')
>>> np.array([np.array([1,2,3, 4]), np.array(["a", "bb", "ccc"])])
array([array([1, 2, 3, 4]), array(['a', 'bb', 'ccc'],
dtype='<U3')], dtype=object)
</code></pre>
| 2 | 2016-07-27T04:58:21Z | 38,604,232 | <p>Look at the outputs:</p>
<pre><code>>>> np.array([np.array([1,2,3]), np.array(["a", "bb", "ccc"])])
array([['1', '2', '3'],
['a', 'bb', 'ccc']],
dtype='<U11')
>>> np.array([np.array([1,2,3,4]), np.array(["a", "bb", "ccc"])])
array([array([1, 2, 3, 4]), array(['a', 'bb', 'ccc'],
dtype='<U3')], dtype=object)
</code></pre>
<p>The first output concatenates the arrays into a 2x1 array, each cell with three elements. The second output does not concatenate the arrays.</p>
<p>Now, watch this:</p>
<pre><code>>>> a = np.array([np.array([1,2,3])])
>>> b = np.array([np.array(['i','j','k'])])
>>> np.concatenate((a, b))
array([['1', '2', '3'],
['i', 'j', 'k']],
dtype='<U11')
>>> a = np.array([np.array([1,2,3,4])])
>>> np.concatenate((a, b))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: all the input array dimensions except for the concatenation axis must match exactly
>>> np.concatenate((a, b), axis=1)
array([['1', '2', '3', '4', 'i', 'j', 'k']],
dtype='<U11')
</code></pre>
<p>See the difference? When Numpy tries to concatenate arrays of ints and strings, if they each have the same dimension, NumPy will convert the ints to strings. If they don't have equal dimensions, it won't concatenate them because you get those errors.</p>
| 1 | 2016-07-27T05:15:55Z | [
"python",
"numpy"
] |
Weird behavior with numpy arrays of arrays in typing | 38,604,045 | <p>Why is the first array being converted entirely to string type, while the individual types of the second array remain the same? How would I force the first array (<code>np.array([np.array([1,2,3]), np.array(["a", "bb", "ccc"])])</code>) to consist of a <code>dtype = np.int64</code> array and a <code>dtype = np.str_</code> array? I tried setting <code>dtype = object</code> for the entire array, but this caused the dtypes of the individual arrays to also change to object.</p>
<pre><code>>>> import numpy as np
>>> np.array([np.array([1,2,3]), np.array(["a", "bb", "ccc"])])
array([['1', '2', '3'],
['a', 'bb', 'ccc']],
dtype='<U21')
>>> np.array([np.array([1,2,3, 4]), np.array(["a", "bb", "ccc"])])
array([array([1, 2, 3, 4]), array(['a', 'bb', 'ccc'],
dtype='<U3')], dtype=object)
</code></pre>
| 2 | 2016-07-27T04:58:21Z | 38,604,272 | <p><code>np.array</code> sometimes tries to be 'too smart'. But the basic principle is that it tries to create the highest dimensional array that can with the input. Only when it fails does it resort to making a simpler array of dtype=object. Remember, the original intent was to produce a multidimensional array of numbers. <code>object</code> dtype is a more recent, and poorly developed, generalization.</p>
<p>With</p>
<pre><code>np.array([np.array([1,2,3]), np.array(["a", "bb", "ccc"])])
</code></pre>
<p>the subarrays have the same length. So it creates the same sort of array as it would if give a list of lists, <code>np.array([[1,2,3],["a", "bb", "ccc"]])</code>. And since it can't force "a" to be an int, it forces <code>1</code> to be a string. I'm not sure why it gave you a <code>U21</code> and me <code>U11</code>. Seems that <code>U3</code> would have been sufficient.</p>
<p>Another way to think of this, is <code>concatenate</code> on a new axis. Recent versions added a <code>np.stack</code> that gives more control over that.</p>
<pre><code>np.stack([np.array([1,2,3]), np.array(["a", "bb", "ccc"])])
</code></pre>
<p>But in the 2nd case, the 2 arrays have different length. It can't form a 2d array from those, so it leaves them as is, and makes a 1d 2element object array.</p>
<p>There are a couple of tricks that can be used to make an object array with equal length elements. One is make an empty object array of the right size, and assign the elements</p>
<pre><code>In [81]: x=np.empty((2,), dtype=object)
In [82]: x[:] = [np.array([1,2,3]), np.array(["a", "bb", "ccc"])]
In [83]: x
Out[83]:
array([array([1, 2, 3]), array(['a', 'bb', 'ccc'],
dtype='<U3')], dtype=object)
</code></pre>
<p>Another is to start with elements of different size, and change or delete one.</p>
<pre><code>In [84]: x = np.array([[1,2,3,4], ["a", "bb", "ccc"]])
In [85]: x[0] = np.array([1,2,3])
</code></pre>
| 2 | 2016-07-27T05:18:49Z | [
"python",
"numpy"
] |
custom authentication not working in django-tastypie | 38,604,125 | <p>My question is, how do i write my own custom authentication correctly??</p>
<p>i have tried to follow this:
<a href="http://django-tastypie.readthedocs.org/en/latest/authentication.html#implementing-your-own-authentication-authorization" rel="nofollow">http://django-tastypie.readthedocs.org/en/latest/authentication.html#implementing-your-own-authentication-authorization</a></p>
<p>I have implemented basic method,</p>
<p><strong>api.py</strong></p>
<pre><code>def prepareResponce(responceData):
"""Prepares a Json responce with status 200"""
response = JsonResponse(responceData)
return response # {"foo": "bar"}
class CustomBasicAuthentication(BasicAuthentication):
userID = None
userType = None
userAccess = None
userName = None
def is_authenticated(self, request, **kwargs):
if 'admin' in request.user.username:
return prepareResponce({'logged in': 'Admin' })
#return True
return prepareResponce({'not allowed for':userName })
def get_identifier(self, request):
return request.user.username
class UserResource(ModelResource):
class Meta:
queryset = User.objects.all()
resource_name = 'user'
authentication = CustomBasicAuthentication()
allowed_methods = ['get', 'post']
</code></pre>
<p>when i call API providing admin's username and password it's always return the else part. <strong>where am i did wrong ?</strong></p>
| 0 | 2016-07-27T05:05:44Z | 38,605,062 | <p>You missed <code>return</code> and You don't call parent <code>is_authenticated</code> function:</p>
<pre><code>def is_authenticated(self, request, **kwargs):
super(CustomBasicAuthentication, self).is_authenticated(request, **kwargs)
if 'admin' == request.user.username:
return prepareResponce({'logged in': 'Admin' })
return prepareResponce({'not allowed for': self.userName })
</code></pre>
| 1 | 2016-07-27T06:14:30Z | [
"python",
"django",
"authentication",
"tastypie"
] |
How to startup my python script automatically in ubuntu | 38,604,386 | <p><strong><em>I need my own gnome applet python program to run automatically when system starts.</em></strong></p>
| -2 | 2016-07-27T05:27:17Z | 38,605,773 | <p>All you need to do is put a script in <code>/etc/init.d/</code> and it will run on startup.</p>
<p>Also, be sure to put the interpreter at the top of the file, such as <code>#! /bin/bash</code>, and be sure to make it executable with <code>chmod +x /etc/init.d/myscript</code></p>
<p><strong>Example file</strong></p>
<pre><code>#! /bin/bash
python /path/to/my/script.py
</code></pre>
| 0 | 2016-07-27T06:55:47Z | [
"python",
"linux"
] |
Is there any way to check from url if that file is already downloaded? | 38,604,499 | <blockquote>
<p>Suppose I have two urls which redirect to same file(hosted on 2 servers separately) and I've downloaded the file from one of the url. Is it possible to avoid downloading the same file again when I click the other url (checking in the system, if the file exists)?</p>
<p>The main aim is to optimize data usage and remove redundancy.</p>
</blockquote>
<p>I read about md5 checks for a file but can I calculate md5 checksum of a file on Internet without downloading it ?</p>
| 0 | 2016-07-27T05:35:44Z | 38,604,591 | <p>It's not possible to calculate a md5 hash without downloading the file, no.</p>
<p>What you can do though, is to check if the redirected url is the same, using the <a href="https://docs.python.org/2.6/library/urllib.html#urllib.urlopen" rel="nofollow"><code>geturl()</code></a> method:</p>
<pre><code>if urlopen(url1).geturl() == urlopen(url2).geturl():
print("It's the same file")
</code></pre>
| 1 | 2016-07-27T05:42:33Z | [
"python",
"md5"
] |
Is there any way to check from url if that file is already downloaded? | 38,604,499 | <blockquote>
<p>Suppose I have two urls which redirect to same file(hosted on 2 servers separately) and I've downloaded the file from one of the url. Is it possible to avoid downloading the same file again when I click the other url (checking in the system, if the file exists)?</p>
<p>The main aim is to optimize data usage and remove redundancy.</p>
</blockquote>
<p>I read about md5 checks for a file but can I calculate md5 checksum of a file on Internet without downloading it ?</p>
| 0 | 2016-07-27T05:35:44Z | 38,604,631 | <p>You can make use of the <a href="https://en.wikipedia.org/wiki/HTTP_ETag" rel="nofollow"><strong>Etag</strong></a> HTTP header.</p>
<blockquote>
<p>An ETag is an opaque identifier assigned by a web server to a specific
version of a resource found at a URL. If the resource representation
at that URL ever changes, a new and different ETag is assigned. Used
in this manner ETags are similar to fingerprints, and they can be
quickly compared to determine whether two representations of a
resource are the same.</p>
</blockquote>
<p>However</p>
<blockquote>
<p>The use of ETags in the HTTP header is optional (not mandatory as with
some other fields of the HTTP 1.1 header). The method by which ETags
are generated has never been specified in the HTTP specification.</p>
</blockquote>
| 2 | 2016-07-27T05:45:19Z | [
"python",
"md5"
] |
Scraping Yahoo Finance Balance Sheet with Python | 38,604,506 | <p>My question is a follow-up question to one asked <a href="http://stackoverflow.com/questions/35439105/scrape-yahoo-finance-income-statement-with-python">here</a>.</p>
<p>The function: </p>
<blockquote>
<p>periodic_figure_values()</p>
</blockquote>
<p>seems to work fine except in the case where the name of a line item being searched appears twice. The specific case I am referring to is trying to get data for "Long Term Debt". The function in the link above will return the following error:</p>
<pre><code>Traceback (most recent call last):
File "test.py", line 31, in <module>
LongTermDebt=(periodic_figure_values(soup, "Long Term Debt"))
File "test.py", line 21, in periodic_figure_values
value = int(str_value)
ValueError: invalid literal for int() with base 10: 'Short/Current Long Term Debt'
</code></pre>
<p>because it seems to get tripped up on "Short/Current Long Term Debt". You see, the page has both "Short/Current Long Term Debt" and "Long Term Debt". You can see an example of the source page using Apple's balance sheet <a href="https://ca.finance.yahoo.com/q/bs?s=AAPL&annual" rel="nofollow">here</a>. </p>
<p>I'm trying to find a way for the function to return data for "Long Term Debt" without getting tripped up on "Short/Current Long Term Debt".</p>
<p>Here is the function and an example that fetches "Cash and Cash Equivalents", which works fine, and "Long Term Debt", which does not work:</p>
<pre><code>import requests, bs4, re
def periodic_figure_values(soup, yahoo_figure):
values = []
pattern = re.compile(yahoo_figure)
title = soup.find("strong", text=pattern) # works for the figures printed in bold
if title:
row = title.parent.parent
else:
title = soup.find("td", text=pattern) # works for any other available figure
if title:
row = title.parent
else:
sys.exit("Invalid figure '" + yahoo_figure + "' passed.")
cells = row.find_all("td")[1:] # exclude the <td> with figure name
for cell in cells:
if cell.text.strip() != yahoo_figure: # needed because some figures are indented
str_value = cell.text.strip().replace(",", "").replace("(", "-").replace(")", "")
if str_value == "-":
str_value = 0
value = int(str_value)
values.append(value)
return values
res = requests.get('https://ca.finance.yahoo.com/q/bs?s=AAPL')
res.raise_for_status
soup = bs4.BeautifulSoup(res.text, 'html.parser')
Cash=(periodic_figure_values(soup, "Cash And Cash Equivalents"))
print(Cash)
LongTermDebt=(periodic_figure_values(soup, "Long Term Debt"))
print(LongTermDebt)
</code></pre>
| 3 | 2016-07-27T05:36:11Z | 38,604,725 | <p>You could change the function so that it accepts a regular expression instead of a plain string. Then you can search for <code>^Long Term Debt</code> to make sure there's no text before that. All you need to do is to change</p>
<pre><code>if cell.text.strip() != yahoo_figure:
</code></pre>
<p>to</p>
<pre><code>if not re.match(yahoo_figure, cell.text.strip()):
</code></pre>
| 0 | 2016-07-27T05:52:24Z | [
"python",
"regex",
"web-scraping",
"beautifulsoup",
"python-requests"
] |
Scraping Yahoo Finance Balance Sheet with Python | 38,604,506 | <p>My question is a follow-up question to one asked <a href="http://stackoverflow.com/questions/35439105/scrape-yahoo-finance-income-statement-with-python">here</a>.</p>
<p>The function: </p>
<blockquote>
<p>periodic_figure_values()</p>
</blockquote>
<p>seems to work fine except in the case where the name of a line item being searched appears twice. The specific case I am referring to is trying to get data for "Long Term Debt". The function in the link above will return the following error:</p>
<pre><code>Traceback (most recent call last):
File "test.py", line 31, in <module>
LongTermDebt=(periodic_figure_values(soup, "Long Term Debt"))
File "test.py", line 21, in periodic_figure_values
value = int(str_value)
ValueError: invalid literal for int() with base 10: 'Short/Current Long Term Debt'
</code></pre>
<p>because it seems to get tripped up on "Short/Current Long Term Debt". You see, the page has both "Short/Current Long Term Debt" and "Long Term Debt". You can see an example of the source page using Apple's balance sheet <a href="https://ca.finance.yahoo.com/q/bs?s=AAPL&annual" rel="nofollow">here</a>. </p>
<p>I'm trying to find a way for the function to return data for "Long Term Debt" without getting tripped up on "Short/Current Long Term Debt".</p>
<p>Here is the function and an example that fetches "Cash and Cash Equivalents", which works fine, and "Long Term Debt", which does not work:</p>
<pre><code>import requests, bs4, re
def periodic_figure_values(soup, yahoo_figure):
values = []
pattern = re.compile(yahoo_figure)
title = soup.find("strong", text=pattern) # works for the figures printed in bold
if title:
row = title.parent.parent
else:
title = soup.find("td", text=pattern) # works for any other available figure
if title:
row = title.parent
else:
sys.exit("Invalid figure '" + yahoo_figure + "' passed.")
cells = row.find_all("td")[1:] # exclude the <td> with figure name
for cell in cells:
if cell.text.strip() != yahoo_figure: # needed because some figures are indented
str_value = cell.text.strip().replace(",", "").replace("(", "-").replace(")", "")
if str_value == "-":
str_value = 0
value = int(str_value)
values.append(value)
return values
res = requests.get('https://ca.finance.yahoo.com/q/bs?s=AAPL')
res.raise_for_status
soup = bs4.BeautifulSoup(res.text, 'html.parser')
Cash=(periodic_figure_values(soup, "Cash And Cash Equivalents"))
print(Cash)
LongTermDebt=(periodic_figure_values(soup, "Long Term Debt"))
print(LongTermDebt)
</code></pre>
| 3 | 2016-07-27T05:36:11Z | 38,604,731 | <p>The easiest would be to use a <strong><code>try/except</code></strong> combination using the raised <code>ValueError</code>:</p>
<pre><code>import requests, bs4, re
def periodic_figure_values(soup, yahoo_figure):
values = []
pattern = re.compile(yahoo_figure)
title = soup.find("strong", text=pattern) # works for the figures printed in bold
if title:
row = title.parent.parent
else:
title = soup.find("td", text=pattern) # works for any other available figure
if title:
row = title.parent
else:
sys.exit("Invalid figure '" + yahoo_figure + "' passed.")
cells = row.find_all("td")[1:] # exclude the <td> with figure name
for cell in cells:
if cell.text.strip() != yahoo_figure: # needed because some figures are indented
str_value = cell.text.strip().replace(",", "").replace("(", "-").replace(")", "")
if str_value == "-":
str_value = 0
### from here
try:
value = int(str_value)
values.append(value)
except ValueError:
continue
### to here
return values
res = requests.get('https://ca.finance.yahoo.com/q/bs?s=AAPL')
res.raise_for_status
soup = bs4.BeautifulSoup(res.text, 'html.parser')
Cash=(periodic_figure_values(soup, "Cash And Cash Equivalents"))
print(Cash)
LongTermDebt=(periodic_figure_values(soup, "Long Term Debt"))
print(LongTermDebt)
</code></pre>
<p>This one prints out your numbers quite fine.<br>
Note, that you do not really need the <code>re</code> module in this situation here as you're checking for literals only (no wildcards, no boundaries), etc.</p>
| 1 | 2016-07-27T05:52:53Z | [
"python",
"regex",
"web-scraping",
"beautifulsoup",
"python-requests"
] |
Error during XML parsing | 38,604,551 | <p>I am trying to do XML parsing and get the data for <code>file_name</code> and <code>file_path</code> but running into below error ,can anyone help to figure out why and how to resolve it?</p>
<p>INPUT XML:-</p>
<pre><code><?xml version="1.0" ?>
<contents>
<build>
<name>modem</name>
<role>modem</role>
<chipset>mms1234</chipset>
</build>
<build>
<name>boot</name>
<role>boot</role>
<chipset>ms1234</chipset>
<device_programmer minimized="true">
<file_name>prog_emmc_house_4567_ddr.elf</file_name>
<file_path>images/comPkg/Msm4567Pkg/Bin64/</file_path>
</device_programmer>
<flash_programmer minimized="true">
</flash_programmer>
</build>
</contents>
</code></pre>
<p>CODE:-</p>
<pre><code>contents_xml_file = r"device_programmer.xml"
print contents_xml_file
tree = ET.parse(contents_xml_file)
root = tree.getroot()
device_programmer = root.find("device_programmer")
file_name = device_programmer.get('file_name')
print file_name
file_path = device_programmer.get('file_path')
print file_path
</code></pre>
<p>ERROR:-</p>
<pre><code>Traceback (most recent call last):
File "script.py", line 37, in <module>
file_name = device_programmer.get('file_name')
AttributeError: 'NoneType' object has no attribute 'get'
</code></pre>
| 2 | 2016-07-27T05:39:21Z | 38,605,345 | <p>From the documentation:</p>
<blockquote>
<p>Element.findall() finds only elements with a tag which are direct children of the current element. Element.find() finds the first child with a particular tag, and Element.text accesses the elementâs text content. Element.get() accesses the elementâs attributes:</p>
</blockquote>
<p>This is why </p>
<pre><code>device_programmer = root.find("device_programmer")
</code></pre>
<p>returned <code>None</code> since there is no <code>device_programmer</code> element directly under the <code>root</code>. </p>
<p>You should probably be using XPath syntax:</p>
<pre><code>device_programmer = root.find("//device_programmer")
</code></pre>
| 1 | 2016-07-27T06:32:27Z | [
"python",
"xml"
] |
Error during XML parsing | 38,604,551 | <p>I am trying to do XML parsing and get the data for <code>file_name</code> and <code>file_path</code> but running into below error ,can anyone help to figure out why and how to resolve it?</p>
<p>INPUT XML:-</p>
<pre><code><?xml version="1.0" ?>
<contents>
<build>
<name>modem</name>
<role>modem</role>
<chipset>mms1234</chipset>
</build>
<build>
<name>boot</name>
<role>boot</role>
<chipset>ms1234</chipset>
<device_programmer minimized="true">
<file_name>prog_emmc_house_4567_ddr.elf</file_name>
<file_path>images/comPkg/Msm4567Pkg/Bin64/</file_path>
</device_programmer>
<flash_programmer minimized="true">
</flash_programmer>
</build>
</contents>
</code></pre>
<p>CODE:-</p>
<pre><code>contents_xml_file = r"device_programmer.xml"
print contents_xml_file
tree = ET.parse(contents_xml_file)
root = tree.getroot()
device_programmer = root.find("device_programmer")
file_name = device_programmer.get('file_name')
print file_name
file_path = device_programmer.get('file_path')
print file_path
</code></pre>
<p>ERROR:-</p>
<pre><code>Traceback (most recent call last):
File "script.py", line 37, in <module>
file_name = device_programmer.get('file_name')
AttributeError: 'NoneType' object has no attribute 'get'
</code></pre>
| 2 | 2016-07-27T05:39:21Z | 38,606,489 | <p>Since <code>device_programmer</code> is not direct child of the root element, you need to add <code>.//</code> at the beginning. The <code>.</code> indicates that the XPath is relative to the context element (the root element in this case), and <code>//</code> is abbreviated syntax for <code>descendant-or-self</code> axis :</p>
<pre><code>device_programmer = root.find(".//device_programmer")
</code></pre>
<p>Instead of attributes, <code>file_name</code> and <code>file_path</code> are direct child of <code>device_programmer</code>, so you need to use <code>find('element_name')</code> to get them :</p>
<pre><code>file_name = device_programmer.find('file_name')
print file_name.text
file_path = device_programmer.find('file_path')
print file_path.text
</code></pre>
| 0 | 2016-07-27T07:27:04Z | [
"python",
"xml"
] |
black box script execution? | 38,604,598 | <p>I have a client that would like to examine results of a script I have written. I don't want the client to see the inner workings of the script or I lose my value to them but I want them to be able to run it as many times as they want and observe the results. </p>
<p>I am not sure if there is a general solution to this or specific to a language. If the latter applies, I have scripts in Python and R. </p>
<p>Thanks</p>
| 1 | 2016-07-27T05:43:00Z | 38,605,047 | <p>How about writing scripts outputs to files ,and construct a web interface that consumes this files and displays them in read-only mode? </p>
<p>For example in R you can use
sink()
to route the output messages to a file, you then construct a web interface that simply displays this file.</p>
| 2 | 2016-07-27T06:13:08Z | [
"python",
"machine-learning",
"simulation"
] |
black box script execution? | 38,604,598 | <p>I have a client that would like to examine results of a script I have written. I don't want the client to see the inner workings of the script or I lose my value to them but I want them to be able to run it as many times as they want and observe the results. </p>
<p>I am not sure if there is a general solution to this or specific to a language. If the latter applies, I have scripts in Python and R. </p>
<p>Thanks</p>
| 1 | 2016-07-27T05:43:00Z | 38,605,152 | <p>In Python you can easily use Flask to provide a restful API that the client can send their HTTP request with their parameters and you can provide them with the results.</p>
<p>It is very easy to convert a Python function into a web server. It is as easy as this function:</p>
<pre><code>@app.route('/geo', methods=['GET', 'POST'])
def geo_web():
'''
RESTful API
given a piece of text, vectorize it, classify it into one of the regions using clf (a pre-trained classifier) and return a json which has info about the predicted location(s).
'''
text = request.args['text']
if isinstance(text, list) or isinstance(text, tuple) or len(text) == 0:
return
result = None
try:
result = geo(text, return_lbl_dist=False)
except:
return
return jsonify(**result)
</code></pre>
<p>You just need to add the @app.route... and return a result that can be processed when the HTTP response is read.</p>
<p>You can see my entire project in <a href="https://github.com/afshinrahimi/pigeo" rel="nofollow">here</a>.</p>
| 1 | 2016-07-27T06:20:40Z | [
"python",
"machine-learning",
"simulation"
] |
Unicode() in python 3 | 38,604,655 | <p>I have python 2x code which uses unicode() function before searching ascii strings in unicode list. Short of exception catching or evaluating python version, what is the best way to port this code so it works in both python 2 and 3? </p>
| 0 | 2016-07-27T05:47:04Z | 38,605,313 | <p>Sometimes this dirty hack is enough</p>
<pre><code>try:
unicode
except NameError:
unicode = str
</code></pre>
<p>@honi wrote good advice, use <a href="https://pypi.python.org/pypi/six" rel="nofollow">six</a>.</p>
| 2 | 2016-07-27T06:29:57Z | [
"python",
"unicode"
] |
for loop is run more times then specified. | 38,604,673 | <p>I have been trying to make a drop down menu in pygame. I have a method that that takes a list of strings and renders them to the screen using a for loop. The for loop is shown below.</p>
<pre><code> spacer = 0
for text in range(5):
spacer += 30
rect = pygame.Rect(0, spacer, 100, 20)
pygame.draw.rect(self.surface, (255, 0, 0), rect)
self.rect_list.append(rect)
</code></pre>
<p>I appended each rectangle that was created in the for loop to a list <code>rect_list</code>.
i then printed the list to the screen to see it's contents. The Python IDLE window was spammed with the contents of the list. </p>
<p>The method that contained in the for loop is being called in a second method of another class <code>Menu</code>. The method in class <code>Menu</code> is called in a while loop:</p>
<pre><code>while running:
for event in pygame.event.get():
if event.type == pg.QUIT:
running = False
pygame.quit()
quit()
#--------method being called in while loop----------#
Menu_Class_Obj.render_menu()
#--------method being called in while loop----------#
pygame.display.update()
</code></pre>
| 0 | 2016-07-27T05:48:40Z | 38,605,055 | <p>Every time your menu is rendered, you're appending to <code>menu_items_rect_list</code>. Whatever you put in that list will stay there indefinitely. If you want the list to be empty at the start of the frame, you need to clear it yourself.</p>
| 1 | 2016-07-27T06:13:39Z | [
"python",
"for-loop",
"methods",
"pygame"
] |
for loop is run more times then specified. | 38,604,673 | <p>I have been trying to make a drop down menu in pygame. I have a method that that takes a list of strings and renders them to the screen using a for loop. The for loop is shown below.</p>
<pre><code> spacer = 0
for text in range(5):
spacer += 30
rect = pygame.Rect(0, spacer, 100, 20)
pygame.draw.rect(self.surface, (255, 0, 0), rect)
self.rect_list.append(rect)
</code></pre>
<p>I appended each rectangle that was created in the for loop to a list <code>rect_list</code>.
i then printed the list to the screen to see it's contents. The Python IDLE window was spammed with the contents of the list. </p>
<p>The method that contained in the for loop is being called in a second method of another class <code>Menu</code>. The method in class <code>Menu</code> is called in a while loop:</p>
<pre><code>while running:
for event in pygame.event.get():
if event.type == pg.QUIT:
running = False
pygame.quit()
quit()
#--------method being called in while loop----------#
Menu_Class_Obj.render_menu()
#--------method being called in while loop----------#
pygame.display.update()
</code></pre>
| 0 | 2016-07-27T05:48:40Z | 38,837,126 | <p>The answer to my question is very obvious once I really thought about what was happing. Since I'm calling the method that contains the for-loop in a while loop, the for-loop is being run multiple times. The two solutions I've used for this problem are:
1. setting a limit to how many items can be in the list:</p>
<pre><code>if len(self.rect_list) > 5):
self.rect_list = self.rect_list[:5]
</code></pre>
<p>and two; deleting any more elements then a specified number:</p>
<pre><code>if len(self.text_rect_list) > len(self.sub_items):
del self.text_rect_list[:len(self.sub_items)]
</code></pre>
| 0 | 2016-08-08T19:31:13Z | [
"python",
"for-loop",
"methods",
"pygame"
] |
Convert list into list of lists | 38,604,805 | <p>I want to convert list into list of list. Example:</p>
<pre><code>my_list = ['banana', 'mango', 'apple']
</code></pre>
<p>I want:</p>
<pre><code>my_list = [['banana'], ['mango'], ['apple']]
</code></pre>
<p>I tried:</p>
<pre><code>list(list(my_list))
</code></pre>
| -3 | 2016-07-27T05:57:34Z | 38,604,810 | <p>Use list comprehension</p>
<pre><code>[[i] for i in lst]
</code></pre>
<p>It iterates over each item in the list and put that item into a new list.</p>
<p><em>Example:</em></p>
<pre><code>>>> lst = ['banana', 'mango', 'apple']
>>> [[i] for i in lst]
[['banana'], ['mango'], ['apple']]
</code></pre>
<p>If you apply <code>list</code> func on each item, it would turn each item which is in string format to a list of strings.</p>
<pre><code>>>> [list(i) for i in lst]
[['b', 'a', 'n', 'a', 'n', 'a'], ['m', 'a', 'n', 'g', 'o'], ['a', 'p', 'p', 'l', 'e']]
>>>
</code></pre>
| 6 | 2016-07-27T05:58:13Z | [
"python",
"list"
] |
Convert list into list of lists | 38,604,805 | <p>I want to convert list into list of list. Example:</p>
<pre><code>my_list = ['banana', 'mango', 'apple']
</code></pre>
<p>I want:</p>
<pre><code>my_list = [['banana'], ['mango'], ['apple']]
</code></pre>
<p>I tried:</p>
<pre><code>list(list(my_list))
</code></pre>
| -3 | 2016-07-27T05:57:34Z | 38,604,912 | <p>Try This one Liner:-</p>
<pre><code>map(lambda x:[x], my_list)
</code></pre>
<p><strong>Result</strong></p>
<pre><code>In [1]: map(lambda x:[x], my_list)
Out[1]: [['banana'], ['mango'], ['apple']]
</code></pre>
| 2 | 2016-07-27T06:04:36Z | [
"python",
"list"
] |
Which Exception class is the most suitable for flagging excess number of calls to a function? | 38,604,885 | <p>I have a database connection object, and I want to restrict/enforce max number of calls to it's write operation (function). I have mocked it in tests, and have overridden the write method to monitor calls to it.</p>
<p>However, I am confused about what error to raise when it's called more than the max number allowed (say 2). I've gone through the <a href="https://docs.python.org/2/library/exceptions.html" rel="nofollow">docs</a> but haven't found anything suitable. (Hence, as it suggests) I have used <code>RuntimeError</code> but I am not fully convinced about the message it gives (not the explicit message I display, but the implicit meaning conveyed by the class itself). I feel <code>AttributeError</code> to be a far fit, but nothing else come that close to correctness.</p>
<p>Is there any other builtin exception class which is more suitable for this? </p>
| 0 | 2016-07-27T06:02:39Z | 38,605,509 | <p>If you supply too many arguments to a function you get something like this:</p>
<pre><code>TypeError: function-name takes exactly n arguments (m given)
</code></pre>
<p>So you could do the same to mirror Python. You should probably be careful when you call <code>raise</code> to ensure that your exception string is distinguishable from one raised by Python, otherwise you could mask a genuine <code>TypeError</code>.</p>
<p>Opinion on this is divided. Some say that custom Exception classes are not required. Personally I think there is a place for them if there could be confusion. Creating your own Exception is quite easy, all you need is:</p>
<pre><code>class MyException(TypeError):
pass
</code></pre>
<p>Now you know that any occurrences come from your code, not from Python. Remember if you put this in a module or a class to prefix with the namespace, e.g. <code>MyClass.MyException</code>.</p>
| 0 | 2016-07-27T06:41:50Z | [
"python",
"python-2.7",
"exception",
"semantics"
] |
Pandas indexing after grouping | 38,604,953 | <p>that might be a very simple question, but I am trying to understand how grouping and indexing works in pandas. </p>
<p>Let's say, I have a DataFrame with following data: </p>
<pre><code>df = pd.DataFrame(data={
'p_id': [1, 1, 1, 2, 3, 3, 3, 4, 4],
'rating': [5, 3, 2, 2, 5, 1, 3, 4, 5]
})
</code></pre>
<p>Now, index would be assigned automatically, so DataFrame looks like:</p>
<pre><code> p_id rating
0 1 5
1 1 3
2 1 2
3 2 2
4 3 5
5 3 1
6 3 3
7 4 4
8 4 5
</code></pre>
<p>When I try to group it by p_id, I get:</p>
<pre><code>>> df[['p_id', 'rating']].groupby('p_id').count()
rating
p_id
1 3
2 1
3 3
4 2
</code></pre>
<p>I noticed that p_id now becomes an index for this DataFrame, but first row looks weird to me -- why does it have 'p_id' index in it with empty rating? </p>
<p>I know how to fix it, kind of, if I do this: </p>
<pre><code>>> df[['p_id', 'rating']].groupby('p_id', as_index=False).count()
p_id rating
0 1 3
1 2 1
2 3 3
3 4 2
</code></pre>
<p>Now I don't have this weird first column, but I have both index and p_id. </p>
<p>So my question is, where does this extra row coming from when I don't use as_index=False and is there a way to group DataFrame and keep p_id as index while not having to deal with this extra row? If there are any docs I can read on this, that would also be greatly appreciated.</p>
<p>Thanks</p>
| 2 | 2016-07-27T06:07:40Z | 38,605,016 | <p>It's just an index name...</p>
<p>Demo:</p>
<pre><code>In [46]: df
Out[46]:
p_id rating
0 1 5
1 1 3
2 1 2
3 2 2
4 3 5
5 3 1
6 3 3
7 4 4
8 4 5
In [47]: df.index.name = 'AAA'
</code></pre>
<p>pay attention at the index name: <code>AAA</code></p>
<pre><code>In [48]: df
Out[48]:
p_id rating
AAA
0 1 5
1 1 3
2 1 2
3 2 2
4 3 5
5 3 1
6 3 3
7 4 4
8 4 5
</code></pre>
<p>You can get rid of it using <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.rename_axis.html" rel="nofollow">rename_axis()</a> method:</p>
<pre><code>In [42]: df[['p_id', 'rating']].groupby('p_id').count().rename_axis(None)
Out[42]:
rating
1 3
2 1
3 3
4 2
</code></pre>
| 2 | 2016-07-27T06:11:06Z | [
"python",
"pandas",
"dataframe"
] |
python pandas from itemset to dataframe | 38,604,963 | <p>What is the more scalable way to go from an itemset list::</p>
<pre><code>itemset = [['a', 'b'],
['b', 'c', 'd'],
['a', 'c', 'd', 'e'],
['d'],
['a', 'b', 'c'],
['a', 'b', 'c', 'd']]
</code></pre>
<p>To a dataframe of this kind ::</p>
<pre><code>>>> df
a b c d e
0 1 1 0 0 0
1 0 1 1 1 0
2 1 0 1 1 1
3 0 0 0 1 0
4 1 1 1 0 0
5 1 1 1 1 0
>>>
</code></pre>
<p>The target size of df is 1e6 rows and 500 columns.</p>
| 2 | 2016-07-27T06:08:04Z | 38,605,085 | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.get_dummies.html" rel="nofollow"><code>get_dummies</code></a>:</p>
<pre><code>print (pd.DataFrame(itemset))
0 1 2 3
0 a b None None
1 b c d None
2 a c d e
3 d None None None
4 a b c None
5 a b c d
df1 = (pd.get_dummies(pd.DataFrame(itemset), prefix='', prefix_sep='' ))
print (df1)
a b d b c c d d e
0 1.0 0.0 0.0 1.0 0.0 0.0 0.0 0.0 0.0
1 0.0 1.0 0.0 0.0 1.0 0.0 1.0 0.0 0.0
2 1.0 0.0 0.0 0.0 1.0 0.0 1.0 0.0 1.0
3 0.0 0.0 1.0 0.0 0.0 0.0 0.0 0.0 0.0
4 1.0 0.0 0.0 1.0 0.0 1.0 0.0 0.0 0.0
5 1.0 0.0 0.0 1.0 0.0 1.0 0.0 1.0 0.0
print (df1.groupby(df1.columns, axis=1).sum().astype(int))
a b c d e
0 1 1 0 0 0
1 0 1 1 1 0
2 1 0 1 1 1
3 0 0 0 1 0
4 1 1 1 0 0
5 1 1 1 1 0
</code></pre>
| 2 | 2016-07-27T06:16:45Z | [
"python",
"numpy",
"pandas"
] |
python pandas from itemset to dataframe | 38,604,963 | <p>What is the more scalable way to go from an itemset list::</p>
<pre><code>itemset = [['a', 'b'],
['b', 'c', 'd'],
['a', 'c', 'd', 'e'],
['d'],
['a', 'b', 'c'],
['a', 'b', 'c', 'd']]
</code></pre>
<p>To a dataframe of this kind ::</p>
<pre><code>>>> df
a b c d e
0 1 1 0 0 0
1 0 1 1 1 0
2 1 0 1 1 1
3 0 0 0 1 0
4 1 1 1 0 0
5 1 1 1 1 0
>>>
</code></pre>
<p>The target size of df is 1e6 rows and 500 columns.</p>
| 2 | 2016-07-27T06:08:04Z | 38,607,800 | <p>Here's an almost vectorized approach -</p>
<pre><code>items = np.concatenate(itemset)
col_idx = np.fromstring(items, dtype=np.uint8)-97
lens = np.array([len(item) for item in itemset])
row_idx = np.repeat(np.arange(lens.size),lens)
out = np.zeros((lens.size,lens.max()+1),dtype=int)
out[row_idx,col_idx] = 1
df = pd.DataFrame(out,columns=np.unique(items))
</code></pre>
<p>The last line could be replaced by something like this and could be more performant -</p>
<pre><code>df = pd.DataFrame(out,columns=items[np.unique(col_idx,return_index=True)[1]])
</code></pre>
| 0 | 2016-07-27T08:33:41Z | [
"python",
"numpy",
"pandas"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.