title
stringlengths 10
172
| question_id
int64 469
40.1M
| question_body
stringlengths 22
48.2k
| question_score
int64 -44
5.52k
| question_date
stringlengths 20
20
| answer_id
int64 497
40.1M
| answer_body
stringlengths 18
33.9k
| answer_score
int64 -38
8.38k
| answer_date
stringlengths 20
20
| tags
list |
---|---|---|---|---|---|---|---|---|---|
Longest increasing subsequence in O(n) time? | 39,952,186 | <p>I'm studying this algorithm for the first time. CLRS (15-4.6) asks to write an algorithm to run in O(n lg n) time. The algorithm I came up with seems to run in O(n). I think I must be misunderstanding something, because even wikipedia says it should take O(n lg n) time. (<a href="https://en.wikipedia.org/wiki/Longest_increasing_subsequence" rel="nofollow">https://en.wikipedia.org/wiki/Longest_increasing_subsequence</a>)<br>
Could somebody tell me why this algorithm (in Python) doesn't work in general or isn't O(n) or doesn't answer the question??</p>
<pre><code>"""Attempts to find maximal ordered subsequence in linear time."""
def subseq(n):
"""Assumes the elements of n are unique"""
if len(n) == 1:
return n[:]
first = [n[0]]
second = []
for i in range(1,len(n)):
if n[i] > first[-1]:
second = first[:]
first.append(n[i])
elif not second or n[i] > second[-1]:
first = second[:]
first.append(n[i])
return first
print subseq([0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15])
</code></pre>
| 0 | 2016-10-10T06:09:00Z | 39,952,405 | <p>I'll leave some of the debugging to you, but the following does not produce the maximum length substring using your algorithm. I simply added a few numbers to the example you had, so it should have produced <code>[0, 4, 6, 9, 11, 15]</code> again, but didn't:</p>
<pre><code>>>> print(subseq([0, 12,12,15,14 ,8, 4, 12, 14, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15]))
[0, 12, 13, 15]
</code></pre>
| 0 | 2016-10-10T06:29:15Z | [
"python",
"algorithm",
"longest-substring"
] |
python-rope/ropevim doesn't work properly | 39,952,334 | <p>I've already installed these, pip list:</p>
<pre><code>rope (0.10.3)
ropemode (0.3)
ropevim (0.7.0)
</code></pre>
<p>All the vim plugins I have:</p>
<pre><code>Plugin 'gmarik/vundle'
Plugin 'scrooloose/nerdtree'
Plugin 'jistr/vim-nerdtree-tabs'
Plugin 'altercation/vim-colors-solarized'
Plugin 'kien/ctrlp.vim'
Plugin 'SirVer/ultisnips'
Plugin 'honza/vim-snippets'
Plugin 'jiangmiao/auto-pairs'
Plugin 'scrooloose/nerdcommenter'
Plugin 'vim-airline/vim-airline'
Plugin 'vim-airline/vim-airline-themes'
Plugin 'Valloric/YouCompleteMe'
Plugin 'majutsushi/tagbar
Plugin 'Yggdroot/indentLine'
Plugin 'xolox/vim-misc'
Plugin 'xolox/vim-session'
Plugin 'tpope/vim-surround'
Plugin 'tpope/vim-repeat'
Plugin 'tpope/vim-fugitive'
Plugin 'vim-scripts/VisIncr'
Plugin 'easymotion/vim-easymotion'
Plugin 'godlygeek/tabular'
Plugin 'ternjs/tern_for_vim'
Plugin 'scrooloose/syntastic'
Plugin 'Shutnik/jshint2.vim'
Plugin 'python-rope/ropevim'
</code></pre>
<p>:map</p>
<pre><code>n [m *@:call <SNR>108_Python_jump('?^\s*\(class\|def\)')<CR>
n [[ *@:call <SNR>108_Python_jump('?^\(class\|def\)')<CR>
n ]m *@:call <SNR>108_Python_jump('/^\s*\(class\|def\)')<CR>
n ]] *@:call <SNR>108_Python_jump('/^\(class\|def\)')<CR>
î *@:call AutoPairsJump()<CR>
ð *@:call AutoPairsToggle()<CR>
n <C-A> * ggVG
s <C-H> * <C-G>c
x <Tab> * :call UltiSnips#SaveLastVisualSelection()<CR>gvs
s <Tab> * <Esc>:call UltiSnips#ExpandSnippetOrJump()<CR>
n <CR> o<Esc>
n <C-N> * :bnext<CR>
n <C-P> * :bprevious<CR>
s <C-R> * <C-G>"_c<C-R>
<Space> <Plug>(easymotion-f)
,, <Plug>(easymotion-prefix)
n ,ca <Plug>NERDCommenterAltDelims
x ,cu <Plug>NERDCommenterUncomment
n ,cu <Plug>NERDCommenterUncomment
x ,cb <Plug>NERDCommenterAlignBoth
n ,cb <Plug>NERDCommenterAlignBoth
x ,cl <Plug>NERDCommenterAlignLeft
n ,cl <Plug>NERDCommenterAlignLeft
n ,cA <Plug>NERDCommenterAppend
x ,cy <Plug>NERDCommenterYank
n ,cy <Plug>NERDCommenterYank
x ,cs <Plug>NERDCommenterSexy
n ,cs <Plug>NERDCommenterSexy
x ,ci <Plug>NERDCommenterInvert
n ,ci <Plug>NERDCommenterInvert
n ,c$ <Plug>NERDCommenterToEOL
x ,cn <Plug>NERDCommenterNested
n ,cn <Plug>NERDCommenterNested
x ,cm <Plug>NERDCommenterMinimal
n ,cm <Plug>NERDCommenterMinimal
x ,c<Space> <Plug>NERDCommenterToggle
n ,c<Space> <Plug>NERDCommenterToggle
x ,cc <Plug>NERDCommenterComment
n ,cc <Plug>NERDCommenterComment
n ,o * :<C-U>CtrlP<CR>
n ,c * :SyntasticCheck<CR>
n ,9 * :9wincmd w<CR>
n ,8 * :8wincmd w<CR>
n ,7 * :7wincmd w<CR>
n ,6 * :6wincmd w<CR>
n ,5 * :5wincmd w<CR>
n ,4 * :4wincmd w<CR>
n ,3 * :3wincmd w<CR>
n ,2 * :2wincmd w<CR>
n ,1 * :1wincmd w<CR>
n ,n * :NERDTreeToggle<CR>
n ,r * :Java %<CR>
n ,s * :JavaSearchContext<CR>
n ,d * :JavaDocSearch -x declarations<CR>
n ,i * :JavaImportOrganize<CR>
n ,os * :OpenSession<CR>
n ,sv * :source $MYVIMRC<CR>
n ,v :e $MYVIMRC<CR>
n ,w * :wall<CR>
n ,q * :bp<CR>:bd #<CR>
n ,p "+p
v ,p "+p
n ,y "+y
v ,y "+y
x S <Plug>VSurround
n cS <Plug>CSurround
n cs <Plug>Csurround
n ds <Plug>Dsurround
v gx <Plug>NetrwBrowseXVis
n gx <Plug>NetrwBrowseX
x gS <Plug>VgSurround
n ySS <Plug>YSsurround
n ySs <Plug>YSsurround
n yss <Plug>Yssurround
n yS <Plug>YSurround
n ys <Plug>Ysurround
v <Plug>NetrwBrowseXVis * :<C-U>call netrw#BrowseXVis()<CR>
n <Plug>NetrwBrowseX * :call netrw#BrowseX(expand((exists("g:netrw_gx")? g:netrw_gx : '<cfile>')),netrw#CheckIfRemote())<CR>
<Plug>(easymotion-prefix)N <Plug>(easymotion-N)
<Plug>(easymotion-prefix)n <Plug>(easymotion-n)
# ----- other easymotion-perfix ------- #
x <Plug>(easymotion-activate) * :<C-U>call EasyMotion#activate(1)<CR>
nos<Plug>(easymotion-activate) * :<C-U>call EasyMotion#activate(0)<CR>
<Plug>(easymotion-dotrepeat) * :<C-U>call EasyMotion#DotRepeat()<CR>
# ----- Other easymotion options ------ #
n <SNR>74_: * :<C-U><C-R>=v:count ? v:count : ''<CR>
v <Plug>VgSurround * :<C-U>call <SNR>73_opfunc(visualmode(),visualmode() ==# 'V' ? 0 : 1)<CR>
v <Plug>VSurround * :<C-U>call <SNR>73_opfunc(visualmode(),visualmode() ==# 'V' ? 1 : 0)<CR>
n <Plug>YSurround * :<C-U>set opfunc=<SNR>73_opfunc2<CR>g@
n <Plug>Ysurround * :<C-U>set opfunc=<SNR>73_opfunc<CR>g@
n <Plug>YSsurround * :<C-U>call <SNR>73_opfunc2(v:count1)<CR>
n <Plug>Yssurround * :<C-U>call <SNR>73_opfunc(v:count1)<CR>
n <Plug>CSurround * :<C-U>call <SNR>73_changesurround(1)<CR>
n <Plug>Csurround * :<C-U>call <SNR>73_changesurround()<CR>
n <Plug>Dsurround * :<C-U>call <SNR>73_dosurround(<SNR>73_inputtarget())<CR>
n <Plug>SurroundRepeat * .
n <Plug>NERDCommenterAltDelims * :call <SNR>60_SwitchToAlternativeDelimiters(1)<CR>
x <Plug>NERDCommenterUncomment * :call NERDComment("x", "Uncomment")<CR>
n <Plug>NERDCommenterUncomment * :call NERDComment("n", "Uncomment")<CR>
x <Plug>NERDCommenterAlignBoth * :call NERDComment("x", "AlignBoth")<CR>
n <Plug>NERDCommenterAlignBoth * :call NERDComment("n", "AlignBoth")<CR>
x <Plug>NERDCommenterAlignLeft * :call NERDComment("x", "AlignLeft")<CR>
n <Plug>NERDCommenterAlignLeft * :call NERDComment("n", "AlignLeft")<CR>
n <Plug>NERDCommenterAppend * :call NERDComment("n", "Append")<CR>
x <Plug>NERDCommenterYank * :call NERDComment("x", "Yank")<CR>
n <Plug>NERDCommenterYank * :call NERDComment("n", "Yank")<CR>
x <Plug>NERDCommenterSexy * :call NERDComment("x", "Sexy")<CR>
n <Plug>NERDCommenterSexy * :call NERDComment("n", "Sexy")<CR>
x <Plug>NERDCommenterInvert * :call NERDComment("x", "Invert")<CR>
n <Plug>NERDCommenterInvert * :call NERDComment("n", "Invert")<CR>
n <Plug>NERDCommenterToEOL * :call NERDComment("n", "ToEOL")<CR>
x <Plug>NERDCommenterNested * :call NERDComment("x", "Nested")<CR>
n <Plug>NERDCommenterNested * :call NERDComment("n", "Nested")<CR>
x <Plug>NERDCommenterMinimal * :call NERDComment("x", "Minimal")<CR>
n <Plug>NERDCommenterMinimal * :call NERDComment("n", "Minimal")<CR>
x <Plug>NERDCommenterToggle * :call NERDComment("x", "Toggle")<CR>
n <Plug>NERDCommenterToggle * :call NERDComment("n", "Toggle")<CR>
x <Plug>NERDCommenterComment * :call NERDComment("x", "Comment")<CR>
n <Plug>NERDCommenterComment * :call NERDComment("n", "Comment")<CR>
s <Del> * <C-G>c
s <BS> * <C-G>c
s <C-Tab> * <Esc>:call UltiSnips#ListSnippets()<CR>
<Plug>NERDTreeFocusToggle & :call <SNR>53_NERDTreeFocusToggle()
<Plug>NERDTreeSteppedClose & :call <SNR>53_NERDTreeSteppedClose()
<Plug>NERDTreeSteppedOpen & :call <SNR>53_NERDTreeSteppedOpen()
<Plug>NERDTreeMirrorToggle & :call <SNR>53_NERDTreeMirrorToggle()
<Plug>NERDTreeMirrorOpen & :call <SNR>53_NERDTreeMirrorOrCreate()
<Plug>NERDTreeTabsFind & :call <SNR>53_NERDTreeFindFile()
<Plug>NERDTreeTabsToggle & :call <SNR>53_NERDTreeToggleAllTabs()
<Plug>NERDTreeTabsClose & :call <SNR>53_NERDTreeCloseAllTabs()
<Plug>NERDTreeTabsOpen & :call <SNR>53_NERDTreeOpenAllTabs()
n <M-Right> <C-W><
n <M-Left> <C-W>>
n <M-Up> <C-W>+
n <M-Down> <C-W>-
n <F2> * :call NumberToggle()<CR>
</code></pre>
<p>:imap</p>
<pre><code>i <BS> *@<C-R>=AutoPairsDelete()<CR>
i î *@<Esc>:call AutoPairsJump()<CR>a
i ð *@AutoPairsToggle()
i â *@<C-R>=AutoPairsBackInsert()<CR>
i å *@<C-R>=AutoPairsFastWrap()<CR>
i <C-H> *@<C-R>=AutoPairsDelete()<CR>
i <CR> &@<CR><SNR>59_AutoPairsReturn
i <Space> *@<C-]><C-R>=AutoPairsSpace()<CR>
i " *@<C-R>=AutoPairsInsert('"')<CR>
i ' *@<C-R>=AutoPairsInsert('''')<CR>
i ( *@<C-R>=AutoPairsInsert('(')<CR>
i ) *@<C-R>=AutoPairsInsert(')')<CR>
i [ *@<C-R>=AutoPairsInsert('[')<CR>
i ] *@<C-R>=AutoPairsInsert(']')<CR>
i ` *@<C-R>=AutoPairsInsert('`')<CR>
i { *@<C-R>=AutoPairsInsert('{')<CR>
i } *@<C-R>=AutoPairsInsert('}')<CR>
i <Up> * pumvisible() ? "\<C-P>" : "\<Up>"
i <Down> * pumvisible() ? "\<C-N>" : "\<Down>"
i <Plug>ISurround * <C-R>=<SNR>73_insert(1)<CR>
i <Plug>Isurround * <C-R>=<SNR>73_insert()<CR>
i <Plug>NERDCommenterInsert * <Space><BS><Esc>:call NERDComment('i', "insert")<CR>
i <Plug>AutoPairsReturn & <SNR>59_AutoPairsReturn
i <SNR>59_AutoPairsReturn * <C-R>=AutoPairsReturn()<CR>
i <C-Tab> * <C-R>=UltiSnips#ListSnippets()<CR>
i <C-G>S <Plug>ISurround
i <C-G>s <Plug>Isurround
i <Tab> * <C-R>=UltiSnips#ExpandSnippetOrJump()<CR>
i <NL> * <C-X><C-O><C-P>
i <C-N> * pumvisible() ? "\<C-N>" : "\<C-N>"
i <C-P> * pumvisible() ? "\<C-P>" : "\<C-P>"
i <C-S> <Plug>Isurround
i kj <Esc>
</code></pre>
<p><code>:version</code> shows <code>-python</code> <code>+python3</code></p>
<p>I didn't add any config of ropevim in <code>.vimrc</code>.
Right now, the whole keybindings don't work. If I type <code>:Rope</code> and tab, nothing shows up. But <code>:h rope</code> will show the docs</p>
<p>Is there anything I missed when installing? Or any configs should be put into .vimrc?</p>
| 0 | 2016-10-10T06:22:51Z | 39,968,142 | <p>What does <code>:map</code> shows? What does <code>:imap</code> shows for <code>Ctrl-]</code>? I have this in my <code>~/.vimrc</code>:</p>
<pre><code>let ropevim_vim_completion=1
let ropevim_extended_complete=1
let ropevim_codeassist_maxfixes=1
let ropevim_goto_def_newwin="tabnew"
let ropevim_autoimport_modules = ["os.*","traceback", "xml.etree"]
"imap <c-space> <C-R>=RopeCodeAssistInsertMode()<CR>
au FileType python
\ noremap <silent> <buffer> <C-]> :RopeGotoDefinition<CR>
</code></pre>
<hr>
<p>OK, so the problem was vim which was not supporting Python 2 plugins. Rope is not yet py3k-compatible.</p>
| 0 | 2016-10-10T23:14:27Z | [
"python",
"vim",
"rope"
] |
How to get the outuput in the correct format | 39,952,498 | <p><img src="http://i.stack.imgur.com/ERBAv.png" alt="enter image description here"> </p>
<pre><code>def read_ndfa(file : open) -> {str:{str:{str}}}:
pass
</code></pre>
<p>file =</p>
<pre><code>start;0;start;1;start;0;near
near;1;end
end
</code></pre>
<p>correct output = <code>{'end': {}, 'start': {'1': {'start'}, '0': {'start', 'near'}}, 'near': {'1': {'end'}}}</code></p>
<p>I need to write a function that takes a file as an input to get the correct output as above. however, I have no idea how to create the inner dictionary by using zip function. can someone show me the correct way to do it? Many thanks.</p>
| -4 | 2016-10-10T06:37:00Z | 39,952,830 | <p>You can take a look at this :</p>
<pre><code>import csv
f = open('data.csv', 'r')
r = csv.reader(f, delimiter=';')
out = {}
for row in r:
out[row[0]] = {} # Set the top level key
# Loop on all odd elements
for pos in range(1, len(row), 2):
if row[pos] in out[row[0]]:
# Add the element to the existing set
out[row[0]][row[pos]].add(row[pos+1])
else:
# Create a new set for the key
out[row[0]][row[pos]] = set([row[pos+1]])
print(out)
f.close()
</code></pre>
<p>Which gives :</p>
<pre><code>{'near': {'1': {'end'}}, 'end': {}, 'start': {'0': {'near', 'start'}, '1': {'start'}}}
</code></pre>
| 0 | 2016-10-10T07:04:18Z | [
"python"
] |
Wrong math result with calling C extension in Python | 39,952,565 | <p>I am calling the <code>pow()</code> function of C's math library. My installation is Python3.5 on Windows 10 but I tried the same program in Python2.7 with same result. The return from the function is not as expected. Not sure what's happening. The code is given below. The result I get is 1.0.</p>
<pre><code>from ctypes import *
libc = cdll.msvcrt
libc.pow.argtypes = [c_double, c_int]
libc.pow.restype = c_double
libc.pow(2.3, 2)
</code></pre>
| 0 | 2016-10-10T06:41:59Z | 39,952,623 | <p>There is a type mismatch. Use c_double for power as well.
Like this. It should work.</p>
<p>libc.pow.argtypes = [c_double, c_double]</p>
| 1 | 2016-10-10T06:46:40Z | [
"python",
"python-c-extension"
] |
Wrong math result with calling C extension in Python | 39,952,565 | <p>I am calling the <code>pow()</code> function of C's math library. My installation is Python3.5 on Windows 10 but I tried the same program in Python2.7 with same result. The return from the function is not as expected. Not sure what's happening. The code is given below. The result I get is 1.0.</p>
<pre><code>from ctypes import *
libc = cdll.msvcrt
libc.pow.argtypes = [c_double, c_int]
libc.pow.restype = c_double
libc.pow(2.3, 2)
</code></pre>
| 0 | 2016-10-10T06:41:59Z | 39,952,655 | <p>pow in C libray takes double, double as input arguments. That's why.</p>
<pre><code>from ctypes import *
libc = cdll.msvcrt
libc.pow.argtypes = [c_double, c_double]
libc.pow.restype = c_double
libc.pow(2.3, 2.0)
</code></pre>
| 0 | 2016-10-10T06:49:16Z | [
"python",
"python-c-extension"
] |
Wrong math result with calling C extension in Python | 39,952,565 | <p>I am calling the <code>pow()</code> function of C's math library. My installation is Python3.5 on Windows 10 but I tried the same program in Python2.7 with same result. The return from the function is not as expected. Not sure what's happening. The code is given below. The result I get is 1.0.</p>
<pre><code>from ctypes import *
libc = cdll.msvcrt
libc.pow.argtypes = [c_double, c_int]
libc.pow.restype = c_double
libc.pow(2.3, 2)
</code></pre>
| 0 | 2016-10-10T06:41:59Z | 39,952,662 | <p>Double check your types, I'm pretty sure the prototype for pow is </p>
<blockquote>
<p>double pow(double a, double b);</p>
</blockquote>
<p>So changes this line </p>
<blockquote>
<p>libc.pow.argtypes = [c_double, c_int]</p>
</blockquote>
<p>To </p>
<blockquote>
<p>libc.pow.argtypes = [c_double, c_double]</p>
</blockquote>
<p>Whenever you call c functions from python always make sure the types you are inputting from python are correct, don't rely on casting like you would in c/c++</p>
| 1 | 2016-10-10T06:49:55Z | [
"python",
"python-c-extension"
] |
tf.image.decode_jpeg raise InvalidArgumentError | 39,952,592 | <p>I am testing tf.image.decode_jpeg and I got InvalidArgumentError.
I am using Python3, in order to let it act like Python2, I added encoding="latin-1"..</p>
<p>My Question:
How can I fix this problem? </p>
<pre><code>import tensorflow as tf
with open("/root/PycharmProjects/mscoco/train2014/COCO_train2014_000000291797.jpg", "r", encoding="latin-1") as f:
image = f.read()
sess = tf.Session()
result = sess.run(tf.image.decode_jpeg(image, channels=3))
</code></pre>
<p>This is the error.</p>
<pre><code>Not a JPEG file: starts with 0xc3 0xbf
Not a JPEG file: starts with 0xc3 0xbf
Traceback (most recent call last):
File "/usr/lib/python3.4/site-packages/tensorflow/python/client/session.py", line 965, in _do_call
return fn(*args)
File "/usr/lib/python3.4/site-packages/tensorflow/python/client/session.py", line 947, in _run_fn
status, run_metadata)
File "/usr/lib64/python3.4/contextlib.py", line 66, in __exit__
next(self.gen)
File "/usr/lib/python3.4/site-packages/tensorflow/python/framework/errors.py", line 450, in raise_exception_on_not_ok_status
pywrap_tensorflow.TF_GetCode(status))
tensorflow.python.framework.errors.InvalidArgumentError: Invalid JPEG data, size 165886
[[Node: DecodeJpeg = DecodeJpeg[acceptable_fraction=1, channels=0, fancy_upscaling=true, ratio=1, try_recover_truncated=false, _device="/job:localhost/replica:0/task:0/cpu:0"](DecodeJpeg/contents)]]
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/root/PycharmProjects/mytf/models/im2txt/im2txt/data/test.py", line 7, in <module>
result = sess.run(tf.image.decode_jpeg(image))
File "/usr/lib/python3.4/site-packages/tensorflow/python/client/session.py", line 710, in run
run_metadata_ptr)
File "/usr/lib/python3.4/site-packages/tensorflow/python/client/session.py", line 908, in _run
feed_dict_string, options, run_metadata)
File "/usr/lib/python3.4/site-packages/tensorflow/python/client/session.py", line 958, in _do_run
target_list, options, run_metadata)
File "/usr/lib/python3.4/site-packages/tensorflow/python/client/session.py", line 978, in _do_call
raise type(e)(node_def, op, message)
tensorflow.python.framework.errors.InvalidArgumentError: Invalid JPEG data, size 165886
[[Node: DecodeJpeg = DecodeJpeg[acceptable_fraction=1, channels=0, fancy_upscaling=true, ratio=1, try_recover_truncated=false, _device="/job:localhost/replica:0/task:0/cpu:0"](DecodeJpeg/contents)]]
Caused by op 'DecodeJpeg', defined at:
File "/root/PycharmProjects/mytf/models/im2txt/im2txt/data/test.py", line 7, in <module>
result = sess.run(tf.image.decode_jpeg(image))
File "/usr/lib/python3.4/site-packages/tensorflow/python/ops/gen_image_ops.py", line 283, in decode_jpeg
name=name)
File "/usr/lib/python3.4/site-packages/tensorflow/python/framework/op_def_library.py", line 703, in apply_op
op_def=op_def)
File "/usr/lib/python3.4/site-packages/tensorflow/python/framework/ops.py", line 2317, in create_op
original_op=self._default_original_op, op_def=op_def)
File "/usr/lib/python3.4/site-packages/tensorflow/python/framework/ops.py", line 1239, in __init__
self._traceback = _extract_stack()
Process finished with exit code 1
</code></pre>
<p>Thanks to Felix, I solved my problem by using <strong>tf.read_file</strong></p>
<p>I tried to rewrite this using placeholder:
And this is my code:</p>
<pre><code>import tensorflow as tf
path = "/root/PycharmProjects/mscoco/train2014/COCO_train2014_000000291797.jpg"
with open(path, "r", encoding="latin-1") as f:
image = f.read()
encoded_jpeg = tf.placeholder(dtype=tf.string)
decoded_jpeg = tf.image.decode_jpeg(encoded_jpeg, channels=3)
sess = tf.InteractiveSession()
sess.run(decoded_jpeg, feed_dict={encoded_jpeg: image})
</code></pre>
<p>And I got the error again, anyone can tell me how to fix it? This time, I cannot use tf.read_file() because I cannot feed a tensor to a tensor.</p>
<pre><code>Not a JPEG file: starts with 0xc3 0xbf
Traceback (most recent call last):
File "/usr/lib/python3.4/site-packages/tensorflow/python/client/session.py", line 965, in _do_call
return fn(*args)
File "/usr/lib/python3.4/site-packages/tensorflow/python/client/session.py", line 947, in _run_fn
status, run_metadata)
File "/usr/lib64/python3.4/contextlib.py", line 66, in __exit__
next(self.gen)
File "/usr/lib/python3.4/site-packages/tensorflow/python/framework/errors.py", line 450, in raise_exception_on_not_ok_status
pywrap_tensorflow.TF_GetCode(status))
tensorflow.python.framework.errors.InvalidArgumentError: Invalid JPEG data, size 165886
[[Node: DecodeJpeg = DecodeJpeg[acceptable_fraction=1, channels=3, fancy_upscaling=true, ratio=1, try_recover_truncated=false, _device="/job:localhost/replica:0/task:0/cpu:0"](_recv_Placeholder_0)]]
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/root/PycharmProjects/mytf/models/im2txt/im2txt/data/test.py", line 13, in <module>
sess.run(decoded_jpeg, feed_dict={encoded_jpeg: image})
File "/usr/lib/python3.4/site-packages/tensorflow/python/client/session.py", line 710, in run
run_metadata_ptr)
File "/usr/lib/python3.4/site-packages/tensorflow/python/client/session.py", line 908, in _run
feed_dict_string, options, run_metadata)
File "/usr/lib/python3.4/site-packages/tensorflow/python/client/session.py", line 958, in _do_run
target_list, options, run_metadata)
File "/usr/lib/python3.4/site-packages/tensorflow/python/client/session.py", line 978, in _do_call
raise type(e)(node_def, op, message)
tensorflow.python.framework.errors.InvalidArgumentError: Invalid JPEG data, size 165886
[[Node: DecodeJpeg = DecodeJpeg[acceptable_fraction=1, channels=3, fancy_upscaling=true, ratio=1, try_recover_truncated=false, _device="/job:localhost/replica:0/task:0/cpu:0"](_recv_Placeholder_0)]]
Caused by op 'DecodeJpeg', defined at:
File "/root/PycharmProjects/mytf/models/im2txt/im2txt/data/test.py", line 9, in <module>
decoded_jpeg = tf.image.decode_jpeg(encoded_jpeg, channels=3)
File "/usr/lib/python3.4/site-packages/tensorflow/python/ops/gen_image_ops.py", line 283, in decode_jpeg
name=name)
File "/usr/lib/python3.4/site-packages/tensorflow/python/framework/op_def_library.py", line 703, in apply_op
op_def=op_def)
File "/usr/lib/python3.4/site-packages/tensorflow/python/framework/ops.py", line 2317, in create_op
original_op=self._default_original_op, op_def=op_def)
File "/usr/lib/python3.4/site-packages/tensorflow/python/framework/ops.py", line 1239, in __init__
self._traceback = _extract_stack()
</code></pre>
| 0 | 2016-10-10T06:44:14Z | 39,955,190 | <p>The input to <code>decode_jpg</code> is a string Tensor with the file contents (see the <a href="https://www.tensorflow.org/versions/r0.11/api_docs/python/image.html#decode_jpeg" rel="nofollow">API</a> here), not the result of python's <code>read()</code>.</p>
<p>So, you should do something like this:</p>
<pre><code>file_contents = tf.read_file(filename)
image = tf.image.decode_jpeg(image, channels=3)
</code></pre>
| 1 | 2016-10-10T09:27:11Z | [
"python",
"tensorflow"
] |
Compare two list of dictionaries and create a new list with all keys and values in python | 39,952,634 | <pre><code>a = [{'a':{'a':1}}, {'b':{'b':1}}, {'c':{}}]
b = [{'a':{'a':1,'b':0}}, {'b':{'a':1}}]
</code></pre>
<p>Here I have two list of dict. I want to compare these and generate a new list like this:</p>
<pre><code>newlist = [{'a':{'a':1,'b':0}}, {'b':{'a':1,'b':1}}, {'c':{'a':0,'b':0}}]
</code></pre>
| 1 | 2016-10-10T06:47:52Z | 39,958,162 | <pre><code>A_list = [{'a':{'A':1}}, {'b':{}}]
B_list = [{'b': {'B': 1}}, {'a': {'A': 0}}]
list_with_all_keys = [{'a':{}}, {'b':{}}, {'c':{}}]
new_lod = [{k:{'A':(1 if k in A_list and 'A' in A_list[k] and A_list[k]['A'] is 1 else 0),
'B':(1 if k in B_list and 'B' in B_list[k] and B_list[k]['B'] is 1 else 0)}}
for k in [list(n.keys())[0] for n in list_with_all_keys]]
</code></pre>
<p><code>new_lod</code> is then <code>[{'a': {'B': 0, 'A': 0}}, {'b': {'B': 0, 'A': 0}}, {'c': {'B': 0, 'A': 0}}]</code></p>
<p>Note, that I added some upper-case letters, to clarify whats happening, it also work if you only use lower case letters <code>a</code>and <code>b</code> instead of <code>A</code>/<code>A_list</code> and <code>B</code>/<code>B_list</code> respectively.</p>
<p><strong>Sidenote</strong></p>
<p>I assume you do not get duplicate keys in the first level of dictionaries in the list. I think this is a correct assumption, since the required output would collapse these duplicate keys in the first level dictionaries. Thus you can skip the list and use one dictionary instead of a list of dictionaries. This slightly simplifies the expressions. But depending on your application there might be even better (speak easier) ways to compare or/and combine two lists, dictionaries or sets.</p>
<pre><code>A_dict = {'a':{'A':1}, 'b':{}}
B_dict = {'b': {'B': 1}, 'a': {'A': 0}}
dict_with_all_keys = {'a':{}, 'b':{}, 'c':{}}
# a dictionary solution with no list
new_dict = {k:{'A':(1 if k in A_dict and 'A' in A_dict[k] and A_dict[k]['A'] is 1 else 0),
'B':(1 if k in B_dict and 'B' in B_dict[k] and B_dict[k]['B'] is 1 else 0)}
for k in dict_with_all_keys}
</code></pre>
| 0 | 2016-10-10T12:19:48Z | [
"python",
"list",
"dictionary"
] |
Compare two list of dictionaries and create a new list with all keys and values in python | 39,952,634 | <pre><code>a = [{'a':{'a':1}}, {'b':{'b':1}}, {'c':{}}]
b = [{'a':{'a':1,'b':0}}, {'b':{'a':1}}]
</code></pre>
<p>Here I have two list of dict. I want to compare these and generate a new list like this:</p>
<pre><code>newlist = [{'a':{'a':1,'b':0}}, {'b':{'a':1,'b':1}}, {'c':{'a':0,'b':0}}]
</code></pre>
| 1 | 2016-10-10T06:47:52Z | 39,959,397 | <p>A more readable way of doing it would be </p>
<pre><code>a = [{'a':{'a':1}}, {'b':{'b':1}}, {'c':{}}]
b = [{'a':{'a':1,'b':0}}, {'b':{'a':1}}]
result = {}
for c in a + b:
for key,value in c.items():
result[key] = dict()
result[key]['a'] = value.get('a', 0)
result[key]['b'] = value.get('b', 0)
print(result)
</code></pre>
<p>Will give you answer<br>
<code>{'c': {'a': 0, 'b': 0}, 'a': {'a': 1, 'b': 0}, 'b': {'a': 1, 'b': 0}}</code></p>
| 0 | 2016-10-10T13:25:14Z | [
"python",
"list",
"dictionary"
] |
Should I put the main in a class in Python? | 39,952,675 | <p>So far I've running the <code>main()</code> module in a script way (different .py file and not in a class or whatever) and then call the different instances from my other modules.</p>
<p>Is this right or should I make a class just for the <code>main</code> too?</p>
<p>Regards and thank.</p>
| 0 | 2016-10-10T06:51:31Z | 39,952,785 | <p>You're overthinking it. Don't shoe-gaze over stuff that doesn't have a clear purpose. If you find a good reason to put a "main" function in a class, go ahead. Otherwise just save yourself the trouble.</p>
<p>To answer your question directly, I've never seen the "<code>main</code>" method defined in a <code>class</code> in python. The "main" function is usually just a driver for whatever you want to do with your program. It's something you want to execute every time your program is called. There's no general reason to represent this as an abstract data type, so I don't see the sense in encapsulating it in a class.</p>
<p>The python idiom I've seen most is to check <code>if __name__ == "__main__":</code>, which allows you to run a block of code only if the module is called directly, not as an <code>include</code> to another file. For example: </p>
<pre><code>if __name__ == "__main__":
print "This module was called directly."
</code></pre>
<p>You can see the question <a href="https://stackoverflow.com/questions/419163/what-does-if-name-main-do">What does <code>if __name__ == â__main__â:</code> do?</a> for more details.</p>
| 2 | 2016-10-10T07:00:22Z | [
"python"
] |
Should I put the main in a class in Python? | 39,952,675 | <p>So far I've running the <code>main()</code> module in a script way (different .py file and not in a class or whatever) and then call the different instances from my other modules.</p>
<p>Is this right or should I make a class just for the <code>main</code> too?</p>
<p>Regards and thank.</p>
| 0 | 2016-10-10T06:51:31Z | 39,952,942 | <p>If you don't know whether you need a new class then you should not write it.</p>
| 0 | 2016-10-10T07:11:36Z | [
"python"
] |
HDF5 min_itemsize error: ValueError: Trying to store a string with len [##] in [y] column but this column has a limit of [##]! | 39,952,715 | <p>I am getting the following error after using <code>pandas.HDFStore().append()</code></p>
<pre><code>ValueError: Trying to store a string with len [150] in [values_block_0] column but this column has a limit of [127]!
Consider using min_itemsize to preset the sizes on these columns
</code></pre>
<p>I am creating a pandas DataFrame and appending it to the HDF5 file as follows: </p>
<pre><code>import pandas as pd
store = pd.HDFStore("test1.h5", mode='w')
hdf_key = "one_key"
columns = ["col1", "col2", ... ]
df = pd.Dataframe(...)
df.col1 = df.col1.astype(str)
df.col2 = df.col2astype(int)
df.col3 = df.col3astype(str)
....
store.append(hdf_key, df, data_column=columns, index=False)
</code></pre>
<p>I get the error above: "ValueError: Trying to store a string with len [150] in [values_block_0] column but this column has a limit of [127]!"</p>
<p>Afterwards, I execute the code: </p>
<pre><code>store.get_storer(hdf_key).table.description
</code></pre>
<p>which outputs</p>
<pre><code>{
"index": Int64Col(shape=(), dflt=0, pos=0),
"values_block_0": StringCol(itemsize=127, shape=(5,), dflt=b'', pos=1),
"values_block_1": Int64Col(shape=(5,), dflt=0, pos=2),
"col1": StringCol(itemsize=20, shape=(), dflt=b'', pos=3),
"col2": StringCol(itemsize=39, shape=(), dflt=b'', pos=4)}
</code></pre>
<p>What are <code>values_block_0</code> and <code>values_block_1</code>? </p>
<p>So, following this StackOverflow <a href="http://stackoverflow.com/questions/22710738/pandas-pytable-how-to-specify-min-itemsize-of-the-elements-of-a-multiindex">Pandas pytable: how to specify min_itemsize of the elements of a MultiIndex</a> , I tried</p>
<pre><code>store.append(hdf_key, df, data_column=columns, index=False, min_itemsize={"values_block_0":250})
</code></pre>
<p>This doesn't work though---now I get this error: </p>
<pre><code>ValueError: Trying to store a string with len [250] in [values_block_0] column but this column has a limit of [127]!
Consider using min_itemsize to preset the sizes on these columns
</code></pre>
<p>What am I doing wrong?</p>
<p>EDIT: This code produces the error <code>ValueError: min_itemsize has the key [values_block_0] which is not an axis or data_column</code> from <code>filename.py</code></p>
<pre><code>import pandas as pd
store = pd.HDFStore("test1.h5", mode='w')
hdf_key = "one_key"
my_columns = ["col1", "col2", ... ]
df = pd.Dataframe(...)
df.col1 = df.col1.astype(str)
df.col2 = df.col2astype(int)
df.col3 = df.col3astype(str)
....
store.append(hdf_key, df, data_column=my_columns, index=False, min_itemsize={"values_block_0":350})
</code></pre>
<p>Here is the full error:</p>
<pre><code>(python-3) -bash:1008 $ python filename.py
Traceback (most recent call last):
File "filename.py", line 50, in <module>
store.append(hdf_key, dicts_into_df, data_column=my_columns, index=False, min_itemsize={'values_block_0':350})
File "/path/lib/python-3/lib/python3.5/site-packages/pandas/io/pytables.py", line 970, in append
**kwargs)
File "/path/lib/python-3/lib/python3.5/site-packages/pandas/io/pytables.py", line 1315, in _write_to_group
s.write(obj=value, append=append, complib=complib, **kwargs)
File "/path/lib/python-3/lib/python3.5/site-packages/pandas/io/pytables.py", line 4263, in write
obj=obj, data_columns=data_columns, **kwargs)
File "/path/lib/python-3/lib/python3.5/site-packages/pandas/io/pytables.py", line 3853, in write
**kwargs)
File "/path/lib/python-3/lib/python3.5/site-packages/pandas/io/pytables.py", line 3535, in create_axes
self.validate_min_itemsize(min_itemsize)
File "/path/lib/python-3/lib/python3.5/site-packages/pandas/io/pytables.py", line 3174, in validate_min_itemsize
"data_column" % k)
ValueError: min_itemsize has the key [values_block_0] which is not an axis or data_column
</code></pre>
| 0 | 2016-10-10T06:54:53Z | 39,954,996 | <p><strong>UPDATE:</strong></p>
<p>you have misspelled <code>data_columns</code> parameter: <code>data_column</code> - it should be <code>data_columns</code>. As a result you didn't have any indexed columns in your HDF Store and HDF store added <code>values_block_X</code>:</p>
<pre><code>In [70]: store = pd.HDFStore(r'D:\temp\.data\my_test.h5')
</code></pre>
<p>misspelled parameters will be ignored: </p>
<pre><code>In [71]: store.append('no_idx_wrong_dc', df, data_column=df.columns, index=False)
In [72]: store.get_storer('no_idx_wrong_dc').table
Out[72]:
/no_idx_wrong_dc/table (Table(10,)) ''
description := {
"index": Int64Col(shape=(), dflt=0, pos=0),
"values_block_0": Float64Col(shape=(1,), dflt=0.0, pos=1),
"values_block_1": Int64Col(shape=(1,), dflt=0, pos=2),
"values_block_2": StringCol(itemsize=30, shape=(1,), dflt=b'', pos=3)}
byteorder := 'little'
chunkshape := (1213,)
</code></pre>
<p>is the same as the following:</p>
<pre><code>In [73]: store.append('no_idx_no_dc', df, index=False)
In [74]: store.get_storer('no_idx_no_dc').table
Out[74]:
/no_idx_no_dc/table (Table(10,)) ''
description := {
"index": Int64Col(shape=(), dflt=0, pos=0),
"values_block_0": Float64Col(shape=(1,), dflt=0.0, pos=1),
"values_block_1": Int64Col(shape=(1,), dflt=0, pos=2),
"values_block_2": StringCol(itemsize=30, shape=(1,), dflt=b'', pos=3)}
byteorder := 'little'
chunkshape := (1213,)
</code></pre>
<p>let's spell it correctly:</p>
<pre><code>In [75]: store.append('no_idx_dc', df, data_columns=df.columns, index=False)
In [76]: store.get_storer('no_idx_dc').table
Out[76]:
/no_idx_dc/table (Table(10,)) ''
description := {
"index": Int64Col(shape=(), dflt=0, pos=0),
"value": Float64Col(shape=(), dflt=0.0, pos=1),
"count": Int64Col(shape=(), dflt=0, pos=2),
"s": StringCol(itemsize=30, shape=(), dflt=b'', pos=3)}
byteorder := 'little'
chunkshape := (1213,)
</code></pre>
<p><strong>OLD Answer:</strong></p>
<p>AFAIK you can <strong>effectively</strong> set the <code>min_itemsize</code> parameter <strong>on the first</strong> append only.</p>
<p>Demo:</p>
<pre><code>In [33]: df
Out[33]:
num s
0 11 aaaaaaaaaaaaaaaa
1 12 bbbbbbbbbbbbbb
2 13 ccccccccccccc
3 14 ddddddddddd
In [34]: store = pd.HDFStore(r'D:\temp\.data\my_test.h5')
In [35]: store.append('test_1', df, data_columns=True)
In [36]: store.get_storer('test_1').table.description
Out[36]:
{
"index": Int64Col(shape=(), dflt=0, pos=0),
"num": Int64Col(shape=(), dflt=0, pos=1),
"s": StringCol(itemsize=16, shape=(), dflt=b'', pos=2)}
In [37]: df.loc[4] = [15, 'X'*200]
In [38]: df
Out[38]:
num s
0 11 aaaaaaaaaaaaaaaa
1 12 bbbbbbbbbbbbbb
2 13 ccccccccccccc
3 14 ddddddddddd
4 15 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX...
In [39]: store.append('test_1', df, data_columns=True)
...
skipped
...
ValueError: Trying to store a string with len [200] in [s] column but
this column has a limit of [16]!
Consider using min_itemsize to preset the sizes on these columns
</code></pre>
<p>now using <code>min_itemsize</code>, but still appending to the existing <code>store</code> object:</p>
<pre><code>In [40]: store.append('test_1', df, data_columns=True, min_itemsize={'s':250})
...
skipped
...
ValueError: Trying to store a string with len [250] in [s] column but
this column has a limit of [16]!
Consider using min_itemsize to preset the sizes on these columns
</code></pre>
<p>The following works if we will create a new object in our <code>store</code>:</p>
<pre><code>In [41]: store.append('test_2', df, data_columns=True, min_itemsize={'s':250})
</code></pre>
<p>Check column sizes:</p>
<pre><code>In [42]: store.get_storer('test_2').table.description
Out[42]:
{
"index": Int64Col(shape=(), dflt=0, pos=0),
"num": Int64Col(shape=(), dflt=0, pos=1),
"s": StringCol(itemsize=250, shape=(), dflt=b'', pos=2)}
</code></pre>
| 1 | 2016-10-10T09:17:15Z | [
"python",
"pandas",
"hdf5",
"pytables",
"hdf5storage"
] |
Python Pandas - Group index by minute and compute average | 39,952,753 | <p>So I have a pandas dataframe called 'df' and I want to remove the seconds and just have the index in YYYY-MM-DD HH:MM format. But also the minutes are then grouped and the average for that minute is displayed.</p>
<p>So I want to turn this dataFrame</p>
<pre><code> value
2015-05-03 00:00:00 61.0
2015-05-03 00:00:10 60.0
2015-05-03 00:00:25 60.0
2015-05-03 00:00:30 61.0
2015-05-03 00:00:45 61.0
2015-05-03 00:01:00 61.0
2015-05-03 00:01:10 60.0
2015-05-03 00:01:25 60.0
2015-05-03 00:01:30 61.0
2015-05-03 00:01:45 61.0
2015-05-03 00:02:00 61.0
2015-05-03 00:02:10 60.0
2015-05-03 00:02:25 60.0
2015-05-03 00:02:40 60.0
2015-05-03 00:02:55 60.0
2015-05-03 00:03:00 59.0
2015-05-03 00:03:15 59.0
2015-05-03 00:03:20 59.0
2015-05-03 00:03:35 59.0
2015-05-03 00:03:40 60.0
</code></pre>
<p>into this dataFrame</p>
<pre><code> value
2015-05-03 00:00 60.6
2015-05-03 00:01 60.6
2015-05-03 00:02 60.2
2015-05-03 00:03 59.2
</code></pre>
<p>ive tried code like</p>
<pre><code>df['value'].resample('1Min').mean()
</code></pre>
<p>or </p>
<pre><code>df.index.resample('1Min').mean()
</code></pre>
<p>but this does not seem to work. Any ideas?</p>
| 1 | 2016-10-10T06:58:05Z | 39,952,846 | <p>You need first convert index to <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DatetimeIndex.html" rel="nofollow"><code>DatetimeIndex</code></a>:</p>
<pre><code>df.index = pd.DatetimeIndex(df.index)
#another solution
#df.index = pd.to_datetime(df.index)
print (df['value'].resample('1Min').mean())
#another same solution
#print (df.resample('1Min')['value'].mean())
2015-05-03 00:00:00 60.6
2015-05-03 00:01:00 60.6
2015-05-03 00:02:00 60.2
2015-05-03 00:03:00 59.2
Freq: T, Name: value, dtype: float64
</code></pre>
<p>Another solution with seting values of seconds in index to <code>0</code> by <code>astype</code>:</p>
<pre><code>print (df.groupby([df.index.values.astype('<M8[m]')])['value'].mean())
2015-05-03 00:00:00 60.6
2015-05-03 00:01:00 60.6
2015-05-03 00:02:00 60.2
2015-05-03 00:03:00 59.2
Name: value, dtype: float64
</code></pre>
| 1 | 2016-10-10T07:05:21Z | [
"python",
"pandas",
"group",
"average",
"minute"
] |
How to run functions in random order? | 39,952,782 | <p>I want to run functions with random order. It looks like "shuffle" function which shuffle a variables list.</p>
<p>Input:</p>
<pre><code>def a():
print('a')
def b():
print('b')
def c():
print('c')
shuffle([a,b,c])
</code></pre>
<p>This is output what I want:</p>
<pre><code>a
b
c
</code></pre>
<p>or</p>
<pre><code>a
c
b
</code></pre>
<p>or </p>
<pre><code>c
b
a
</code></pre>
<p>or etc
How to run functions with random order?</p>
| 1 | 2016-10-10T07:00:10Z | 39,952,856 | <p><a href="https://docs.python.org/3/library/random.html#random.shuffle" rel="nofollow"><code>random.shuffle</code></a> is an in-place operation. So you need to keep the list separately and shuffle it.</p>
<pre><code>functions = [a, b, c]
shuffle(functions)
</code></pre>
<p>Now, the functions are shuffled and you just have to execute them</p>
<pre><code>for func in functions:
func()
</code></pre>
<hr>
<p>You can probably store this in a function and do it like this</p>
<pre><code>def run_functions_in_random_order(*funcs):
functions = list(funcs)
shuffle(functions)
for func in functions:
func()
run_functions_in_random_order(a, b, c)
</code></pre>
<hr>
<p>Or you can simply use the functions in closures, like this</p>
<pre><code>def run_functions_in_random_order(*funcs):
def run():
functions = list(funcs)
shuffle(functions)
for func in functions:
func()
return run
random_exec = run_functions_in_random_order(a, b, c)
random_exec()
random_exec()
random_exec()
</code></pre>
| 5 | 2016-10-10T07:05:54Z | [
"python",
"function",
"python-3.x",
"random"
] |
How to run functions in random order? | 39,952,782 | <p>I want to run functions with random order. It looks like "shuffle" function which shuffle a variables list.</p>
<p>Input:</p>
<pre><code>def a():
print('a')
def b():
print('b')
def c():
print('c')
shuffle([a,b,c])
</code></pre>
<p>This is output what I want:</p>
<pre><code>a
b
c
</code></pre>
<p>or</p>
<pre><code>a
c
b
</code></pre>
<p>or </p>
<pre><code>c
b
a
</code></pre>
<p>or etc
How to run functions with random order?</p>
| 1 | 2016-10-10T07:00:10Z | 39,952,990 | <p>Or make a list and take random: </p>
<pre><code>import random
def a():
print('a')
def b():
print('b')
def c():
print('c')
my_list = [a, b, c]
random.choice(my_list)()
</code></pre>
| 1 | 2016-10-10T07:14:22Z | [
"python",
"function",
"python-3.x",
"random"
] |
How to run functions in random order? | 39,952,782 | <p>I want to run functions with random order. It looks like "shuffle" function which shuffle a variables list.</p>
<p>Input:</p>
<pre><code>def a():
print('a')
def b():
print('b')
def c():
print('c')
shuffle([a,b,c])
</code></pre>
<p>This is output what I want:</p>
<pre><code>a
b
c
</code></pre>
<p>or</p>
<pre><code>a
c
b
</code></pre>
<p>or </p>
<pre><code>c
b
a
</code></pre>
<p>or etc
How to run functions with random order?</p>
| 1 | 2016-10-10T07:00:10Z | 39,952,997 | <pre><code>import random
def a():
print('a')
def b():
print('b')
def c():
print('c')
# map the inputs to the function blocks
options = {0 : a,
1 : b,
2 : c,
}
num = random.randint(0, 2)
options[num]()
</code></pre>
<p>That's a simple way to randomly choose the functions</p>
| -1 | 2016-10-10T07:14:54Z | [
"python",
"function",
"python-3.x",
"random"
] |
How to run functions in random order? | 39,952,782 | <p>I want to run functions with random order. It looks like "shuffle" function which shuffle a variables list.</p>
<p>Input:</p>
<pre><code>def a():
print('a')
def b():
print('b')
def c():
print('c')
shuffle([a,b,c])
</code></pre>
<p>This is output what I want:</p>
<pre><code>a
b
c
</code></pre>
<p>or</p>
<pre><code>a
c
b
</code></pre>
<p>or </p>
<pre><code>c
b
a
</code></pre>
<p>or etc
How to run functions with random order?</p>
| 1 | 2016-10-10T07:00:10Z | 39,953,439 | <p>Here is how I would do. Basically what <strong>thefourtheye</strong> has suggested. <a href="https://repl.it/DsMk/0" rel="nofollow">Run this Code</a></p>
<pre><code>from random import shuffle
def a():
print('a')
def b():
print('b')
def c():
print('c')
def main():
lis = [a,b,c]
shuffle(lis)
for i in lis:
i()
</code></pre>
| 1 | 2016-10-10T07:43:48Z | [
"python",
"function",
"python-3.x",
"random"
] |
Python 3.5 async/await with real code example | 39,952,799 | <p>I've read tons of articles and tutorial about Python's 3.5 async/await thing. I have to say I'm pretty confused because some use get_event_loop() and run_until_complete() some use ensure_future() some use asyncio.wait() and some use call_soon().</p>
<p>It seems like I have a lot choices but I have no idea if they are completely identical or there are cases where you use loops and there are cases where you use wait().</p>
<p>But the thing is all examples work with <code>asyncio.sleep()</code> as simulation of real slow operation which returns awaitable object. Once I try to swap this line for some real code whole thing fails. So my question is what the heck are differences between approaches written above and how should I run 3rd party library which is not ready for async/await. I do use Quandl service to fetch some stock data.</p>
<pre><code> import asyncio
import quandl
async def slow_operation(n):
# await asyncio.sleep(1) # Works because it's await ready.
await quandl.Dataset(n) # Doesn't work because it's not await ready.
async def main():
await asyncio.wait([
slow_operation("SIX/US9884981013EUR4"),
slow_operation("SIX/US88160R1014EUR4"),
])
# You don't have to use any code for 50 requests/day.
quandl.ApiConfig.api_key = "MY_SECRET_CODE"
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
</code></pre>
<p>Hope you get the point how lost I feel and how simple thing I would like to have running in paralel.</p>
<p>Thank you.</p>
| 0 | 2016-10-10T07:01:42Z | 39,953,219 | <p>If 3rd party library is not compatible with <code>async/await</code> then obviously you can't use it easily. There are 2 cases:</p>
<p>1) Let's say that the function in the library is asynchronous and it gives you a callback, e.g.</p>
<pre><code>def fn(..., clb):
...
</code></pre>
<p>So you can do:</p>
<pre><code>def on_result(...):
...
fn(..., on_result)
</code></pre>
<p>In that case you can wrap such function into asyncio protocol like this:</p>
<pre><code>from asyncio import Future
def wrapper(...):
future = Future()
def my_clb(...):
future.set_result(xyz)
fn(..., my_clb)
return future
</code></pre>
<p>(use <code>future.set_exception(exc)</code> on exception)</p>
<p>Then you can simply call that wrapper in some <code>async</code> function with <code>await</code>:</p>
<pre><code>value = await wrapper(...)
</code></pre>
<p>Note that <code>await</code> works with any <code>Future</code> object, you don't have to declare <code>wrapper</code> as <code>async</code>.</p>
<p>2) If the function in the library is synchronous then you can run it in a separate thread (probably you would use some thread pool for that). The whole code may look like this:</p>
<pre><code>import asyncio
import time
from concurrent.futures import ThreadPoolExecutor
# Initialize 10 threads
THREAD_POOL = ThreadPoolExecutor(10)
def synchronous_handler(param1, ...):
# do something synchronous
time.sleep(2)
return "foo"
# somewhere else
async def main():
loop = asyncio.get_event_loop()
futures = [
loop.run_in_executor(THREAD_POOL, synchronous_handler, param1, ...),
loop.run_in_executor(THREAD_POOL, synchronous_handler, param1, ...),
loop.run_in_executor(THREAD_POOL, synchronous_handler, param1, ...),
]
await asyncio.wait(futures)
for future in futures:
print(future.result())
with THREAD_POOL:
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
</code></pre>
<p>If you can't use threads for whatever reason then using such library simply makes entire asynchronous code pointless.</p>
<p>Note however that using synchronous library with async is probably a bad idea. You won't get much and yet you complicate the code alot.</p>
| 1 | 2016-10-10T07:28:41Z | [
"python",
"asynchronous",
"async-await",
"python-3.5"
] |
How to know the folder size in a zipfile (Python) | 39,952,867 | <p>I know that you can get the size in bytes of a file in a ZIP file using the .file_size method
But is there any what I can get the size of a folder instead?</p>
<p>Ex: </p>
<pre><code>import zipfile, os
os.chdir('C:\\')
zp= zipfile.ZipFile('example.zip')
spamInfo = zp.getinfo('spam.txt') #Here, Instead of a file I'd like to put a folder
spamInfo.file_size
zp.close()
</code></pre>
<p>Any help would be greatly appreciated.</p>
| 1 | 2016-10-10T07:06:21Z | 39,953,116 | <p>Just put below code into your program.</p>
<pre><code>size = sum([zinfo.file_size for zinfo in zp.filelist])
zip_kb = float(size)/1000 #kB
</code></pre>
<p>Hopefully, It will work for you. :)</p>
| 3 | 2016-10-10T07:22:45Z | [
"python",
"size",
"folder",
"zipfile"
] |
Win32: Python to get all Column Names from Excel | 39,952,931 | <p>How can I get all defined names from a Excel Worksheet using the COM-interface, i.e. Win32 API in Python?</p>
<p>I want to obtain some sort of a dict, e.g. in the example below it would be:</p>
<pre><code>cols['Stamm_ISIN'] = 2
</code></pre>
<p>so that I could access the column later using it's ID 2 to set some values: <code>excel.Cells(row, cols['Stamm_ISIN']).Value = 'x'</code></p>
<p>I'm somewhat stuck at the API documentation <a href="https://msdn.microsoft.com/en-us/library/office/ff841280.aspx" rel="nofollow">https://msdn.microsoft.com/en-us/library/office/ff841280.aspx</a> so it seems to somehow be possible... Any moreover I couldn't find any result when googeling :(</p>
<p><a href="http://i.stack.imgur.com/pjQ2d.png" rel="nofollow"><img src="http://i.stack.imgur.com/pjQ2d.png" alt="enter image description here"></a></p>
| 0 | 2016-10-10T07:10:57Z | 39,956,132 | <p>The following script shows you how to display all of the column headings for a given WorkSheet. First it calculates the number of columns used and then enumerates each column. Next it displays all of the named ranges for a given WorkBook, for each it stores the instance into the <code>cols</code> dictionary. This can then be used in conjunction with <code>Range()</code> to set all cells in a given named range to a given value:</p>
<pre><code>import win32com.client as win32
excel = win32.gencache.EnsureDispatch('Excel.Application')
wb = excel.Workbooks.Open(r"test file.xlsx")
ws = wb.Worksheets("Sheet1")
cols = {} # Dictionary holding named range objects
# Determine the number of columns used in the top row
xlToLeft = -4159
col_count = ws.Cells(1, ws.Columns.Count).End(xlToLeft).Column
# Print each column heading
for col in range(1, col_count + 1):
print "Col {}, {}".format(col, ws.Cells(1, col).Value)
# Enumerate all named ranges in the Workbook
for index in range(1, wb.Names.Count + 1):
print "Workbook: ", wb.Names(index).Name, wb.Names(index).Value
cols[wb.Names(index).Name] = wb.Names(index)
# Enumerate any named ranges in the current Worksheet
for index in range(1, ws.Names.Count + 1):
print "Sheet: ", ws.Names(index).Name, ws.Names(index).Value
# Change all cells for a named range called "TestRange" to "TEST"
ws.Range(cols["TestRange"]).Value = "TEST"
# Save the changes
wb.Save()
excel.Application.Quit()
</code></pre>
<p>In this example, your Excel file would need to have a named range called <code>TestRange</code>.</p>
| 1 | 2016-10-10T10:23:42Z | [
"python",
"excel",
"winapi",
"com"
] |
How do I create lists out of dictionary, having same name as dictionary keys and same size as value of that key? | 39,952,982 | <p>In Python, Suppose there is a dictionary named fruits:</p>
<pre><code>fruits={
"apple":5,
"orange":7,
"mango":9
}
</code></pre>
<p>On reading the dictionary items, it should create 3 lists having same name as dictionary keys viz. apple, orange and mango and size of theses lists should be 5, 7 and 9 respectively.
The elements of these lists should be given from the user through console.</p>
| -2 | 2016-10-10T07:14:08Z | 39,953,203 | <pre><code>d = { "apple":5, "orange":7, "mango":9 }
for k in d:
temp = []
for k2 in range(0,d[k]):
print "enter the next "+str(k)+":"
temp.append(raw_input())
exec(str(k)+"="+str(temp))
</code></pre>
<p>but don't.
<a href="http://stackoverflow.com/questions/8818318/how-to-eval-a-string-containing-an-equal-symbol">How to eval a string containing an equal symbol?</a></p>
| 0 | 2016-10-10T07:27:24Z | [
"python",
"list",
"python-3.x",
"dictionary"
] |
How do I create lists out of dictionary, having same name as dictionary keys and same size as value of that key? | 39,952,982 | <p>In Python, Suppose there is a dictionary named fruits:</p>
<pre><code>fruits={
"apple":5,
"orange":7,
"mango":9
}
</code></pre>
<p>On reading the dictionary items, it should create 3 lists having same name as dictionary keys viz. apple, orange and mango and size of theses lists should be 5, 7 and 9 respectively.
The elements of these lists should be given from the user through console.</p>
| -2 | 2016-10-10T07:14:08Z | 39,954,428 | <p>Got a solution for this-</p>
<pre><code>fruit = {
"apple": 5,
"banana" : 10
}
for key in fruit.items():
key = list(fruit.get(key)*[None])
</code></pre>
<p>This will serve my need.</p>
| 3 | 2016-10-10T08:43:31Z | [
"python",
"list",
"python-3.x",
"dictionary"
] |
Python Pandas: select column with the number of unique values greater than 10 | 39,953,068 | <p>In R, we can use <code>sapply</code> to extract columns with the number of unique values greater than 10 by:</p>
<pre><code>X[, sapply(X, function(x) length(unique(x))) >=10]
</code></pre>
<p>How can we do the same thing in Python Pandas?</p>
<p>Also, how can we choose columns with missing proportion less than 10% like what we can do in R:</p>
<pre><code>X[, sapply(X, function(x) sum(is.na(x))/length(x) ) < 0.1]
</code></pre>
<p>Thanks.</p>
| 1 | 2016-10-10T07:19:27Z | 39,953,117 | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.nunique.html" rel="nofollow"><code>nunique</code></a> with <code>apply</code>, because it works only with <code>Series</code>:</p>
<pre><code>print (df.ix[:, df.apply(lambda x: x.nunique()) >= 10])
</code></pre>
<p>and second <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.isnull.html" rel="nofollow"><code>isnull</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.mean.html" rel="nofollow"><code>mean</code></a>:</p>
<pre><code>print (df.ix[:, df.isnull().mean() < 0.1])
</code></pre>
<p>Sample:</p>
<pre><code>df = pd.DataFrame({'A':[1,np.nan,3],
'B':[4,4,np.nan],
'C':[7,8,9],
'D':[3,3,5]})
print (df)
A B C D
0 1.0 4.0 7 3
1 NaN 4.0 8 3
2 3.0 NaN 9 5
</code></pre>
<pre><code>print (df.ix[:, df.apply(lambda x: x.nunique()) >= 2])
A C D
0 1.0 7 3
1 NaN 8 3
2 3.0 9 5
print (df.isnull().sum())
A 1
B 1
C 0
D 0
dtype: int64
print (df.isnull().sum() / len(df.index))
A 0.333333
B 0.333333
C 0.000000
D 0.000000
dtype: float64
print (df.isnull().mean())
A 0.333333
B 0.333333
C 0.000000
D 0.000000
dtype: float64
print (df.ix[:, df.isnull().sum() / len(df.index) < 0.1])
C D
0 7 3
1 8 3
2 9 5
</code></pre>
<p>Or:</p>
<pre><code>print (df.ix[:, df.isnull().mean() < 0.1])
C D
0 7 3
1 8 3
2 9 5
</code></pre>
| 3 | 2016-10-10T07:22:50Z | [
"python",
"pandas",
"sapply"
] |
split long string inside one list to small lists | 39,953,075 | <p>How do you split this long string of one list to small multi-lists as show on the output ? (I have file has 100 lines)</p>
<pre><code>Num=['S', 'I', 'R', 'T', 'S', 'A', 'V', 'P', 'S', 'P', 'C', 'G', 'K', 'Y', 'Y', 'T', 'L', 'N', 'G', 'S', 'K', '\n', ',', 'S', 'T', 'P', 'C', 'T', 'T', 'I', 'N', 'K', 'V', 'K', 'A', 'S', 'G', 'M', 'K', 'A', 'I', 'M', 'M', 'A', '\n']
</code></pre>
<p>Output should look like this:</p>
<pre><code>['S', 'I', 'R', 'T', 'S', 'A', 'V', 'P', 'S', 'P', 'K', 'G', 'K', 'Y', 'Y', 'T', 'L', 'N', 'G', 'S', 'K']
['S', 'T', 'P', 'C', 'T', 'T', 'I', 'N', 'K', 'V', 'K', 'A', 'S', 'G', 'M', 'K', 'A', 'I', 'M', 'M', 'A']
</code></pre>
| -1 | 2016-10-10T07:20:07Z | 39,953,135 | <p>First <code>join</code> the elements, <code>strip()</code> leading-trailing whitespace characters, <code>split</code> on a new line <code>\n</code> and comma <code>,</code> and then map them to a list again.</p>
<p>In short:</p>
<pre><code>l1, l2 = map(list, "".join(Num).strip().split('\n,'))
</code></pre>
<p>Now, <code>l1, l2</code> look, respectively:</p>
<pre><code>['S', 'I', 'R', 'T', 'S', 'A', 'V', 'P', 'S', 'P', 'C', 'G', 'K', 'Y', 'Y', 'T', 'L', 'N', 'G', 'S', 'K']
</code></pre>
<p>and</p>
<pre><code>['S', 'T', 'P', 'C', 'T', 'T', 'I', 'N', 'K', 'V', 'K', 'A', 'S', 'G', 'M', 'K', 'A', 'I', 'M', 'M', 'A']
</code></pre>
| 1 | 2016-10-10T07:24:01Z | [
"python",
"string",
"python-2.7",
"python-3.x"
] |
Clustering words on the basis of similarity in meaning which is provided in trainings set | 39,953,134 | <p>Which machine learning algorithm would serve to starting point for the below problem ?</p>
<p>I have a list of words which is similar to the below.</p>
<p><strong>curate</strong> : a member of the clergy in certain churches (such as the Anglican church) who assists the priest in charge of a church or a group of churches</p>
<p><strong>yardman</strong>: a person employed to do outdoor work (as mowing lawns)</p>
<p>and other normal words.</p>
<p>what i want to is decide that new word belongs to our category(job title) or not based on their meaning.</p>
<p>For example:</p>
<ul>
<li>nurse: 1</li>
<li>teacher:1</li>
<li>swimming:0</li>
<li>swimmer:1</li>
<li>facilitator:1</li>
<li>playing:0</li>
</ul>
<blockquote>
<ul>
<li>1-fit into our category</li>
<li>2-does not fit into category.</li>
</ul>
</blockquote>
<p>i am using python as tool for implementation machine learning purpose.</p>
| 0 | 2016-10-10T07:23:52Z | 39,963,454 | <p>This is a problem of text similarity, where you want to match the similarity of a given block of text to a known set. For example, "nurse: a person working healthcare...". If the similarity is above a certain threshold, then there is a match, otherwise it is considered to not be a match.</p>
<p>To start, you will need some sort of representation for the text, so that you can perform the comparison. Some common text representations are:</p>
<ul>
<li>Bag of Words / Word counts (see <a href="http://scikit-learn.org/stable/modules/feature_extraction.html" rel="nofollow">TF-IDF</a>)</li>
<li>Word embeddings (see <a href="https://radimrehurek.com/gensim/models/word2vec.html" rel="nofollow">Word2Vec</a>)</li>
</ul>
<p>With TF-IDF, the sentences for each job description are converted into a vector of counts, with the length of the vector being equal to the size of the vocabulary for all words in all job descriptions. With Word2Vec, each word is treated as a vector of a defined size that represents the word's context in the training corpus. You can either trading your own Word2Vec model on your data or use a <a href="https://github.com/3Top/word2vec-api/blob/master/README.md" rel="nofollow">pretrained model</a>. You will need to combine the vectors for each sentence yourself to make the job descriptions comparable. An easy first step is to average all of the word vectors, but you can also try Doc2Vec (See <a href="https://radimrehurek.com/gensim/models/doc2vec.html" rel="nofollow">here</a>).</p>
<p>Lastly, you will need a distance function to compare the two representations. For TF-IDF, <a href="https://en.m.wikipedia.org/wiki/Cosine_similarity" rel="nofollow">cosine similarity</a> is a fairly standard one. For Word2Vec, you can use <a href="https://en.m.wikipedia.org/wiki/Euclidean_distance" rel="nofollow">euclidean distance</a> or even the word mover's distance (WMD see <a href="https://radimrehurek.com/gensim/models/doc2vec.html" rel="nofollow">here</a> again) </p>
<p>Putting it all together at a high level, you will want to do something like the following:</p>
<pre><code>trainingWords = {}
trainingWords['gardener'] = 'a person who tends a garden...'
trainingWords['valet'] = 'A person who parks a car...'
trainingVectors = {}
for (category in trainingWords):
trainingVectors[category] = convert(trainingWords[category])
newWord = 'nurse'
newDescription = 'A person working in healthcare...'
newVector = convert(newDescription)
threshold = <some number>
output = {}
for (category in trainingVectors):
if (distance(newVector, trainingVector[category]) < threshold):
output[category] = 1
else:
output[category] = 0
print output
</code></pre>
<p>This assumes that you have a function convert that converts raw text into one of the reorientation mentioned earlier, a function distance that users s distance function mentioned earlier, and a threshold appropriate to your problem and distance function. For example, cosine similarity uses values in the range of 0 to 1, so you'd need to pick a threshold for what is considered a match (ex. 0.85).</p>
| 0 | 2016-10-10T17:14:44Z | [
"python",
"python-3.x",
"machine-learning",
"cluster-analysis",
"word"
] |
Can variables have synonyms? | 39,953,156 | <p>I have very big string, which give me access to my dictionary in another dictionary in another class.</p>
<pre><code>self.app_data.ip_table[self.app_data.cfg.MY_IP]['tasks']
</code></pre>
<p>If I used this dict in sequence of strings, I can write something like this (I think so):</p>
<pre><code>with self.app_data:
...
</code></pre>
<p>But I use this variable in different lines in all file, I can't use <code>with</code> instruction. Than I think, in C++ we can use something like <code>#define VAR very.long.access.path.to.variable</code>.</p>
<p>Is there something like that in python? Can I shorter variable access name?</p>
<p>P.S.
That long-access-name variable changes with other thread. I don't need just assigned it to another variable. I'm looking for text-shorter for code</p>
| -1 | 2016-10-10T07:25:20Z | 39,953,428 | <p>Use properties maybe?</p>
<pre><code>class C:
def __init__(self, ...):
self.app_data = get_app_data()
@property
def var(self):
return self.app_data.very['long'].path.here
@var.setter
def var(self, value):
self.app_data.very['long'].path.here = value
c = C()
print c.var
c.var = 1337
</code></pre>
<p>Also you can create <code>var_threadsafe</code> property with a mutex inside if you expect this data to be read/written in multiple threads.</p>
| 1 | 2016-10-10T07:42:51Z | [
"python",
"python-2.7",
"variables",
"dictionary"
] |
How to call codes of a package directly without installing and importing module? | 39,953,159 | <p>Sorry I am a newbie. I have a python package created with one of my colleagues which is not available currently. Now I have to make small changes to module. I don't want to install the module. I want to just call the codes directly. Is there any way to copy files in the same folder and call it directly? </p>
<p>How can I use code of the package with minimal changes in it? </p>
| -4 | 2016-10-10T07:25:30Z | 39,972,235 | <p>If you want to use anything defined within another file, you will have to <code>import</code> it.</p>
<p>To be able to <code>import</code> a module, you do <em>not</em> have to install it into the system-wide package directory. Python will look up modules you're trying to <code>import</code> on the <code>PYTHONPATH</code> environment variable; simply set that to the directory where you have the file:</p>
<pre><code>myproject/
foo.py
bar.py
</code></pre>
<p><em>foo.py:</em></p>
<pre><code>import bar
bar.baz()
</code></pre>
<pre><code>$ export PYTHONPATH=myproject
$ python myproject/foo.py
</code></pre>
<p>This enables Python to find <code>bar</code> in the directory <code>myproject</code>, outside the system-wide module installation directory.</p>
<p>You can also set up an isolated environment using <a href="http://virtualenv.pypa.io" rel="nofollow">virtualenv</a> and install the module there, which will take care of dependencies if it has any.</p>
| 1 | 2016-10-11T07:23:06Z | [
"python",
"python-3.x"
] |
How can I alter the index of loop for a list | 39,953,254 | <p>I've a list and I want to display the content with index by manually changing the value of index. I've tried to do it in two ways but it is not working.</p>
<p>way 1:</p>
<pre><code>x=['hello','how','are','you','hope','you','are','fine','I','am','doing','work','in','python']
for i,item in enumerate(x):
print (i,item)
if item == 'are':
i+=2
</code></pre>
<p>way 2:</p>
<pre><code>x=['hello','how','are','you','hope','you','are','fine','I','am','doing','work','in','python']
for i in xrange(len(x)):
print x[i]
if item == 'are':
i+=2
</code></pre>
| -1 | 2016-10-10T07:30:18Z | 39,953,496 | <p>The issue here is that both <code>enumerate()</code> and <code>xrange()</code> generate a series of values that is unaffected by external changes to <code>i</code>, which is an unconnected variable. Using @efferalgans's suggestion the best way might be to call the <code>next()</code> function twice, but this will mean storing a reference to the generator. So you want to do something like this:</p>
<pre><code>x=['hello','how','are','you','hope','you','are','fine','I','am','doing','work','in','python']
g = enumerate(x)
for i,item in g:
print (i,item)
if item == 'are':
next(g)
next(g)
</code></pre>
<p>from which I see the result</p>
<pre><code>0 hello
1 how
2 are
5 you
6 are
9 am
10 doing
11 work
12 in
13 python
</code></pre>
| 1 | 2016-10-10T07:46:56Z | [
"python",
"python-2.7",
"nltk"
] |
How can I alter the index of loop for a list | 39,953,254 | <p>I've a list and I want to display the content with index by manually changing the value of index. I've tried to do it in two ways but it is not working.</p>
<p>way 1:</p>
<pre><code>x=['hello','how','are','you','hope','you','are','fine','I','am','doing','work','in','python']
for i,item in enumerate(x):
print (i,item)
if item == 'are':
i+=2
</code></pre>
<p>way 2:</p>
<pre><code>x=['hello','how','are','you','hope','you','are','fine','I','am','doing','work','in','python']
for i in xrange(len(x)):
print x[i]
if item == 'are':
i+=2
</code></pre>
| -1 | 2016-10-10T07:30:18Z | 39,954,192 | <p>Just use a while loop. It's the simplest, clearest and most flexible solution:</p>
<pre><code>i = 0
while i < len(x):
print x[i]
if x[i] == 'are':
i+=1
i += 1
</code></pre>
<p>As you can see, looping over a string is simple and you are completely free to change the index on the fly -- <code>i</code> is just a normal variable. It's not clear what your code was actually meant to do, so the above does what your code would (presumably) have done if it worked: It will skip the word that <em>follows</em> the word "are".</p>
| 1 | 2016-10-10T08:29:14Z | [
"python",
"python-2.7",
"nltk"
] |
Get video dimension in python-opencv | 39,953,263 | <p>I can get size of image, like this:</p>
<pre><code>import cv2
img = cv2.imread('my_image.jpg',0)
height, width = img.shape[:2]
</code></pre>
<p>How about video?</p>
| 0 | 2016-10-10T07:30:52Z | 39,953,739 | <p>It gives <code>width</code> and <code>height</code> of file or camera as float (so you may have to convert to integer)</p>
<p>But it always gives me <code>0.0 FPS</code>.</p>
<pre><code>import cv2
vcap = cv2.VideoCapture('video.avi') # 0=camera
if vcap.isOpened():
# get vcap property
width = vcap.get(cv2.cv.CV_CAP_PROP_FRAME_WIDTH) # float
height = vcap.get(cv2.cv.CV_CAP_PROP_FRAME_HEIGHT) # float
# or
width = vcap.get(3) # float
height = vcap.get(4) # float
# it gives me 0.0 :/
fps = vcap.get(cv2.cv.CV_CAP_PROP_FPS)
</code></pre>
<hr>
<p>It seems it can works <code>fps = vcap.get(7)</code> but I checked this only on one file.</p>
| 1 | 2016-10-10T08:01:14Z | [
"python",
"opencv",
"video"
] |
I can't remove file, created by memmap | 39,953,501 | <p>I can't remove file created <code>numpy.memmap</code> funtion</p>
<pre><code>class MyClass
def __init__(self):
self.fp = np.memmap(filename, dtype='float32', mode='w+', shape=flushed_chunk_shape)
...
def __del__(self):
del self.fp
os.remove(filename)
</code></pre>
<p>When I run <code>del myclass</code> (instanse of MyClass) I've got error <code>WindowsError: [Error 32] The process cannot access the file</code>. If I use <code>memmap</code> and deleting the file in no objected oriented way everything ok. So I consider trouble in destructor. But why it happens?</p>
| 0 | 2016-10-10T07:47:10Z | 39,954,126 | <p>Numpy memmapped files are not unmapped until garbage collected, and <code>del self.fp</code> does not ensure garbage collection. A file which is not unmapped yet cannot be deleted.</p>
<p>The numpy.memmap docs say "Deletion flushes memory changes to disk". It does not say it unmaps, because it doesn't unmap.</p>
<p>Solution 1. Force garbage collection </p>
<pre><code>import gc
...
del self.fp
gc.collect()
os.remove(filename)
</code></pre>
<p>You need to make sure there are no other references to fp anywhere, or it may not be garbage collected even in this case.</p>
<p>Solution 2. Force unmap</p>
<pre><code>self.fp._mmap.close()
del self.fp
os.remove(filename)
</code></pre>
<p>Note that in the second case, if there is an access to fp after it's closed, it will probably crash the python interpreter (not throw exception, just crash)</p>
| 0 | 2016-10-10T08:26:05Z | [
"python",
"numpy",
"numpy-memmap"
] |
Updating an ordered list of dicts from a new list of dicts (priority merge) | 39,953,539 | <p>I'm currently faced with having to semi-regularly update (synchronize) a large-ish list of dicts from a canonical changing source while maintaining my own updates to it. A non-standard merge, for which the simplest description is probably:-</p>
<ul>
<li><code>A</code> is my own list of dicts (updated by my program to include cached values as additional keys.</li>
<li><code>b</code> is some regularly sent information from a source (A was originally identical to b). It contains a few keys, but not the cached values I've added to A.</li>
<li><code>keys = ['key1', 'key2']</code> is a list of keys which both A and b have (A has more keys than that.</li>
<li><code>mkey = 'mtime'</code> is a special key which both A and b have which indicates that I should invalidate the cached values of A.</li>
</ul>
<p>Basically, if a dict in <code>A</code> matches a dict in <code>b</code>, I should keep the dict in A unless <code>b['mtime'] > A['mtime']</code>. If a dict appears in <code>A</code> but not in <code>b</code> I get rid of it, while if it appears in <code>b</code> but not in <code>A</code> I add it to <code>A</code>.</p>
<p>My holy grail objective is to not lose any cached key-value pairs in <code>A</code> at all, but I'm having trouble achieving that. My current solution looks something like this:-</p>
<pre><code>def priority_merge(A, b, keys, mkey):
retval = []
b_index = 0
for elemA in A:
if b_index >= len(b):
break # No more items in b
elemb = b[b_index]
minA = { k: elemA[k] for k in keys }
minb = { k: elemb[k] for k in keys }
if minA == minb: # Found a match
if elemA[mkey] >= elemb[mkey]:
retval.append(elemA)
else: # Check mkey to see if take b instead
retval.append(elemb)
b_index = b_index + 1
else: # No match, check forward by one
if b_index+1 >= len(b):
continue
elembplus = b[b_index+1]
minb = { k: elembplus[k] for k in keys}
if minA == minb:
retval.append(elemb) # This is a new element
if elemA[mkey] >= elembplus[mkey]:
retval.append(elemA)
else:
retval.append(elembplus)
b_index = b_index + 2
if b_index <= len(b):
retval.extend(b[b_index:])
return retval
</code></pre>
<p>This works fine as long as I don't get more than one additions and/or deletions (<code>b</code> relative to <code>A</code>) in a row. So if <code>A</code> contains 1, 2, 3, 5 and <code>b</code> contains 1, 2, 3, 4, 5 it's fine, but if <code>A</code> contains 1, 2, 5 and <code>b</code> contains 1, 2, 3, 4, 5 this breaks down.</p>
<p>I could do a check till len(b) under the else case commented as <code># No match, check forward by one</code>, or first iterate through both <code>A</code> and <code>b</code> to map matching elements, then iterate through again based on that map to create retval. This seems error-prone though (I'm sure its do-able logic wise, but I'm also fairly sure code I write for it would be buggy). Please recommend a suitable algorithm to tackle this problem, whether it be my two ideas or something else.</p>
| 1 | 2016-10-10T07:49:42Z | 39,956,818 | <p>As I told hash method could help you to ensure comparison, based only on <code>keys</code> list you will able to find the intersection element (element to merged) and difference element. </p>
<pre><code>class HashedDictKey(dict):
def __init__(self, keys_, **kwargs):
super().__init__(**kwargs)
self.keys_ = keys_
def __hash__(self):
return hash(tuple(sorted((k, self.get(k)) for k in self.keys_)))
def __eq__(self, other):
return hash(self) == hash(other)
def merge(A, B):
to_be_added = []
to_be_del = []
to_be_updated = []
def get(obj, it):
for i in it:
if obj == i:
return i
raise ValueError("No %s value" % obj)
for a, b in zip_longest(A, B):
if a in B:
to_be_updated.append(a)
if a not in B:
to_be_del.append(a)
if b not in A:
to_be_added.append(b)
for i in to_be_del:
A.remove(i)
for j in to_be_added:
A.append(j)
for i in to_be_updated:
a = get(i, A)
b = get(i, B)
if b['mtime'] > a['mtime']:
A.remove(a)
</code></pre>
<p><a href="https://gist.github.com/anonymous/fb9ede72b501788c759c80c77bbb5d02" rel="nofollow">here the complete snippet</a> </p>
| 0 | 2016-10-10T11:04:45Z | [
"python",
"algorithm",
"merge"
] |
Is there any function as TentativeRoughFix in Python? | 39,953,571 | <p>I have applied Boruta on my dataset to determine the importance of features with respect to a predictor variable. However it is unable to determine the importance of several features.They are being shown as tentative.
Is there any function as TentativeRoughFix in Python. The TentativeRoughFix function is present in R-language. If there is any such function, can anybody guide me towards it. Or any suggestion regarding how to change the importance of variables from "tentative" to "important" or "not important" in python will be very appreciated.</p>
| 0 | 2016-10-10T07:51:47Z | 39,953,911 | <p>There are plenty of options for feature selection in scikit-learn (see <a href="http://scikit-learn.org/stable/modules/feature_selection.html" rel="nofollow">docu</a>).</p>
<p>There is also a Boruta python implementation <a href="https://github.com/danielhomola/boruta_py" rel="nofollow">Boruta_py</a>, but I never tested it.</p>
| 0 | 2016-10-10T08:11:39Z | [
"python",
"machine-learning",
"feature-selection"
] |
rpy2 running R function | 39,953,624 | <p>I have an R function</p>
<pre><code> square_num <- function(x) {
return(x*x)
}
</code></pre>
<p>when I run this via rpy2 as:</p>
<pre><code>from rpy2.robjects.packages import SignatureTranslatedAnonymousPackage as STAP
string = """
square_num <- function(x) {
return(x*x)
}
"""
testy = STAP(string, "testy")
Jack = testy.square_num(10)
print(Jack)
</code></pre>
<p>it works.</p>
<p>When I have the function inside an R file and run it using</p>
<pre><code>from rpy2.robjects.packages import SignatureTranslatedAnonymousPackage as STAP
with open('Algo.r', 'r') as f:
string = f.read()
testy = STAP(string, "testy")
Jack = testy.square_num(10)
print(Jack)
</code></pre>
<p>I get:</p>
<pre><code>Traceback (most recent call last):
File "Main.py", line 25, in <module>
testy = STAP(string, "testy")
File "/usr/local/lib/python2.7/dist-packages/rpy2/robjects/packages.py", line 290, in __init__
reval(string, env)
File "/usr/local/lib/python2.7/dist-packages/rpy2/robjects/packages.py", line 75, in reval
p = rinterface.parse(string)
rpy2.rinterface.RParsingError
</code></pre>
<p>The function is the same in both instances. I just copied and pasted it into a .r file?</p>
| 0 | 2016-10-10T07:54:57Z | 39,962,390 | <p>Did you check the content of your Python variable <code>string</code> ? </p>
<p>The following should work:</p>
<pre><code>from rpy2.robjects.packages import SignatureTranslatedAnonymousPackage as STAP
string = """
square_num <- function(x) {
return(x*x)
}
"""
testy = STAP(string, "testy")
Jack = testy.square_num(10)
print(Jack)
with open('algo.R', 'w') as fh_out:
fh_out.write(string)
with open('algo.R', 'r') as f:
string_again = f.read()
testy = STAP(string_again, "testy")
Jack = testy.square_num(10)
print(Jack)
</code></pre>
| 0 | 2016-10-10T16:08:55Z | [
"python",
"rpy2"
] |
Can't get my Apache to work with mod_wsgi | 39,953,696 | <p>As per guide I downloaded the <a href="https://storage.googleapis.com/google-code-archive-downloads/v2/code.google.com/modwsgi/mod_wsgi-win32-ap22py27-3.3.so" rel="nofollow">mod_wsgi-win32-ap22py27-3.3.so</a>, renamed it to mod_wsgi.so and put it into the /modules folder of Apache.</p>
<p>Next I added the 'LoadModule wsgi_module modules/mod_wsgi.so' line to the httpd.conf.</p>
<p>When starting up Apache it hands me this error: "The requested operation has failed!"</p>
<p>This is the output of the error.log:</p>
<pre><code>Starting the Apache2.2 service
The Apache2.2 service is running.
] Apache/2.2.25 (Win32) configured -- resuming normal operations
[Fri Oct 07 12:59:37 2016] [notice] Server built: Jul 10 2013 01:52:12
[Fri Oct 07 12:59:37 2016] [notice] Parent: Created child process 3420
[Fri Oct 07 12:59:38 2016] [notice] Child 3420: Child process is running
[Fri Oct 07 12:59:38 2016] [notice] Child 3420: Acquired the start mutex.
[Fri Oct 07 12:59:38 2016] [notice] Child 3420: Starting 64 worker threads.
[Fri Oct 07 12:59:38 2016] [notice] Child 3420: Starting thread to listen on port 80.
[Fri Oct 07 12:59:58 2016] [error] [client 127.0.0.1] File does not exist: C:/Program Files (x86)/Apache Software Foundation/Apache2.2/htdocs/favicon.ico
[Fri Oct 07 12:59:59 2016] [error] [client 127.0.0.1] File does not exist: C:/Program Files (x86)/Apache Software Foundation/Apache2.2/htdocs/favicon.ico
[Fri Oct 07 13:01:05 2016] [notice] Parent: Received shutdown signal -- Shutting down the server.
[Fri Oct 07 13:01:05 2016] [notice] Child 3420: Exit event signaled. Child process is ending.
[Fri Oct 07 13:01:06 2016] [notice] Child 3420: Released the start mutex
[Fri Oct 07 13:01:07 2016] [notice] Child 3420: All worker threads have exited.
[Fri Oct 07 13:01:07 2016] [notice] Child 3420: Child process is exiting
[Fri Oct 07 13:01:07 2016] [notice] Parent: Child process exited successfully.
[Fri Oct 07 13:07:27 2016] [warn] mod_wsgi: Compiled for Python/2.7.
[Fri Oct 07 13:07:27 2016] [warn] mod_wsgi: Runtime using Python/2.7.11.
[Fri Oct 07 13:07:27 2016] [notice] Apache/2.2.25 (Win32) mod_wsgi/3.3 Python/2.7.11 configured -- resuming normal operations
[Fri Oct 07 13:07:27 2016] [notice] Server built: Jul 10 2013 01:52:12
[Fri Oct 07 13:07:27 2016] [notice] Parent: Created child process 7712
[Fri Oct 07 13:07:28 2016] [warn] mod_wsgi: Compiled for Python/2.7.
[Fri Oct 07 13:07:28 2016] [warn] mod_wsgi: Runtime using Python/2.7.11.
[Fri Oct 07 13:07:28 2016] [notice] Child 7712: Child process is running
ImportError: No module named site
[Fri Oct 07 13:07:28 2016] [crit] (OS 1813)Der angegebene Ressourcentyp wurde nicht in der Image-Datei gefunden. : master_main: create child process failed. Exiting.
[Fri Oct 07 13:42:17 2016] [notice] Apache/2.2.25 (Win32) configured -- resuming normal operations
[Fri Oct 07 13:42:17 2016] [notice] Server built: Jul 10 2013 01:52:12
[Fri Oct 07 13:42:17 2016] [notice] Parent: Created child process 5752
[Fri Oct 07 13:42:17 2016] [notice] Child 5752: Child process is running
[Fri Oct 07 13:42:17 2016] [notice] Child 5752: Acquired the start mutex.
[Fri Oct 07 13:42:17 2016] [notice] Child 5752: Starting 64 worker threads.
[Fri Oct 07 13:42:17 2016] [notice] Child 5752: Starting thread to listen on port 80.
[Fri Oct 07 13:42:28 2016] [notice] Parent: Received restart signal -- Restarting the server.
[Fri Oct 07 13:42:28 2016] [notice] Child 5752: Exit event signaled. Child process is ending.
[Fri Oct 07 13:42:28 2016] [notice] Apache/2.2.25 (Win32) configured -- resuming normal operations
[Fri Oct 07 13:42:28 2016] [notice] Server built: Jul 10 2013 01:52:12
[Fri Oct 07 13:42:28 2016] [notice] Parent: Created child process 5828
[Fri Oct 07 13:42:28 2016] [warn] mod_wsgi: Compiled for Python/2.7.9+.
[Fri Oct 07 13:42:28 2016] [warn] mod_wsgi: Runtime using Python/2.7.11.
[Fri Oct 07 13:42:28 2016] [notice] Child 5828: Child process is running
ImportError: No module named site
[Fri Oct 07 13:42:28 2016] [crit] (OS 1813)Der angegebene Ressourcentyp wurde nicht in der Image-Datei gefunden. : master_main: create child process failed. Exiting.
[Fri Oct 07 13:42:29 2016] [notice] Child 5752: Released the start mutex
[Fri Oct 07 13:42:30 2016] [notice] Child 5752: All worker threads have exited.
[Fri Oct 07 13:42:30 2016] [notice] Child 5752: Child process is exiting
[Fri Oct 07 13:43:17 2016] [warn] mod_wsgi: Compiled for Python/2.7.9+.
[Fri Oct 07 13:43:17 2016] [warn] mod_wsgi: Runtime using Python/2.7.11.
[Fri Oct 07 13:43:17 2016] [notice] Apache/2.2.25 (Win32) mod_wsgi/4.4.12 Python/2.7.11 configured -- resuming normal operations
[Fri Oct 07 13:43:17 2016] [notice] Server built: Jul 10 2013 01:52:12
[Fri Oct 07 13:43:17 2016] [notice] Parent: Created child process 1200
[Fri Oct 07 13:43:17 2016] [warn] mod_wsgi: Compiled for Python/2.7.9+.
[Fri Oct 07 13:43:17 2016] [warn] mod_wsgi: Runtime using Python/2.7.11.
[Fri Oct 07 13:43:17 2016] [notice] Child 1200: Child process is running
ImportError: No module named site
[Fri Oct 07 13:43:17 2016] [crit] (OS 1813)Der angegebene Ressourcentyp wurde nicht in der Image-Datei gefunden. : master_main: create child process failed. Exiting.
[Fri Oct 07 14:01:14 2016] [warn] mod_wsgi: Compiled for Python/2.7.9+.
[Fri Oct 07 14:01:14 2016] [warn] mod_wsgi: Runtime using Python/2.7.11.
[Fri Oct 07 14:01:14 2016] [notice] Apache/2.2.25 (Win32) mod_wsgi/4.4.12 Python/2.7.11 configured -- resuming normal operations
[Fri Oct 07 14:01:14 2016] [notice] Server built: Jul 10 2013 01:52:12
[Fri Oct 07 14:01:14 2016] [notice] Parent: Created child process 6128
[Fri Oct 07 14:01:14 2016] [warn] mod_wsgi: Compiled for Python/2.7.9+.
[Fri Oct 07 14:01:14 2016] [warn] mod_wsgi: Runtime using Python/2.7.11.
[Fri Oct 07 14:01:14 2016] [notice] Child 6128: Child process is running
ImportError: No module named site
[Fri Oct 07 14:01:14 2016] [crit] (OS 1813)Der angegebene Ressourcentyp wurde nicht in der Image-Datei gefunden. : master_main: create child process failed. Exiting.
[Fri Oct 07 14:01:24 2016] [notice] Apache/2.2.25 (Win32) configured -- resuming normal operations
[Fri Oct 07 14:01:24 2016] [notice] Server built: Jul 10 2013 01:52:12
[Fri Oct 07 14:01:24 2016] [notice] Parent: Created child process 8268
[Fri Oct 07 14:01:24 2016] [notice] Child 8268: Child process is running
[Fri Oct 07 14:01:24 2016] [notice] Child 8268: Acquired the start mutex.
[Fri Oct 07 14:01:24 2016] [notice] Child 8268: Starting 64 worker threads.
[Fri Oct 07 14:01:24 2016] [notice] Child 8268: Starting thread to listen on port 80.
[Fri Oct 07 14:01:29 2016] [notice] Parent: Received shutdown signal -- Shutting down the server.
[Fri Oct 07 14:01:29 2016] [notice] Child 8268: Exit event signaled. Child process is ending.
[Fri Oct 07 14:01:30 2016] [notice] Child 8268: Released the start mutex
[Fri Oct 07 14:01:31 2016] [notice] Child 8268: All worker threads have exited.
[Fri Oct 07 14:01:31 2016] [notice] Child 8268: Child process is exiting
[Fri Oct 07 14:01:31 2016] [notice] Parent: Child process exited successfully.
[Mon Oct 10 09:37:29 2016] [warn] mod_wsgi: Compiled for Python/2.7.9+.
[Mon Oct 10 09:37:29 2016] [warn] mod_wsgi: Runtime using Python/2.7.11.
[Mon Oct 10 09:37:29 2016] [notice] Apache/2.2.25 (Win32) mod_wsgi/4.4.12 Python/2.7.11 configured -- resuming normal operations
[Mon Oct 10 09:37:29 2016] [notice] Server built: Jul 10 2013 01:52:12
[Mon Oct 10 09:37:29 2016] [notice] Parent: Created child process 1012
[Mon Oct 10 09:37:29 2016] [warn] mod_wsgi: Compiled for Python/2.7.9+.
[Mon Oct 10 09:37:29 2016] [warn] mod_wsgi: Runtime using Python/2.7.11.
[Mon Oct 10 09:37:29 2016] [notice] Child 1012: Child process is running
ImportError: No module named site
[Mon Oct 10 09:37:29 2016] [crit] (OS 1813)Der angegebene Ressourcentyp wurde nicht in der Image-Datei gefunden. : master_main: create child process failed. Exiting.
[Mon Oct 10 09:37:55 2016] [notice] Apache/2.2.25 (Win32) configured -- resuming normal operations
[Mon Oct 10 09:37:55 2016] [notice] Server built: Jul 10 2013 01:52:12
[Mon Oct 10 09:37:55 2016] [notice] Parent: Created child process 6368
[Mon Oct 10 09:37:55 2016] [notice] Child 6368: Child process is running
[Mon Oct 10 09:37:55 2016] [notice] Child 6368: Acquired the start mutex.
[Mon Oct 10 09:37:55 2016] [notice] Child 6368: Starting 64 worker threads.
[Mon Oct 10 09:37:55 2016] [notice] Child 6368: Starting thread to listen on port 80.
[Mon Oct 10 09:38:14 2016] [notice] Parent: Received restart signal -- Restarting the server.
[Mon Oct 10 09:38:14 2016] [notice] Child 6368: Exit event signaled. Child process is ending.
[Mon Oct 10 09:38:15 2016] [notice] Apache/2.2.25 (Win32) configured -- resuming normal operations
[Mon Oct 10 09:38:15 2016] [notice] Server built: Jul 10 2013 01:52:12
[Mon Oct 10 09:38:15 2016] [notice] Parent: Created child process 7484
[Mon Oct 10 09:38:15 2016] [warn] mod_wsgi: Compiled for Python/2.7.9+.
[Mon Oct 10 09:38:15 2016] [warn] mod_wsgi: Runtime using Python/2.7.11.
[Mon Oct 10 09:38:15 2016] [notice] Child 7484: Child process is running
ImportError: No module named site
[Mon Oct 10 09:38:15 2016] [crit] (OS 1813)Der angegebene Ressourcentyp wurde nicht in der Image-Datei gefunden. : master_main: create child process failed. Exiting.
[Mon Oct 10 09:38:15 2016] [warn] (OS 995)Der E/A-Vorgang wurde wegen eines Threadendes oder einer Anwendungsanforderung abgebrochen. : winnt_accept: Asynchronous AcceptEx failed.
[Mon Oct 10 09:38:15 2016] [notice] Child 6368: Released the start mutex
[Mon Oct 10 09:38:16 2016] [notice] Child 6368: All worker threads have exited.
[Mon Oct 10 09:38:16 2016] [notice] Child 6368: Child process is exiting
</code></pre>
<p>I'm not sure what the problem is exactly since the mod_wsg is for Python 2.7 and I am using Python 2.7 (32 Bit) in Addition to Apache 2.2 (32 Bit).</p>
| 0 | 2016-10-10T07:59:01Z | 39,953,980 | <p>Solved the issue.</p>
<p>I had to set the environment variables PYTHONHOME and PYTHONPATH for it to fix the 'ImportError: No module named site' error.</p>
<pre><code>set PYTHONHOME=c:\Python27
set PYTHONPATH=c:\Python27\Lib
set PATH=%PYTHONHOME%;%PATH%
</code></pre>
| 1 | 2016-10-10T08:15:59Z | [
"python",
"apache",
"mod-wsgi"
] |
install ns3.21 in ubuntu16.04 error | 39,954,098 | <ol>
<li><p>When I try to "sudo apt-get install gsl-bin libgsl0-dev libgsl0ldbl" 16.04 cannot find the package libgsl0ldbl for the reason that libgsl0-dev is replaced by libgsl-dev and libgsl0ldbl is obslolete, now replaced by libgsl2. I don't know if it matters.</p></li>
<li><p>When I run the command "./build.py âenable-examples âenable-tests".
It failed with the message :</p>
<h1>Build NS-3</h1></li>
</ol>
<p>Entering directory <code>./ns-3.25'
Traceback (most recent call last):
</code>File "./build.py", line 171, in
sys.exit(main(sys.argv))
File "./build.py", line 162, in main
build_ns3(config, build_examples, build_tests, args, build_options)
File "./build.py", line 81, in build_ns3
run_command(cmd) # waf configure ...
File "/home/limeng/ns3/ns-allinone-3.25/util.py", line 20, in run_command
print(" => ", ' '.join(argv))`
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 0: ordinal not in range(128)</p>
| 0 | 2016-10-10T08:23:52Z | 40,142,985 | <p>I personally tried to do that and it didn't worth the trouble at all so I ended up installing it on Ubuntu 14.04.</p>
<p>In case you have no other choice, try watching this <a href="https://www.youtube.com/watch?v=SckgZkBg-Oc" rel="nofollow">tutorial</a></p>
| 0 | 2016-10-19T23:13:49Z | [
"python",
"ubuntu",
"ubuntu-16.04",
"ns-3"
] |
Looping each row in file1.txt over all rows of file2.txt for comparing | 39,954,370 | <p>I have two text files, say file1.txt contains something like</p>
<p>100.145 10.0728</p>
<p>100.298 10.04</p>
<p>and file2.txt contains something like</p>
<p>100.223 8.92739</p>
<p>100.209 9.04269</p>
<p>100.084 9.08411</p>
<p>100.023 9.01252</p>
<p>I want to compare column 1 and column 2 of both files and print match if the difference of both columns in file1.txt and in file2.txt is less or equal to 0.001.</p>
<p>since both files don't have equal no. or rows, i want row1 of file1.txt to be compared with all the rows of file2.txt, then it will now pick row2 of file1.txt and do same until all rows of file1.txt are exhausted. Difference should like this ($1 file1.txt - $1 file2.txt) and ($2 file1.txt - $2 file2.txt) if difference of both is less or equal 0.001, it should print the rows in both file that match</p>
| -3 | 2016-10-10T08:39:46Z | 39,956,275 | <p>you can try this;</p>
<pre><code>#!/bin/bash
while read line; do
while read line2; do
Col1F1=$(echo $line | awk '{print $1}')
Col1F2=$(echo $line2 | awk '{print $1}')
Col2F1=$(echo $line | awk '{print $2}')
Col2F2=$(echo $line2 | awk '{print $2}')
if [ ! -z "${Col1F1}" ] && [ ! -z "${Col1F2}" ]; then
diffCol1=$(awk '{print $1-$2}' <<< "$Col1F1 $Col1F2")
diffCol2=$(awk '{print $1-$2}' <<< "$Col2F1 $Col2F2")
if (( $(echo "$diffCol1 < 0.001" |bc -l) && $(echo "$diffCol2 < 0.001" |bc -l))); then
echo -e ${Col1F1} "\t" ${Col2F1} "\t" ${Col1F2} "\t" ${Col2F2} "\n"
fi
fi
done < file2.txt
done < file1.txt
</code></pre>
| -1 | 2016-10-10T10:32:20Z | [
"python",
"awk"
] |
POST request works in Postman but not in Python | 39,954,475 | <p>When I make this POST request in Postman, I get the data. When I do it in Python 2.7 (using a Jupyter notebook), I get the error "No JSON object could be decoded". What am I doing wrong and how can I make it work?</p>
<pre><code>import json
import requests
url = 'http://api.scb.se/OV0104/v1/doris/en/ssd/BE/BE0101/BE0101A/BefolkningNy'
headers={'content-type': 'application/json'}
payload = {
"query": [
{
"code": "ContentsCode",
"selection": {
"filter": "item",
"values": [
"BE0101N1"
]
}
},
{
"code": "Tid",
"selection": {
"filter": "item",
"values": [
"2010",
"2011"
]
}
},
{
"code": "Region",
"selection": {
"filter": "item",
"values": [
"01"
]
}
}
],
"response": {
"format": "json"
}
}
headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
r = requests.post(url, data=payload)
print(r.text)
print(r.json())
</code></pre>
<p>The manual for the api is here, but it is not much help:</p>
<p><a href="http://www.scb.se/en_/About-us/Open-data-API/API-for-the-Statistical-Database-/" rel="nofollow">http://www.scb.se/en_/About-us/Open-data-API/API-for-the-Statistical-Database-/</a></p>
| 1 | 2016-10-10T08:46:31Z | 39,954,514 | <p>Set <code>json=payload</code> and requests will add the headers you need:</p>
<pre><code>url = 'http://api.scb.se/OV0104/v1/doris/en/ssd/BE/BE0101/BE0101A/BefolkningNy'
payload = ....
r = requests.post(url, json=payload)
</code></pre>
<p>That will give you your json:</p>
<pre><code>In [7]:
...: r = requests.post(url, json=payload)
...: print(r.json())
...:
{u'data': [{u'values': [u'2054343'], u'key': [u'01', u'2010']}, {u'values': [u'2091473'], u'key': [u'01', u'2011']}], u'comments': [], u'columns': [{u'text': u'region', u'code': u'Region', u'type': u'd'}, {u'text': u'year', u'code': u'Tid', u'type': u't'}, {u'text': u'Population', u'code': u'BE0101N1', u'type': u'c'}]}
</code></pre>
<p>If you happen to get an <em>json.decoder.JSONDecodeError: Unexpected UTF-8 BOM (decode using utf-8-sig):</em> error set the encoding to <em>utf-8-sig</em>:</p>
<pre><code>r = requests.post(url, json=payload)
r.encoding = "utf-8-sig"
print(r.json())
</code></pre>
| 1 | 2016-10-10T08:49:02Z | [
"python",
"json"
] |
My module has __init__.py and still Python can't import it | 39,954,495 | <p>I have a small python module </p>
<pre><code>+-- address_book
| +-- models.py
| +-- __init__.py
+-- test
| +-- test_models.py
</code></pre>
<p>When I run <code>python address_book/test/test_models.py</code> I get this error </p>
<pre><code>Traceback (most recent call last):
File "address_book/test/test_models.py", line 5, in <module>
from address_book import models
ImportError: No module named 'address_book'
</code></pre>
<h1>test_models.py</h1>
<pre><code>#!/usr/bin/env python
# -*- coding: utf-8 -*-
import unittest
from address_book import models
...
...
...
if __name__ == '__main__':
unittest.main()
</code></pre>
| 1 | 2016-10-10T08:47:40Z | 39,954,623 | <p>Your file structure should look like </p>
<pre><code>+-- address_book
| +-- __init__.py
| +-- models.py
+-- test
| +-- test_models.py
| +-- __init__.py
</code></pre>
<p>For your code to work you also have to be in the directory above address_book.</p>
| 2 | 2016-10-10T08:55:49Z | [
"python"
] |
My module has __init__.py and still Python can't import it | 39,954,495 | <p>I have a small python module </p>
<pre><code>+-- address_book
| +-- models.py
| +-- __init__.py
+-- test
| +-- test_models.py
</code></pre>
<p>When I run <code>python address_book/test/test_models.py</code> I get this error </p>
<pre><code>Traceback (most recent call last):
File "address_book/test/test_models.py", line 5, in <module>
from address_book import models
ImportError: No module named 'address_book'
</code></pre>
<h1>test_models.py</h1>
<pre><code>#!/usr/bin/env python
# -*- coding: utf-8 -*-
import unittest
from address_book import models
...
...
...
if __name__ == '__main__':
unittest.main()
</code></pre>
| 1 | 2016-10-10T08:47:40Z | 39,954,628 | <p>Like said in comment, your tree looks strange. Put tests on the same level as address_book.</p>
<p>To run the tests, you should use auto test discovery tools like nose or pytest (in doubt, go for pytest). Those tools automatically find the packages they are testing so that you don't have to install them or care in any way about their presence in the PATH.</p>
<p>It might sound like a burden at first, having to learn a new tool, but it's pretty straightforward, and on the long run, pytest is really helpful.</p>
| 2 | 2016-10-10T08:55:55Z | [
"python"
] |
My module has __init__.py and still Python can't import it | 39,954,495 | <p>I have a small python module </p>
<pre><code>+-- address_book
| +-- models.py
| +-- __init__.py
+-- test
| +-- test_models.py
</code></pre>
<p>When I run <code>python address_book/test/test_models.py</code> I get this error </p>
<pre><code>Traceback (most recent call last):
File "address_book/test/test_models.py", line 5, in <module>
from address_book import models
ImportError: No module named 'address_book'
</code></pre>
<h1>test_models.py</h1>
<pre><code>#!/usr/bin/env python
# -*- coding: utf-8 -*-
import unittest
from address_book import models
...
...
...
if __name__ == '__main__':
unittest.main()
</code></pre>
| 1 | 2016-10-10T08:47:40Z | 39,955,868 | <pre><code>There is problem with import of module from parent directory as __main__ lies in child folder
if you do the folder structure like below your same code for import will work
+----test
+---test_models.py
+---__init__.py
+---address_book
+---__init__.py
+---models.py
</code></pre>
<p>or you can add your project path to PYTHONPATH variable and your same code will work</p>
| 0 | 2016-10-10T10:05:36Z | [
"python"
] |
My module has __init__.py and still Python can't import it | 39,954,495 | <p>I have a small python module </p>
<pre><code>+-- address_book
| +-- models.py
| +-- __init__.py
+-- test
| +-- test_models.py
</code></pre>
<p>When I run <code>python address_book/test/test_models.py</code> I get this error </p>
<pre><code>Traceback (most recent call last):
File "address_book/test/test_models.py", line 5, in <module>
from address_book import models
ImportError: No module named 'address_book'
</code></pre>
<h1>test_models.py</h1>
<pre><code>#!/usr/bin/env python
# -*- coding: utf-8 -*-
import unittest
from address_book import models
...
...
...
if __name__ == '__main__':
unittest.main()
</code></pre>
| 1 | 2016-10-10T08:47:40Z | 39,956,380 | <p>The problem stems from the fact that python does not know where to look for <code>address_book</code>. You can fix this by setting the <code>PYTHONPATH</code> environment variable before starting python.</p>
<p>Given the following directory structure:</p>
<pre><code>base_dir
+-- address_book
| +-- __init__.py
| +-- models.py
+-- test
| +-- test_models.py
</code></pre>
<p>Then this will work:</p>
<pre><code>$ env PYTHONPATH=/path/to/base_dir python address_book/test/test_models.py
.
----------------------------------------------------------------------
Ran 1 test in 0.001s
OK
</code></pre>
<p><code>PYTHONPATH</code> can be a relative path as well, just so long as the relative path points to the source directory from the current working directory</p>
<p>To avoid typing out the <code>env PYTHONPATH=/path/to/base_dir</code> each time you can set it using your shells appropriate syntax. Below I set the PYTHONPATH environment variable using a bash syntax.</p>
<pre><code>$ cd /path/to/base_dir
$ export PYTHONPATH=. # the current directory as a relative link
$ python address_book/test/test_models.py
.
----------------------------------------------------------------------
Ran 1 test in 0.001s
OK
</code></pre>
<hr>
<p>As a side note I would alter your directory structure as it's not a great idea to keep your tests in the same directory tree as your source directory. Typically you might do something like this:</p>
<pre><code>base_dir
+-- address_book
| +-- __init__.py
| +-- models.py
+-- test # no __init__, not a module
| +-- test_models.py
</code></pre>
<p>This allows you to more easily package your project without also including your tests.</p>
| 1 | 2016-10-10T10:38:42Z | [
"python"
] |
How to ajaxable validate a PasswordChangeForm? | 39,954,578 | <p>I have some forms that I want to validate with an ajax view.</p>
<pre><code>class ProfileEditPasswordForm(PasswordChangeForm):
class Meta:
model = User
class AjaxValidation(generic.edit.FormView):
def get(self, request, *args, **kwargs):
return HttpResponseRedirect('/')
def form_invalid(self, form):
data = []
for k, v in form._errors.iteritems():
text = {
'desc': ', '.join(v),
}
if k == '__all__':
text['key'] = '#%s' % self.request.POST.get('form')
else:
text['key'] = '#id_%s' % k
data.append(text)
return HttpResponse(json.dumps(data))
def form_valid(self, form):
return HttpResponse("ok")
def get_form_class(self):
form_dict = {
'signup': forms.RegisterForm,
'signin': forms.LoginForm,
'safety': forms.ProfileEditPasswordForm
}
return form_dict[self.request.POST.get('form')] #=> TypeError
</code></pre>
<p>As you can see, I have 3 different forms. First two work just fine. But the third one returns me an error.</p>
<blockquote>
<p><code>__init__() takes at least 2 arguments (1 given)</code></p>
</blockquote>
<p>I believe that it happens because my form requires a user to validate his old password, so I did this:</p>
<pre><code>'safety': forms.ProfileEditPasswordForm(user=self.request.user)
</code></pre>
<p>And know it throws another error:</p>
<blockquote>
<p><code>'ProfileEditPasswordForm' object is not callable</code></p>
</blockquote>
<p>And here I stuck.</p>
<hr>
<pre><code>Traceback:
File "***/env/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
132. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "***/env/local/lib/python2.7/site-packages/django/views/generic/base.py" in view
71. return self.dispatch(request, *args, **kwargs)
File "***/env/local/lib/python2.7/site-packages/django/views/generic/base.py" in dispatch
89. return handler(request, *args, **kwargs)
File "***/env/local/lib/python2.7/site-packages/django/views/generic/edit.py" in post
213. form = self.get_form()
File "***/env/local/lib/python2.7/site-packages/django/views/generic/edit.py" in get_form
74. return form_class(**self.get_form_kwargs())
Exception Type: TypeError at /accounts/validate/
Exception Value: 'ProfileEditPasswordForm' object is not callable
Request information:
GET: No GET data
POST:
csrfmiddlewaretoken = u'MjSRpY4NQsTuv6hG8HLYZYI3n9HpPU4R'
form = u'safety'
old_password = u''
new_password1 = u''
new_password2 = u''
</code></pre>
| 0 | 2016-10-10T08:53:14Z | 39,956,875 | <p>I think the problem is that django <code>FormView</code> is not compatible with <code>PasswordChangeForm</code>. The form requires the user to be passed to its constructor, but the view will not do that. You could try overriding <code>get_form_kwargs</code> method like this:</p>
<pre><code>class AjaxValidation(generic.edit.FormView):
# your methods
def get_form_kwargs(self):
kwargs = super(AjaxValidation, self).get_form_kwargs()
kwargs['user'] = self.request.user
return kwargs
</code></pre>
<p>The <code>kwargs</code> will be passed to form constructor and it should work. <code>get_form_class</code> is OK in your main code example</p>
| 1 | 2016-10-10T11:07:49Z | [
"python",
"ajax",
"django",
"python-2.7",
"django-1.8"
] |
How to convert column with list of values into rows in Pandas DataFrame | 39,954,668 | <p>Hi I have a dataframe like this:</p>
<pre><code> A B
0: some value [[L1, L2]]
</code></pre>
<p>I want to change it into:</p>
<pre><code> A B
0: some value L1
1: some value L2
</code></pre>
<p>How can I do that?</p>
| 2 | 2016-10-10T08:58:21Z | 39,955,283 | <p>you can do it this way:</p>
<pre><code>In [84]: df
Out[84]:
A B
0 some value [[L1, L2]]
1 another value [[L3, L4, L5]]
In [85]: (df['B'].apply(lambda x: pd.Series(x[0]))
....: .stack()
....: .reset_index(level=1, drop=True)
....: .to_frame('B')
....: .join(df[['A']], how='left')
....: )
Out[85]:
B A
0 L1 some value
0 L2 some value
1 L3 another value
1 L4 another value
1 L5 another value
</code></pre>
| 2 | 2016-10-10T09:32:11Z | [
"python",
"pandas",
"dataframe"
] |
How to convert column with list of values into rows in Pandas DataFrame | 39,954,668 | <p>Hi I have a dataframe like this:</p>
<pre><code> A B
0: some value [[L1, L2]]
</code></pre>
<p>I want to change it into:</p>
<pre><code> A B
0: some value L1
1: some value L2
</code></pre>
<p>How can I do that?</p>
| 2 | 2016-10-10T08:58:21Z | 39,955,506 | <p>I can't find a elegant way to handle this, but the following codes can work...</p>
<pre><code>import pandas as pd
import numpy as np
df = pd.DataFrame([{"a":1,"b":[[1,2]]},{"a":4, "b":[[3,4,5]]}])
z = []
for k,row in df.iterrows():
for j in list(np.array(row.b).flat):
z.append({'a':row.a, 'b':j})
result = pd.DataFrame(z)
</code></pre>
| 0 | 2016-10-10T09:44:24Z | [
"python",
"pandas",
"dataframe"
] |
How to convert column with list of values into rows in Pandas DataFrame | 39,954,668 | <p>Hi I have a dataframe like this:</p>
<pre><code> A B
0: some value [[L1, L2]]
</code></pre>
<p>I want to change it into:</p>
<pre><code> A B
0: some value L1
1: some value L2
</code></pre>
<p>How can I do that?</p>
| 2 | 2016-10-10T08:58:21Z | 39,959,302 | <p>Faster solution with <code>chain.from_iterable</code> and <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.repeat.html" rel="nofollow"><code>numpy.repeat</code></a>:</p>
<pre><code>df = pd.DataFrame({'A':['a','b'],
'B':[[['A1', 'A2']],[['A1', 'A2', 'A3']]]})
print (df)
A B
0 a [[A1, A2]]
1 b [[A1, A2, A3]]
df1 = pd.DataFrame({ "A": np.repeat(df.A.values,
[len(x) for x in (chain.from_iterable(df.B))]),
"B": list(chain.from_iterable(chain.from_iterable(df.B)))})
print (df1)
A B
0 a A1
1 a A2
2 b A1
3 b A2
4 b A3
</code></pre>
<p><strong>Timings</strong>:</p>
<pre><code>A = np.unique(np.random.randint(0, 1000, 1000))
B = [[list(string.ascii_letters[:random.randint(3, 10)])] for _ in range(len(A))]
df = pd.DataFrame({"A":A, "B":B})
print (df)
A B
0 0 [[a, b, c, d, e, f, g, h]]
1 1 [[a, b, c]]
2 3 [[a, b, c, d, e, f, g, h, i]]
3 5 [[a, b, c, d, e]]
4 6 [[a, b, c, d, e, f, g, h, i]]
5 7 [[a, b, c, d, e, f, g]]
6 8 [[a, b, c, d, e, f]]
7 10 [[a, b, c, d, e, f]]
8 11 [[a, b, c, d, e, f, g]]
9 12 [[a, b, c, d, e, f, g, h, i]]
10 13 [[a, b, c, d, e, f, g, h]]
...
...
In [67]: %timeit pd.DataFrame({ "A": np.repeat(df.A.values, [len(x) for x in (chain.from_iterable(df.B))]),"B": list(chain.from_iterable(chain.from_iterable(df.B)))})
1000 loops, best of 3: 818 µs per loop
In [68]: %timeit ((df['B'].apply(lambda x: pd.Series(x[0])).stack().reset_index(level=1, drop=True).to_frame('B').join(df[['A']], how='left')))
10 loops, best of 3: 103 ms per loop
</code></pre>
| 0 | 2016-10-10T13:20:42Z | [
"python",
"pandas",
"dataframe"
] |
How to save fileobject/stream to text file on disk in python? | 39,954,670 | <p>I have a file object which is just a string with a large number of youtube urls taken from a playlist, how would I go about saving it to a .txt file?
Thanks</p>
| -5 | 2016-10-10T08:58:26Z | 39,954,744 | <p>Assuming your file object is f:</p>
<pre><code>with open("urls.txt", "w") as urls_file:
urls_file.write(f.read())
</code></pre>
<p>It may need improvement depending on the file size.</p>
| 1 | 2016-10-10T09:02:19Z | [
"python",
"python-3.x"
] |
How to create a graph in Python using a CSV File data by graph-tool? | 39,954,768 | <p>I'm trying to create a graph with graph-tool (<a href="https://graph-tool.skewed.de" rel="nofollow">https://graph-tool.skewed.de</a>) from csv file that content like:</p>
<pre><code>A,B,50
A,C,34
C,D,55
D,D,80
A,D,90
B,D,78
</code></pre>
<p>Now I want to create a graph with A, B, C, D as nodes and the third column numbers as edges. I am using graph-tool library. The third column number shows the common items shared by A,B and A,C and so on.</p>
<p>I can do it by "networkx" (read_edgelist and etc) but I want to do it with graph-tool.</p>
| 0 | 2016-10-10T09:03:46Z | 39,957,150 | <p>Assuming you already know how to read the CSV file in Python (for example, using the <a href="https://docs.python.org/3.6/library/csv.html" rel="nofollow">CSV library</a>), The docs on the website <a href="https://graph-tool.skewed.de/static/doc/quickstart.html#creating-and-manipulating-graphs" rel="nofollow">explain how to do this very clearly.</a></p>
<p>Something like</p>
<pre><code>import graph_tool
g = Graph(directed=False)
# this is the result of csv.parse(file)
list_of_edges = [['A', 'B', 50], ['A','C',34], ['C','D',55], ['D','D',80], ['A','D',90], ['B','D',78]]
vertices = {}
for e in list_of_edges:
if e[0] not in vertices:
vertices[e[0]] = True
if e[1] not in vertices:
vertices[e[1]] = True
for d in vertices:
vertices[d] = g.add_vertex()
for edge in list_of_edges:
g.add_edge(vertices[edge[0]], vertices[edge[1]])
</code></pre>
| 1 | 2016-10-10T11:24:13Z | [
"python",
"csv",
"graph-tool"
] |
Python webcam record | 39,954,788 | <p>I want to create a webcam streaming app that records webcam stream for, say about 30 seconds, and save it as <code>myFile.wmv</code>. Now To get live camera feed I know this code :-</p>
<pre><code>import cv2
import numpy as np
c = cv2.VideoCapture(0)
while(1):
_,f = c.read()
cv2.imshow('e2',f)
if cv2.waitKey(5)==27:
break
cv2.destroyAllWindows()
</code></pre>
<p>But I have no idea off how to record for a given number of seconds and save it as a file in its current directory,</p>
<p>Please someone point me to the right direction</p>
<p>Thanks</p>
| -2 | 2016-10-10T09:04:46Z | 39,955,438 | <p><em>ABOUT TIME</em></p>
<p>Why do not use the python <a href="https://docs.python.org/2/library/time.html" rel="nofollow">time function</a>? In particular <code>time.time()</code> Look at this <a href="http://stackoverflow.com/a/23197503/6564973">answer about time in python</a></p>
<p>NB OpenCV should have (or had) its own timer but I can not tell you for sure if it works in current versions. </p>
<p><em>ABOUT RECORDING/SAVING</em></p>
<p>Look at this <a href="http://stackoverflow.com/a/29317298/6564973">other answer</a></p>
| 1 | 2016-10-10T09:40:50Z | [
"python",
"python-2.7",
"opencv",
"video",
"webcam"
] |
Collapse the result of the cartesian product | 39,954,890 | <p>To calculate cartesian product with python is very simple. Just need to use
<a href="https://docs.python.org/3/library/itertools.html#itertools.product" rel="nofollow">itertools.product</a></p>
<pre><code>>>> source = [['a', 'b', 'c'], [1, 2, 3]]
>>> list(itertools.product(*source))
[('a', 1), ('a', 2), ('a', 3), ('b', 1), ('b', 2), ('b', 3), ('c', 1), ('c', 2), ('c', 3)]
</code></pre>
<p>But I can't find the reverse operation. How to find the source <code>[['a', 'b', 'c'], [1, 2, 3]]</code> from the result of a product. Does anyone know the universal solution?</p>
<p>I appreciate any suggestions.</p>
| 1 | 2016-10-10T09:10:47Z | 39,955,028 | <p>Its only a partial solution but assuming you <strong>know for certain</strong> that the result is a valid cartesian product generated by <code>itertools.product</code> and it is over lists of <strong>distinct</strong> values</p>
<pre><code>>>> [list(collections.OrderedDict.fromkeys(y)) for y in zip(*cartesian_product)]
[['a', 'b', 'c'], [1, 2, 3]]
</code></pre>
<p>Here we simply use the <code>zip(*...)</code> idiom to unpack the tuples and then use <code>OrderedDict</code> in lieu of an <code>OrderedSet</code> to reduce them to their unique values.</p>
<p>This approach generalises to larger <code>itertools.product</code> of distinct values. For example:</p>
<pre><code>>>> source = [['a', 'b', 'c'], [1, 2, 3], [3, 5, 7]]
>>> cartesian_product = itertools.product(*source)
>>> [list(collections.OrderedDict.fromkeys(y)) for y in zip(*cartesian_product)]
[['a', 'b', 'c'], [1, 2, 3], [3, 5, 7]]
</code></pre>
| 6 | 2016-10-10T09:18:47Z | [
"python",
"itertools"
] |
Mapping Python list values to dictionary values | 39,955,222 | <p>I have a list of rows...</p>
<p><code>rows = [2, 21]</code></p>
<p>And a dictionary of data...</p>
<p><code>data = {'x': [46, 35], 'y': [20, 30]}</code></p>
<p>I'd like to construct a second dictionary, <code>dataRows</code>, keyed by the row that looks like this...</p>
<p><code>dataRows = {2: {'x': 46, 'y': 20}, 21: {'x': 35, 'y': 30}}</code></p>
<p>I tried the following code, but the values of <code>dataRows</code> are always the same (last value in loop):</p>
<pre><code>for i, row in enumerate(rows):
for key, value in data.items():
dataRows[row] = value[i]
</code></pre>
<p>Any assistance would be greatly appreciated.</p>
| 2 | 2016-10-10T09:28:49Z | 39,955,362 | <p>Your issue is that you are not puting sub-dictionaries inside dataRows. The fix would be this:</p>
<pre><code>for i, row in enumerate(rows):
dataRows[row] = {}
for key, value in data.items():
dataRows[row][key] = value[i]
</code></pre>
| 7 | 2016-10-10T09:36:56Z | [
"python"
] |
Mapping Python list values to dictionary values | 39,955,222 | <p>I have a list of rows...</p>
<p><code>rows = [2, 21]</code></p>
<p>And a dictionary of data...</p>
<p><code>data = {'x': [46, 35], 'y': [20, 30]}</code></p>
<p>I'd like to construct a second dictionary, <code>dataRows</code>, keyed by the row that looks like this...</p>
<p><code>dataRows = {2: {'x': 46, 'y': 20}, 21: {'x': 35, 'y': 30}}</code></p>
<p>I tried the following code, but the values of <code>dataRows</code> are always the same (last value in loop):</p>
<pre><code>for i, row in enumerate(rows):
for key, value in data.items():
dataRows[row] = value[i]
</code></pre>
<p>Any assistance would be greatly appreciated.</p>
| 2 | 2016-10-10T09:28:49Z | 39,955,393 | <p>Following code works for me:</p>
<pre><code>rows = [2, 21]
data = {'x': [46, 35], 'y': [20, 30]}
dataRows = {}
for i, row in enumerate(rows):
dataRows[row] = {}
dataRows[row]['x'] = data['x'][i]
dataRows[row]['y'] = data['y'][i]
print dataRows
</code></pre>
<p>UPDATE:</p>
<p>You can also use collections.defaultdict() to avoid assigning dict to dataRows in every iteration.</p>
<pre><code>import collections
rows = [2, 21]
data = {'x': [46, 35], 'y': [20, 30]}
dataRows = collections.defaultdict(dict)
for i, row in enumerate(rows):
for key, value in data.items():
dataRows[row][key] = value[i]
print dataRows
</code></pre>
| 2 | 2016-10-10T09:38:25Z | [
"python"
] |
Mapping Python list values to dictionary values | 39,955,222 | <p>I have a list of rows...</p>
<p><code>rows = [2, 21]</code></p>
<p>And a dictionary of data...</p>
<p><code>data = {'x': [46, 35], 'y': [20, 30]}</code></p>
<p>I'd like to construct a second dictionary, <code>dataRows</code>, keyed by the row that looks like this...</p>
<p><code>dataRows = {2: {'x': 46, 'y': 20}, 21: {'x': 35, 'y': 30}}</code></p>
<p>I tried the following code, but the values of <code>dataRows</code> are always the same (last value in loop):</p>
<pre><code>for i, row in enumerate(rows):
for key, value in data.items():
dataRows[row] = value[i]
</code></pre>
<p>Any assistance would be greatly appreciated.</p>
| 2 | 2016-10-10T09:28:49Z | 39,955,429 | <p>In a line:</p>
<pre><code>>>> {r: {k: v[i] for k, v in data.items()} for i, r in enumerate(rows)}
{2: {'x': 46, 'y': 20}, 21: {'x': 35, 'y': 30}}
</code></pre>
| 0 | 2016-10-10T09:40:26Z | [
"python"
] |
Mapping Python list values to dictionary values | 39,955,222 | <p>I have a list of rows...</p>
<p><code>rows = [2, 21]</code></p>
<p>And a dictionary of data...</p>
<p><code>data = {'x': [46, 35], 'y': [20, 30]}</code></p>
<p>I'd like to construct a second dictionary, <code>dataRows</code>, keyed by the row that looks like this...</p>
<p><code>dataRows = {2: {'x': 46, 'y': 20}, 21: {'x': 35, 'y': 30}}</code></p>
<p>I tried the following code, but the values of <code>dataRows</code> are always the same (last value in loop):</p>
<pre><code>for i, row in enumerate(rows):
for key, value in data.items():
dataRows[row] = value[i]
</code></pre>
<p>Any assistance would be greatly appreciated.</p>
| 2 | 2016-10-10T09:28:49Z | 39,955,582 | <p>Here's a Python 3 solution with only one explicit loop:</p>
<pre><code>{r: dict(zip(data.keys(), d)) for r, *d in zip(rows, *data.values())}
</code></pre>
| 0 | 2016-10-10T09:48:18Z | [
"python"
] |
Python Django official tutorial "Polls", beginner gets frustrating errors | 39,955,232 | <p>I am trying to follow through the Python Django Tutorial from the official site.</p>
<p>However I find it hard to follow. I did everything as written but I got the following error"</p>
<p><a href="http://i.stack.imgur.com/o8pce.jpg" rel="nofollow">ERROR screen caption</a></p>
<p>It sounds like something is wrong with the ENV, but I am not so sure why.
Also at the last line of error it said "include is not defined"... </p>
| -1 | 2016-10-10T09:29:19Z | 39,955,273 | <p>You are missing the line <code>from django.conf.urls import include, url</code>.</p>
| 1 | 2016-10-10T09:31:37Z | [
"python",
"django",
"compiler-errors",
"virtualenv"
] |
Pandas pivot table: columns order and subtotals | 39,955,336 | <p>I'm using Pandas 0.19.</p>
<p>Considering the following data frame:</p>
<pre><code>FID admin0 admin1 admin2 windspeed population
0 cntry1 state1 city1 60km/h 700
1 cntry1 state1 city1 90km/h 210
2 cntry1 state1 city2 60km/h 100
3 cntry1 state2 city3 60km/h 70
4 cntry1 state2 city4 60km/h 180
5 cntry1 state2 city4 90km/h 370
6 cntry2 state3 city5 60km/h 890
7 cntry2 state3 city6 60km/h 120
8 cntry2 state3 city6 90km/h 420
9 cntry2 state3 city6 120km/h 360
10 cntry2 state4 city7 60km/h 740
</code></pre>
<p>How can I create a table like this one?</p>
<pre><code> population
60km/h 90km/h 120km/h
admin0 admin1 admin2
cntry1 state1 city1 700 210 0
cntry1 state1 city2 100 0 0
cntry1 state2 city3 70 0 0
cntry1 state2 city4 180 370 0
cntry2 state3 city5 890 0 0
cntry2 state3 city6 120 420 360
cntry2 state4 city7 740 0 0
</code></pre>
<p>I have tried with the following pivot table:</p>
<pre><code>table = pd.pivot_table(df,index=["admin0","admin1","admin2"], columns=["windspeed"], values=["population"],fill_value=0)
</code></pre>
<p>In general it works great, but unfortunately I am not able to sort the new columns in the right order: the 120km/h column appears before the ones for 60km/h and 90km/h. How can I specify the order of the new columns?</p>
<p>Moreover, as a second step I need to add subtotals both for admin0 and admin1. Ideally, the table I need should be like this:</p>
<pre><code> population
60km/h 90km/h 120km/h
admin0 admin1 admin2
cntry1 state1 city1 700 210 0
cntry1 state1 city2 100 0 0
SUM state1 800 210 0
cntry1 state2 city3 70 0 0
cntry1 state2 city4 180 370 0
SUM state2 250 370 0
SUM cntry1 1050 580 0
cntry2 state3 city5 890 0 0
cntry2 state3 city6 120 420 360
SUM state3 1010 420 360
cntry2 state4 city7 740 0 0
SUM state4 740 0 0
SUM cntry2 1750 420 360
SUM ALL 2800 1000 360
</code></pre>
| 5 | 2016-10-10T09:35:19Z | 39,956,010 | <p>you can do it using <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reindex.html" rel="nofollow">reindex()</a> method and custom sorting:</p>
<pre><code>In [26]: table
Out[26]:
population
windspeed 120km/h 60km/h 90km/h
admin0 admin1 admin2
cntry1 state1 city1 0 700 210
city2 0 100 0
state2 city3 0 70 0
city4 0 180 370
cntry2 state3 city5 0 890 0
city6 360 120 420
state4 city7 0 740 0
In [27]: cols = sorted(table.columns.tolist(), key=lambda x: int(x[1].replace('km/h','')))
In [28]: cols
Out[28]: [('population', '60km/h'), ('population', '90km/h'), ('population', '120km/h')]
In [29]: table = table.reindex(columns=cols)
In [30]: table
Out[30]:
population
windspeed 60km/h 90km/h 120km/h
admin0 admin1 admin2
cntry1 state1 city1 700 210 0
city2 100 0 0
state2 city3 70 0 0
city4 180 370 0
cntry2 state3 city5 890 0 0
city6 120 420 360
state4 city7 740 0 0
</code></pre>
| 2 | 2016-10-10T10:15:05Z | [
"python",
"pandas",
"dataframe",
"pivot"
] |
Pandas pivot table: columns order and subtotals | 39,955,336 | <p>I'm using Pandas 0.19.</p>
<p>Considering the following data frame:</p>
<pre><code>FID admin0 admin1 admin2 windspeed population
0 cntry1 state1 city1 60km/h 700
1 cntry1 state1 city1 90km/h 210
2 cntry1 state1 city2 60km/h 100
3 cntry1 state2 city3 60km/h 70
4 cntry1 state2 city4 60km/h 180
5 cntry1 state2 city4 90km/h 370
6 cntry2 state3 city5 60km/h 890
7 cntry2 state3 city6 60km/h 120
8 cntry2 state3 city6 90km/h 420
9 cntry2 state3 city6 120km/h 360
10 cntry2 state4 city7 60km/h 740
</code></pre>
<p>How can I create a table like this one?</p>
<pre><code> population
60km/h 90km/h 120km/h
admin0 admin1 admin2
cntry1 state1 city1 700 210 0
cntry1 state1 city2 100 0 0
cntry1 state2 city3 70 0 0
cntry1 state2 city4 180 370 0
cntry2 state3 city5 890 0 0
cntry2 state3 city6 120 420 360
cntry2 state4 city7 740 0 0
</code></pre>
<p>I have tried with the following pivot table:</p>
<pre><code>table = pd.pivot_table(df,index=["admin0","admin1","admin2"], columns=["windspeed"], values=["population"],fill_value=0)
</code></pre>
<p>In general it works great, but unfortunately I am not able to sort the new columns in the right order: the 120km/h column appears before the ones for 60km/h and 90km/h. How can I specify the order of the new columns?</p>
<p>Moreover, as a second step I need to add subtotals both for admin0 and admin1. Ideally, the table I need should be like this:</p>
<pre><code> population
60km/h 90km/h 120km/h
admin0 admin1 admin2
cntry1 state1 city1 700 210 0
cntry1 state1 city2 100 0 0
SUM state1 800 210 0
cntry1 state2 city3 70 0 0
cntry1 state2 city4 180 370 0
SUM state2 250 370 0
SUM cntry1 1050 580 0
cntry2 state3 city5 890 0 0
cntry2 state3 city6 120 420 360
SUM state3 1010 420 360
cntry2 state4 city7 740 0 0
SUM state4 740 0 0
SUM cntry2 1750 420 360
SUM ALL 2800 1000 360
</code></pre>
| 5 | 2016-10-10T09:35:19Z | 39,956,469 | <p>Solution with subtotals and <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.MultiIndex.from_arrays.html" rel="nofollow"><code>MultiIndex.from_arrays</code></a>. Last <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.concat.html" rel="nofollow"><code>concat</code></a> and all <code>Dataframes</code>, <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sort_index.html" rel="nofollow"><code>sort_index</code></a> and add all <code>sum</code>:</p>
<pre><code>#replace km/h and convert to int
df.windspeed = df.windspeed.str.replace('km/h','').astype(int)
print (df)
FID admin0 admin1 admin2 windspeed population
0 0 cntry1 state1 city1 60 700
1 1 cntry1 state1 city1 90 210
2 2 cntry1 state1 city2 60 100
3 3 cntry1 state2 city3 60 70
4 4 cntry1 state2 city4 60 180
5 5 cntry1 state2 city4 90 370
6 6 cntry2 state3 city5 60 890
7 7 cntry2 state3 city6 60 120
8 8 cntry2 state3 city6 90 420
9 9 cntry2 state3 city6 120 360
10 10 cntry2 state4 city7 60 740
#pivoting
table = pd.pivot_table(df,
index=["admin0","admin1","admin2"],
columns=["windspeed"],
values=["population"],
fill_value=0)
print (table)
population
windspeed 60 90 120
admin0 admin1 admin2
cntry1 state1 city1 700 210 0
city2 100 0 0
state2 city3 70 0 0
city4 180 370 0
cntry2 state3 city5 890 0 0
city6 120 420 360
state4 city7 740 0 0
</code></pre>
<pre><code>#groupby and create sum dataframe by levels 0,1
df1 = table.groupby(level=[0,1]).sum()
df1.index = pd.MultiIndex.from_arrays([df1.index.get_level_values(0),
df1.index.get_level_values(1)+ '_sum',
len(df1.index) * ['']])
print (df1)
population
windspeed 60 90 120
admin0
cntry1 state1_sum 800 210 0
state2_sum 250 370 0
cntry2 state3_sum 1010 420 360
state4_sum 740 0 0
df2 = table.groupby(level=0).sum()
df2.index = pd.MultiIndex.from_arrays([df2.index.values + '_sum',
len(df2.index) * [''],
len(df2.index) * ['']])
print (df2)
population
windspeed 60 90 120
cntry1_sum 1050 580 0
cntry2_sum 1750 420 360
#concat all dataframes together, sort index
df = pd.concat([table, df1, df2]).sort_index(level=[0])
</code></pre>
<pre><code>#add km/h to second level in columns
df.columns = pd.MultiIndex.from_arrays([df.columns.get_level_values(0),
df.columns.get_level_values(1).astype(str) + 'km/h'])
#add all sum
df.loc[('All_sum','','')] = table.sum().values
print (df)
population
60km/h 90km/h 120km/h
admin0 admin1 admin2
cntry1 state1 city1 700 210 0
city2 100 0 0
state1_sum 800 210 0
state2 city3 70 0 0
city4 180 370 0
state2_sum 250 370 0
cntry1_sum 1050 580 0
cntry2 state3 city5 890 0 0
city6 120 420 360
state3_sum 1010 420 360
state4 city7 740 0 0
state4_sum 740 0 0
cntry2_sum 1750 420 360
All_sum 2800 1000 360
</code></pre>
<p>EDIT by comment:</p>
<pre><code>def f(x):
print (x)
if (len(x) > 1):
return x.sum()
df1 = table.groupby(level=[0,1]).apply(f).dropna(how='all')
df1.index = pd.MultiIndex.from_arrays([df1.index.get_level_values(0),
df1.index.get_level_values(1)+ '_sum',
len(df1.index) * ['']])
print (df1)
population
windspeed 60 90 120
admin0
cntry1 state1_sum 800.0 210.0 0.0
state2_sum 250.0 370.0 0.0
cntry2 state3_sum 1010.0 420.0 360.0
</code></pre>
| 4 | 2016-10-10T10:44:19Z | [
"python",
"pandas",
"dataframe",
"pivot"
] |
Django How can I use redis in Windows10? | 39,955,449 | <p>I am developing small system with Django framework and Windows 10. I am going to use Redis for caching on memory. Well, I found that Redis doesn't support Windows OS officially but MsOpenTech provides a package for Windows 64 bit. I installed it with chocolatey package manager. <a href="https://chocolatey.org/packages/redis-64" rel="nofollow">https://chocolatey.org/packages/redis-64</a></p>
<p>Then I installed django-redis package by pip install in cmd. Well, It automatically installed redis module at the same time. I thought it would be fine to delete redis module because I already installed redis 3.0.503 64 bit(for Win). But it occured error "no mudule named 'redis'". I checked django-redis directory "django_redis-4.5.0-py3.4.egg-info". There was one line 'redis>=2.10.0' in 'requries.text' file. so I assumed django-redis is set to need redis 2.10.0 as default.</p>
<p>well, then I just installed redis by pip install redis in cmd. After setting in Django, I saved some key value data as test on redis. (by using cache_page decorator)</p>
<pre><code>CACHES = {
"default" : {
"BACKEND": "django_redis.cache.RedisCache",
"LOCATION": "redis://127.0.0.1:6379/1",
"OPTION": {
"CLIENT_CLASS": "django_redis.client.DefaultClient",
},
"KEY_PREFIX": "Test"
}
}
</code></pre>
<p>I connected to redis.</p>
<pre><code>redis-cli -n 1
</code></pre>
<p>I checked keys</p>
<pre><code>127.0.0.1:6379[1]> keys *
</code></pre>
<p>result was like this. empty</p>
<pre><code>(empty list or set)
</code></pre>
<p>then I put test data on redis by cache_page decorator to check it. I got this result.</p>
<pre><code>1) "Test:1:views.decorators.cache.cache_page..GET.1be77f2243e36ea7e7fa68d85c1c277e.d41d8cd98f00b204e9800998ecf8427e.en-us.Korea_Standard_Time"
2) "Test:1:views.decorators.cache.cache_header..1be77f2243e36ea7e7fa68d85c1c277e.en-us.Korea_Standard_Time"
</code></pre>
<p>I checked it with get command.it is supposed to show rendered HTML string. </p>
<pre><code>get "Test:1:views.decorators.cache.cache_page..GET.1be77f2243e36ea7e7fa68d85c1c277e.d41d8cd98f00b204e9800998ecf8427e.en-us.Korea_Standard_Time"
</code></pre>
<p>The result like below seems alright.</p>
<pre><code>"\x80\x04\x95\xe8\a\x00\x00\x00\x00\x00\x00\x8c\x14django.http.response\x94\x8c\x0cHttpResponse\x94\x93\x94)}\x94\x92\x94}\x94(\x8c\x06closed\x94\x89\x8c\b_charset\x94N\x8c\x0e_handler_class\x94N\x8c\b_headers\x94}\x94(\x8c\x0ccontent-type\x94\x8c\x0cContent-Type\x94\x8c\x18text/html; charset=utf-8\x94\x86\x94\x8c\aexpires\x94\x8c\aExpires\x94\x8c\x1dMon, 10 Oct 2016 09:32:19 GMT\x94\x86\x94\x8c\rcache-control\x94\x8c\rCache-Control\x94\x8c\nmax-age=60\x94\x86\x94\x8c\rlast-modified\x94\x8c\rLast-Modified\x94\x8c\x1dMon, 10 Oct 2016 09:31:19 GMT\x94\x86\x94u\x8c\x0e_reason_phrase\x94N\x8c\acookies\x94\x8c\x0chttp.cookies\x94\x8c\x0cSimpleCookie\x94\x93\x94)}\x94\x92\x94\x8c\x11_closable_objects\x94]\x94\x8c\n_container\x94]\x94B/\x06\x00\x00<!DOCTYPE html>\n<html lang=\"ko\">\n\n<head>\n<title>Menu front page</title>\n</head>\n\n<body>\n<div id=\"context_processor_test\">\n\t<ul>\n\t\t<li>[&lt;Menu: root&gt;, &lt;Menu: \xed\x98\x84\xed\x99\xa9\xeb\xb6\x84\xec\x84\x9d&gt;, &lt;Menu: \xec\x9e\xac\xea\xb3\xa0\xed\x98\x84\xed\x99\xa9&gt;, &lt;Menu: \xed\x98\x84\xec\x9e\xac \xec\x9e\xac\xea\xb3\xa0&gt;, &lt;Menu: \xea\xb8\xb0\xea\xb0\x84\xec\x9e\xac\xea\xb3\xa0 \xec\xa1\xb0\xed\x9a\x8c&gt;, &lt;Menu: \xec\x9e\xac\xea\xb3\xa0\xea\xb8\xb0\xea\xb4\x80 \xec\xa1\xb0\xed\x9a\x8c&gt;, &lt;Menu: \xec\x9e\xac\xea\xb3\xa0 \xed\x9a\x8c\xec\xa0\x84\xec\x9c\xa8 \xec\xa1\xb0\xed\x9a\x8c&gt;, &lt;Menu: \xeb\xa7\xa4\xec\x9e\x85\xeb\xa7\xa4\xec\xb6\x9c \xeb\xb6\x84\xec\x84\x9d&gt;, &lt;Menu: \xea\xb8\xb0\xea\xb0\x84\xeb\xb3\x84 \xed\x98\x84\xed\x99\xa9&gt;, &lt;Menu: \xec\x83\x81\xed\x92\x88\xeb\xb3\x84 \xed\x98\x84\xed\x99\xa9&gt;, &lt;Menu: \xea\xb1\xb0\xeb\x9e\x98\xed\x98\x95\xed\x83\x9c\xeb\xb3\x84 \xed\x98\x84\xed\x99\xa9&gt;, &lt;Menu: \xec\x82\xac\xec\x97\x85\xeb\xb6\x80\xeb\xb3\x84 \xed\x98\x84\xed\x99\xa9&gt;, &lt;Menu: \xea\xb1\xb0\xeb\x9e\x98\xec\xb2\x98\xeb\xb3\x84 \xed\x98\x84\xed\x99\xa9&gt;, &lt;Menu: \xec\x9e\x91\xec\x97\x85\xed\x98\x84\xed\x99\xa9&gt;, &lt;Menu: \xec\x9e\x91\xec\x97\x85\xec\x9a\x94\xec\xb2\xad \xed\x98\x84\xed\x99\xa9&gt;, &lt;Menu: \xea\xb2\x80\xec\x88\x98\xec\x9a\x94\xec\xb2\xad&gt;, &lt;Menu: \xec\x83\x81\xed\x92\x88\xed\x99\x94 \xec\x9a\x94\xec\xb2\xad&gt;, &lt;Menu: \xec\xa0\x9c\xed\x92\x88\xed\x99\x94 \xec\x9a\x94\xec\xb2\xad&gt;, &lt;Menu: \xec\x97\xbd\xec\x97\x89\xea\xb4\x80\xeb\xa6\xac&gt;, &lt;Menu: \xeb\x82\xb4\xeb\xb6\x80\xec\xb2\x98\xeb\xa6\xac&gt;, &lt;Menu: \xed\x8c\x90\xeb\xa7\xa4\xea\xb4\x80\xeb\xa6\xac&gt;, &lt;Menu: \xea\xb5\xac\xeb\xa7\xa4\xea\xb4\x80\xeb\xa6\xac&gt;, &lt;Menu: \xed\x99\x98\xea\xb2\xbd\xec\x84\xa4\xec\xa0\x95&gt;]</li>\n\t</ul>\n</div>\n\n<div id=\"context_processor_test2\">\n\t<ul>\n\t\t<li>&lt;QuerySet [&lt;UserInfo: dkjfadl&gt;, &lt;UserInfo: fidlajf&gt;, &lt;UserInfo: fjialejgljadf&gt;, &lt;UserInfo: dfialghelfdja&gt;, &lt;UserInfo: dkajlf&gt;, &lt;UserInfo: testgroup&gt;, &lt;UserInfo: dfjlda&gt;, &lt;UserInfo: fjdalfiagda&gt;, &lt;UserInfo: remann&gt;, &lt;UserInfo: aldfjdalfj&gt;, &lt;UserInfo: dlkajflad&gt;, &lt;UserInfo: dkajfldafj&gt;, &lt;UserInfo: djafldijfl&gt;, &lt;UserInfo: testgroup&gt;, &lt;UserInfo: &lt;bound method Group.__str__ of &lt;Group: remann&gt;&gt;&gt;, &lt;UserInfo: remann&gt;, &lt;UserInfo: testgroup&gt;, &lt;UserInfo: testgroup&gt;]&gt;</li>\n\t</ul>\n</div>\n<!--\n<div id=\"top_menu\">\n\t\n</div>\n-->\n\n\n\n\n</body>\n</html>\n\n\x94aub."
</code></pre>
<p>Because my templete code is like below.</p>
<pre><code><!DOCTYPE html>
<html lang="ko">
<head>
<title>{% block title %}Menu front page{% endblock %}</title>
</head>
<body>
<div id="context_processor_test">
<ul>
<li>{{ menu_list }}</li>
</ul>
</div>
<div id="context_processor_test2">
<ul>
<li>{{ user_info_list }}</li>
</ul>
</div>
<!--
<div id="top_menu">
{% for top_menu in root.get_children %}
<ul style="display:inline-block;">
<li><a href="{{top_menu.menu_alias}}"> {{ top_menu.menu_name }} </a></li>
</ul>
{% endfor %}
</div>
-->
{% block content %}{% endblock %}
{% block footer %}{% endblock %}
</body>
</html>
</code></pre>
<p>My question are</p>
<p>1) Is it okay to use redis on Windows with this setting? I wonder if it works properly.</p>
<p>2) I wonder why it named like "Test:1:views.decorators.cache.cache_page..GET.1be77f2243e36ea7e7fa68d85c1c277e.d41d8cd98f00b204e9800998ecf8427e.en-us.Korea_Standard_Time" instead of just "Test:1:views.decorators.cache.cache_page"</p>
<p>well, my question could be not well explained or out of point.
Just let me know if you need to know more in detail or properly.</p>
<p>I hope there are some people have similar issues with Windows OS to deal with Redis and Django!</p>
<p>Thank you for reading!</p>
| 0 | 2016-10-10T09:41:18Z | 39,956,710 | <p>You uninstalled the Python <code>redis</code> package thinking it was the Redis server but it's just a Python package with code to <em>access</em> Redis. You need to reinstall it. But you seem to have that part fixed.</p>
<p>As for using Redis with Django on Windows 10 the way you installed it, I would say it depends on what you want to do. If you just want to play around with it to learn, you should be fine. On the other hand, if you want to do some more serious development, I would install Redis another way. Here are a few possibilities I can think of:</p>
<ul>
<li>Installing Linux in a virtual machine with VirtualBox, VMWare or something like that, and install Redis in there;</li>
<li>Windows 10 now has the possibility of running Ubuntu Linux in it, so perhaps installing Redis there is the easiest option;</li>
<li>Use a Docker container to run Redis (use Docker for Windows: <a href="https://docs.docker.com/engine/getstarted/" rel="nofollow">https://docs.docker.com/engine/getstarted/</a> then you can get the Redis image from here: <a href="https://hub.docker.com/_/redis/" rel="nofollow">https://hub.docker.com/_/redis/</a>)</li>
</ul>
<p>Finally, regarding why the cache entries have those names, the default key Django cache creates for cache entries is defined <a href="https://github.com/django/django/blob/master/django/core/cache/backends/base.py#L27" rel="nofollow">here (django/core/cache/backends/base.py:27)</a>:</p>
<pre class="lang-python prettyprint-override"><code>def default_key_func(key, key_prefix, version):
"""
Default function to generate keys.
Constructs the key used by all other methods. By default it prepends
the `key_prefix'. KEY_FUNCTION can be used to specify an alternate
function with custom key making behavior.
"""
return '%s:%s:%s' % (key_prefix, version, key)
</code></pre>
<p>In your case the key is <code>Test:1:views.decorators.cache.cache_page..GET.1be77f2243e36ea7e7fa68d85c1c277e.d41d8cd98f00b204e9800998ecf8427e.en-us.Korea_Standard_Time</code>, so that gives us the following breakdown:</p>
<pre><code>key_prefix = Test
version = 1
key = views.decorators.cache.cache_page..GET.1be77f2243e36ea7e7fa68d85c1c277e.d41d8cd98f00b204e9800998ecf8427e.en-us.Korea_Standard_Time
</code></pre>
<p>If you have a look in <a href="https://github.com/django/django/blob/master/django/views/decorators/cache.py#L10" rel="nofollow"><code>django/views/decorators/cache.py:10</code></a> you can see how the key part is composed. Specifically, this:</p>
<blockquote>
<p>The cache is keyed by the URL and some data from the headers.</p>
</blockquote>
<p>The extra stuff you see there beyond what you were expecting is the headers data from the request.</p>
| 1 | 2016-10-10T10:57:10Z | [
"python",
"django",
"redis",
"windows-10"
] |
Python google query with requests module, get responce in http format | 39,955,450 | <p>I want to execute a google query with requests module in python. Here is my script:</p>
<pre><code>import requests
searchfor = 'test'
payload = {'q': searchfor, 'key': API_KEY, 'cx': SEARCH_ENGINE_ID}
link = 'https://www.googleapis.com/customesearch/v1'
r = requests.get(link, paramas=payload)
print r.content
</code></pre>
<p>and then run the script as: ./googler.py > out</p>
<p>and the out is in json format.</p>
<p>How can I get the responce in http format?</p>
| 0 | 2016-10-10T09:41:21Z | 39,956,133 | <p>The google api only supports <a href="https://developers.google.com/custom-search/json-api/v1/overview" rel="nofollow">atom/Json</a>. </p>
<p>So you have to parse the JSON to HTML.
You maybe want to check <a href="https://docs.python.org/2/library/json.html" rel="nofollow">json package</a>.</p>
<p>append something like this to your file:</p>
<pre><code>import json
items = json.loads(r)['items']
print "<html><body>"
for item in items:
print "<a href=" +item['url'] + ">" + item['title'] + "</a>"
print "</body></html>"
</code></pre>
| 1 | 2016-10-10T10:23:47Z | [
"python",
"json",
"http",
"google-app-engine",
"request"
] |
sqlalchemy existing database query | 39,955,521 | <p>I am using SQLAlchmey as ORM for a python project. I have created few models/schema and it is working fine. Now I need to query a existing mysql database, no insert/update just the select statement. </p>
<p>How can I create a wrapper around the tables of this existing database? I have briefly gone through the sqlalchemy docs and SO but couldn't find anything relevant. All suggest execute method, where I need to write the raw sql queries, While I want to use the SQLAlchmey query method in same way as I am using with the SA models.</p>
<p>For example if the existing db has table name User then I want to query it using the dbsession ( only the select operation, probably with join)</p>
| 1 | 2016-10-10T09:45:25Z | 39,966,711 | <p>You seem to have an impression that SQLAlchemy can only work with a database structure created by SQLAlchemy (probably using <code>MetaData.create_all()</code>) - this is not correct. SQLAlchemy can work perfectly with a pre-existing database, you just need to define your models to match database tables. One way to do that is to use reflection, as Ilja Everilä suggests:</p>
<pre><code>class MyClass(Base):
__table__ = Table('mytable', Base.metadata,
autoload=True, autoload_with=some_engine)
</code></pre>
<p>(which, in my opinion, would be totally fine for one-off scripts but may lead to incredibly frustrating bugs in a "real" application if there's a potential that the database structure may change over time)</p>
<p>Another way is to simply define your models as usual taking care to define your models to match the database tables, which is not that difficult. The benefit of this approach is that you can map only a subset of database tables to you models and even only a subset of table columns to your model's fields. Suppose you have 10 tables in the database but only interested in <code>users</code> table from where you only need <code>id</code>, <code>name</code> and <code>email</code> fields:</p>
<pre><code>class User(Base):
id = sa.Column(sa.Integer, primary_key=True)
name = sa.Column(sa.String)
email = sa.Column(sa.String)
</code></pre>
<p>(note how we didn't need to define some details which are only needed to emit correct DDL, such as the length of the String fields or the fact that the <code>email</code> field has an index)</p>
<p>SQLAlchemy will not emit INSERT/UPDATE queries unless you create or modify models in your code. If you want to ensure that your queries are read-only you may create a special user in the database and grant that user SELECT privileges only. Alternatively/in addition, you may also experiment with rolling back the transaction in your application code.</p>
| 1 | 2016-10-10T21:02:46Z | [
"python",
"sqlalchemy",
"pyramid",
"pylons"
] |
Flask GAE app giving error | 39,955,605 | <p>I created a flask app which is working fine on pythonanywhere but when i deployed it on google app engine ,its giving error <a href="http://aapkatool.appspot.com/" rel="nofollow">http://aapkatool.appspot.com/</a></p>
<p>here is my code</p>
<pre><code>from flask import Flask, request, session, redirect,url_for,render_template,flash,abort
import jinja2
import os
jinja_environment = jinja2.Environment(autoescape=True,
loader=jinja2.FileSystemLoader(os.path.join(os.path.dirname(__file__), 'templates')))
app = Flask(__name__)
app.config["DEBUG"] = True
@app.route('/', methods=['POST', 'GET'])
def emi():
if request.method == 'POST':
p =int(request.form['enternumber1'])
r=float(request.form['enternumber2'])
R=(r/12)/100
N =int(request.form['enternumber3'])
Dp =int(request.form['enternumber4'])
P=p-Dp
B=(1+R)**N
I=(B)/(B-1)
EMI1 = (P) * (R) * (I)
EMI="%.2f" %(EMI1)
TAP1=EMI1*N
TAP="%.2f" %(TAP1)
TI=TAP1-P
TI="%.2f" %(TI)
return render_template('index.html', EMI=EMI,TAP=TAP,TI=TI,P=P,r=r,N=N,Dp=Dp)
return render_template('index.html')
</code></pre>
<p>and here is my app.yaml code</p>
<pre><code>application: aapkatool
version: 1
runtime: python27
api_version: 1
threadsafe: yes
handlers:
- url: /.*
script: initialize.app
libraries:
- name: jinja2
version: "2.6"
- name: markupsafe
version: "latest"
</code></pre>
<p>and here is initialize.py code</p>
<pre><code>from google.appengine.ext.webapp.util import run_wsgi_app
from main import app
run_wsgi_app(app)
</code></pre>
<p>here is the complete error</p>
<pre><code>Traceback (most recent call last):
File "C:\Program Files\Google\google_appengine\google\appengine\runtime\wsgi.py", line 267, in Handle
result = handler(dict(self._environ), self._StartResponse)
File "C:\Python27\ageapp\flask\app.py", line 1701, in __call__
return self.wsgi_app(environ, start_response)
File "C:\Python27\ageapp\flask\app.py", line 1685, in wsgi_app
with self.request_context(environ):
File "C:\Python27\ageapp\flask\app.py", line 1646, in request_context
return RequestContext(self, environ)
File "C:\Python27\ageapp\flask\ctx.py", line 186, in __init__
self.match_request()
File "C:\Python27\ageapp\flask\ctx.py", line 204, in match_request
self.url_adapter.match(return_rule=True)
File "C:\Python27\ageapp\werkzeug\werkzeug\routing.py", line 1423, in match
raise NotFound()
NotFound: 404: Not Found
INFO 2016-10-12 15:13:03,801 module.py:788] default: "GET /favicon.ico HTTP/1.1" 500 -
ERROR 2016-10-12 09:43:46,542 wsgi.py:279]
Traceback (most recent call last):
File "C:\Program Files\Google\google_appengine\google\appengine\runtime\wsgi.py", line 267, in Handle
result = handler(dict(self._environ), self._StartResponse)
File "C:\Python27\ageapp\flask\app.py", line 1701, in __call__
return self.wsgi_app(environ, start_response)
File "C:\Python27\ageapp\flask\app.py", line 1689, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "C:\Python27\ageapp\flask\app.py", line 1687, in wsgi_app
response = self.full_dispatch_request()
File "C:\Python27\ageapp\flask\app.py", line 1360, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Python27\ageapp\flask\app.py", line 1358, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Python27\ageapp\flask\app.py", line 1344, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "C:\Python27\ageapp\main.py", line 13, in age2
p =int(request.form['enternumber1'])
File "C:\Python27\ageapp\werkzeug\werkzeug\local.py", line 336, in __getattr__
return getattr(self._get_current_object(), name)
File "C:\Python27\ageapp\werkzeug\werkzeug\utils.py", line 77, in __get__
value = self.func(obj)
File "C:\Python27\ageapp\werkzeug\werkzeug\wrappers.py", line 383, in form
self._load_form_data()
File "C:\Python27\ageapp\flask\wrappers.py", line 129, in _load_form_data
RequestBase._load_form_data(self)
File "C:\Python27\ageapp\werkzeug\werkzeug\wrappers.py", line 318, in _load_form_data
data = parser.parse_from_environ(self.environ)
File "C:\Python27\ageapp\werkzeug\werkzeug\formparser.py", line 164, in parse_from_environ
return self.parse(stream, mimetype, content_length, options)
File "C:\Python27\ageapp\werkzeug\werkzeug\formparser.py", line 188, in parse
content_length, options)
File "C:\Python27\ageapp\werkzeug\werkzeug\formparser.py", line 98, in wrapper
return f(self, stream, *args, **kwargs)
File "C:\Python27\ageapp\werkzeug\werkzeug\formparser.py", line 209, in _parse_urlencoded
errors=self.errors, cls=self.cls)
File "C:\Python27\ageapp\werkzeug\werkzeug\urls.py", line 278, in url_decode_stream
include_empty, errors))
File "C:\Python27\ageapp\werkzeug\werkzeug\datastructures.py", line 330, in __init__
for key, value in mapping or ():
File "C:\Python27\ageapp\werkzeug\werkzeug\urls.py", line 283, in _url_decode_impl
for pair in pair_iter:
File "C:\Python27\ageapp\werkzeug\werkzeug\wsgi.py", line 670, in make_chunk_iter
stream = make_limited_stream(stream, limit)
File "C:\Python27\ageapp\werkzeug\werkzeug\wsgi.py", line 579, in make_limited_stream
raise TypeError('stream not limited and no limit provided.')
TypeError: stream not limited and no limit provided.
INFO 2016-10-12 15:13:46,665 module.py:788] default: "POST / HTTP/1.1" 500 -
please help me why it is giving error.
</code></pre>
<p>Thanks</p>
| 1 | 2016-10-10T09:49:46Z | 39,960,128 | <p>Is the <code>calculate</code> function defined in both deployments on <a href="http://kk268.pythonanywhere.com/emi-calc" rel="nofollow">http://kk268.pythonanywhere.com/emi-calc</a> and <a href="http://aapkatool.appspot.com/" rel="nofollow">http://aapkatool.appspot.com/</a> ? The only error I'm seeing in my browser is:</p>
<pre><code>(index):145 Uncaught ReferenceError: calculate is not defined
onclick @ (index):145
</code></pre>
<p>and I don't see where the <code>calculate</code> function is defined.</p>
| 0 | 2016-10-10T14:03:05Z | [
"python",
"google-app-engine",
"flask",
"jinja2"
] |
Flask GAE app giving error | 39,955,605 | <p>I created a flask app which is working fine on pythonanywhere but when i deployed it on google app engine ,its giving error <a href="http://aapkatool.appspot.com/" rel="nofollow">http://aapkatool.appspot.com/</a></p>
<p>here is my code</p>
<pre><code>from flask import Flask, request, session, redirect,url_for,render_template,flash,abort
import jinja2
import os
jinja_environment = jinja2.Environment(autoescape=True,
loader=jinja2.FileSystemLoader(os.path.join(os.path.dirname(__file__), 'templates')))
app = Flask(__name__)
app.config["DEBUG"] = True
@app.route('/', methods=['POST', 'GET'])
def emi():
if request.method == 'POST':
p =int(request.form['enternumber1'])
r=float(request.form['enternumber2'])
R=(r/12)/100
N =int(request.form['enternumber3'])
Dp =int(request.form['enternumber4'])
P=p-Dp
B=(1+R)**N
I=(B)/(B-1)
EMI1 = (P) * (R) * (I)
EMI="%.2f" %(EMI1)
TAP1=EMI1*N
TAP="%.2f" %(TAP1)
TI=TAP1-P
TI="%.2f" %(TI)
return render_template('index.html', EMI=EMI,TAP=TAP,TI=TI,P=P,r=r,N=N,Dp=Dp)
return render_template('index.html')
</code></pre>
<p>and here is my app.yaml code</p>
<pre><code>application: aapkatool
version: 1
runtime: python27
api_version: 1
threadsafe: yes
handlers:
- url: /.*
script: initialize.app
libraries:
- name: jinja2
version: "2.6"
- name: markupsafe
version: "latest"
</code></pre>
<p>and here is initialize.py code</p>
<pre><code>from google.appengine.ext.webapp.util import run_wsgi_app
from main import app
run_wsgi_app(app)
</code></pre>
<p>here is the complete error</p>
<pre><code>Traceback (most recent call last):
File "C:\Program Files\Google\google_appengine\google\appengine\runtime\wsgi.py", line 267, in Handle
result = handler(dict(self._environ), self._StartResponse)
File "C:\Python27\ageapp\flask\app.py", line 1701, in __call__
return self.wsgi_app(environ, start_response)
File "C:\Python27\ageapp\flask\app.py", line 1685, in wsgi_app
with self.request_context(environ):
File "C:\Python27\ageapp\flask\app.py", line 1646, in request_context
return RequestContext(self, environ)
File "C:\Python27\ageapp\flask\ctx.py", line 186, in __init__
self.match_request()
File "C:\Python27\ageapp\flask\ctx.py", line 204, in match_request
self.url_adapter.match(return_rule=True)
File "C:\Python27\ageapp\werkzeug\werkzeug\routing.py", line 1423, in match
raise NotFound()
NotFound: 404: Not Found
INFO 2016-10-12 15:13:03,801 module.py:788] default: "GET /favicon.ico HTTP/1.1" 500 -
ERROR 2016-10-12 09:43:46,542 wsgi.py:279]
Traceback (most recent call last):
File "C:\Program Files\Google\google_appengine\google\appengine\runtime\wsgi.py", line 267, in Handle
result = handler(dict(self._environ), self._StartResponse)
File "C:\Python27\ageapp\flask\app.py", line 1701, in __call__
return self.wsgi_app(environ, start_response)
File "C:\Python27\ageapp\flask\app.py", line 1689, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "C:\Python27\ageapp\flask\app.py", line 1687, in wsgi_app
response = self.full_dispatch_request()
File "C:\Python27\ageapp\flask\app.py", line 1360, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Python27\ageapp\flask\app.py", line 1358, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Python27\ageapp\flask\app.py", line 1344, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "C:\Python27\ageapp\main.py", line 13, in age2
p =int(request.form['enternumber1'])
File "C:\Python27\ageapp\werkzeug\werkzeug\local.py", line 336, in __getattr__
return getattr(self._get_current_object(), name)
File "C:\Python27\ageapp\werkzeug\werkzeug\utils.py", line 77, in __get__
value = self.func(obj)
File "C:\Python27\ageapp\werkzeug\werkzeug\wrappers.py", line 383, in form
self._load_form_data()
File "C:\Python27\ageapp\flask\wrappers.py", line 129, in _load_form_data
RequestBase._load_form_data(self)
File "C:\Python27\ageapp\werkzeug\werkzeug\wrappers.py", line 318, in _load_form_data
data = parser.parse_from_environ(self.environ)
File "C:\Python27\ageapp\werkzeug\werkzeug\formparser.py", line 164, in parse_from_environ
return self.parse(stream, mimetype, content_length, options)
File "C:\Python27\ageapp\werkzeug\werkzeug\formparser.py", line 188, in parse
content_length, options)
File "C:\Python27\ageapp\werkzeug\werkzeug\formparser.py", line 98, in wrapper
return f(self, stream, *args, **kwargs)
File "C:\Python27\ageapp\werkzeug\werkzeug\formparser.py", line 209, in _parse_urlencoded
errors=self.errors, cls=self.cls)
File "C:\Python27\ageapp\werkzeug\werkzeug\urls.py", line 278, in url_decode_stream
include_empty, errors))
File "C:\Python27\ageapp\werkzeug\werkzeug\datastructures.py", line 330, in __init__
for key, value in mapping or ():
File "C:\Python27\ageapp\werkzeug\werkzeug\urls.py", line 283, in _url_decode_impl
for pair in pair_iter:
File "C:\Python27\ageapp\werkzeug\werkzeug\wsgi.py", line 670, in make_chunk_iter
stream = make_limited_stream(stream, limit)
File "C:\Python27\ageapp\werkzeug\werkzeug\wsgi.py", line 579, in make_limited_stream
raise TypeError('stream not limited and no limit provided.')
TypeError: stream not limited and no limit provided.
INFO 2016-10-12 15:13:46,665 module.py:788] default: "POST / HTTP/1.1" 500 -
please help me why it is giving error.
</code></pre>
<p>Thanks</p>
| 1 | 2016-10-10T09:49:46Z | 39,970,620 | <p>I am not sure why you even have the <code>initialize.py</code> file at all. It doesn't look like you need it. The <a href="https://cloud.google.com/appengine/docs/python/tools/webapp/" rel="nofollow"><code>google.appengine.ext.webapp</code></a> package docs state that its for the deprecated Python 2.5 environment and you're rightfully using Python 2.7.</p>
<ol>
<li>Change your <code>app.yaml</code>'s script handler to point instead to <code>main.app</code>.</li>
<li>Delete <code>initialize.py</code>.</li>
<li>Redeploy or better yet, test your code locally so that you will see what the exact error code is without having to redeploy. If it is only occuring on the deployed version, go into the <a href="https://console.cloud.google.com/logs/viewer" rel="nofollow">logging area of the Cloud Console</a> and expand the failing request to see the error code and problem code that you need to fix.</li>
</ol>
<p>A sample starter project with Flask can be found <a href="https://github.com/GoogleCloudPlatform/python-docs-samples/tree/master/appengine/standard/flask/hello_world" rel="nofollow">here</a>, which is also referenced in the <a href="https://cloud.google.com/appengine/docs/python/getting-started/python-standard-env" rel="nofollow">Getting Started docs for App Engine with Python</a>. Also, get your <a href="https://cloud.google.com/appengine/docs/python/tools/using-local-server" rel="nofollow">local development server running</a> if you haven't already.</p>
| 0 | 2016-10-11T04:42:58Z | [
"python",
"google-app-engine",
"flask",
"jinja2"
] |
matplotlib update plot in while-loop with dates as x-axis | 39,955,701 | <p>This might be obvious, so sorry in advance for this nooby question. I want to update a time series dynamically with matplotlib.pyplot. More precisely, I want to plot newly generated data in a while-loop. </p>
<p>This is my attempt so far:</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt; plt.ion()
import pandas as pd
import time
n = 100
x = np.NaN
y = np.NaN
df = pd.DataFrame(dict(time=x, value=y), index=np.arange(n)) # not neccessarily needed to have a pandas df here, but I like working with it.
# initialise plot and line
line, = plt.plot(df['time'], df['value'])
i=0
# simulate line drawing
while i <= len(df):
#generate random data point
newData = np.random.rand()
# extend the data frame by this data point and attach the current time as index
df.loc[i, "value"] = newData
df.loc[i, "time"] = pd.datetime.now()
# plot values against indices
line.set_data(df['time'][:i], df['value'][:i])
plt.draw()
plt.pause(0.001)
# add to iteration counter
i += 1
print(i)
</code></pre>
<p>This returns <code>TypeError: float() argument must be a string or a number, not 'datetime.datetime'</code>. But as far as I can remeber, matplotlib doesn't have any problems with plotting dates on the x-axis (?).</p>
<p>Many thanks.</p>
| 0 | 2016-10-10T09:55:20Z | 39,957,630 | <p>As Andras Deak pointed out, you should tell pandas explicitly that your <code>time</code> column is datetime. When you do <code>df.info()</code> at the end of your code, you will see that it takes <code>df['time']</code> as float64. You can achieve this with <code>df['time'] = pd.to_datetime(df['time'])</code>. </p>
<p>I was able to make your code run, but I had to add a few lines of code. I was running it in a iPython (Jupyter) console and without the two lines <code>autoscale_view</code> and <code>relim</code>, it was not updating the plot correctly. What's left to do is a nice formatting of the x-axis labels.</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt; plt.ion()
import pandas as pd
import time
n = 100
x = np.NaN
y = np.NaN
df = pd.DataFrame(dict(time=x, value=y), index=np.arange(n)) # not neccessarily needed to have a pandas df here, but I like working with it.
df['time'] = pd.to_datetime(df['time']) #format 'time' as datetime object
# initialise plot and line
fig = plt.figure()
axes = fig.add_subplot(111)
line, = plt.plot(df['time'], df['value'])
i=0
# simulate line drawing
while i <= len(df):
#generate random data point
newData = np.random.rand()
# extend the data frame by this data point and attach the current time as index
df.loc[i, "value"] = newData
df.loc[i, "time"] = pd.datetime.now()
# plot values against indices, use autoscale_view and relim to readjust the axes
line.set_data(df['time'][:i], df['value'][:i])
axes.autoscale_view(True,True,True)
axes.relim()
plt.draw()
plt.pause(0.01)
# add to iteration counter
i += 1
print(i)
</code></pre>
| 1 | 2016-10-10T11:51:33Z | [
"python",
"matplotlib",
"plot",
"while-loop"
] |
Send Persian string from C# server to python client with socket | 39,955,744 | <p>I use socket programming to connect a python program to a C# program.
python code is client and C# code is server. C# code send a string to python with this code:</p>
<pre><code>byte[] R=Encoding.UTF8.GetBytes("one string");
Client.Send(R);
</code></pre>
<p>and i receive data in python code with this:</p>
<pre><code>data=sock.recv(16)
amount_received+=len(data)
print >> sys.stderr, 'received "%s" %data
</code></pre>
<p>When i print recieved data: <code>print >> sys.stderr, 'received "%s" %data</code> , I just see some question marks.
what must I do?</p>
| 1 | 2016-10-10T09:57:56Z | 39,957,141 | <p>try </p>
<pre><code>byte[] R = Encoding.Default.GetBytes("Persian String");
</code></pre>
| 1 | 2016-10-10T11:23:41Z | [
"c#",
"python",
"sockets",
"encode"
] |
Python turning multiple objects into a dictionary | 39,955,844 | <p>I've got an Object which has a name and an indefinite amount of parameters (which is also an object with a name and a value)</p>
<p>I'm pretty new to python so this gets a bit over my head
I want to get all parameters and put them into a dictionary. My code looks like this:</p>
<pre><code>data = {}
for parameter in object.parameters:
parameter.__dict__
data.update({parameter})
</code></pre>
<p>But parameter.__dict__ doesn't work like I thought here.
Any ideas how i can make it work?</p>
<p>EDIT: Thanks it worked by using data.update(vars(parameter))</p>
| 0 | 2016-10-10T10:04:34Z | 39,958,428 | <p>By looking at your output it looks like you class structure is something like this</p>
<pre><code>class class1(object):
def __init__(self, p1, p2):
self.name = p1
self.value = p2
class class2(object):
def __init__(self):
self.parameters = [class1("param1", "value1"), class1("param2", "value2")]
obj = class2()
data = {}
</code></pre>
<p>So when we do </p>
<pre><code>for parameter in obj.parameters:
print(parameter.__dict__)
</code></pre>
<p>We get output</p>
<pre><code>{'value': 'value1', 'name': 'param1'}
{'value': 'value2', 'name': 'param2'}
</code></pre>
<p>So to get the desired output you will have to do something like</p>
<pre><code>for parameter in obj.parameters:
data[parameter.__dict__['name']] = parameter.__dict__['value']
print(data)
</code></pre>
<p>Which will give your desired output</p>
<pre><code>{'param2': 'value2', 'param1': 'value1'}
</code></pre>
| 0 | 2016-10-10T12:34:46Z | [
"python",
"dictionary"
] |
How to check if a file is empty avoid reading the whole file in a submit form? | 39,955,940 | <p>I am using django, and in a web submit form, I want to check if a uploading file is empty, but avoid uploading or reading the whole file to get the file size, because it might be huge and take time to calculate.</p>
| 0 | 2016-10-10T10:10:27Z | 39,956,020 | <p>You are probably looking for <a href="https://docs.python.org/2/library/os.html#os.stat" rel="nofollow">os.stat</a></p>
<p>os.stat(path)</p>
<blockquote>
<p>Perform the equivalent of a stat() system call on the given path.
(This function follows symlinks; to stat a symlink use lstat().)</p>
<p>The return value is an object whose attributes correspond to the
members of the stat structure, namely:</p>
<p>st_mode - protection bits,<br>
st_ino - inode number,<br>
st_dev - device,<br>
st_nlink - number of hard links,<br>
st_uid - user id of owner,<br>
st_gid -
group id of owner,<br>
<strong>st_size - size of file, in bytes</strong>,</p>
</blockquote>
<p>so you just do</p>
<pre><code>import os
os.stat('/uploaded/file/path')
</code></pre>
| 2 | 2016-10-10T10:15:39Z | [
"python",
"django",
"web"
] |
How to check if a file is empty avoid reading the whole file in a submit form? | 39,955,940 | <p>I am using django, and in a web submit form, I want to check if a uploading file is empty, but avoid uploading or reading the whole file to get the file size, because it might be huge and take time to calculate.</p>
| 0 | 2016-10-10T10:10:27Z | 39,956,051 | <pre><code>import os
>>> os.stat("file").st_size == 0
True
</code></pre>
<p>by using this code you can check file is empty or not </p>
| 2 | 2016-10-10T10:17:31Z | [
"python",
"django",
"web"
] |
flask importerrorï¼ cannot import name storage | 39,956,099 | <p>I try to use flask-cloudy to uploads files, but I can't import storage (a model in flask-cloudy)
this is how I config it :</p>
<pre><code>class DevelopmentConfig():
DEBUG = True
SECRET_KEY = 'I_will_never_told_you'
STORAGE_PROVIDER = "LOCAL"
STORAGE_CONTAINER = "./data"
STORAGE_KEY = ""
STORAGE_SECRET = ""
STORAGE_SERVER = True
</code></pre>
<p>and I initialise it in app/<strong>init</strong>.py :</p>
<pre><code>from flask import Flask, redirect, request, url_for, g
from .main import main as main_blueprint
from .auth import auth as auth_blueprint
from config import DevelopmentConfig
from flask_login import LoginManager
from flask_cloudy import Storage #import Storage
login_manager = LoginManager()
login_manager.session_protection = 'strong'
login_manager.login_view = 'auth.login'
def create_app():
app = Flask(__name__)
app.config.from_object(DevelopmentConfig)
app.register_blueprint(main_blueprint)
app.register_blueprint(auth_blueprint, url_prefix='/auth')
login_manager.init_app(app)
storage = Storage()
storage.init_app(app) #initialise it
@login_manager.user_loader
def load_user(user_id):
from .models import User
try:
user = User.get(User.id == int(user_id))
except User.DoesNotExist:
user = None
return user
@login_manager.unauthorized_handler
def unauthorized_callback():
return redirect(url_for('auth.login'))
return app
</code></pre>
<p>then I try to import storage in app/main/views.py:
I had try </p>
<pre><code>from app import storage
</code></pre>
<p>and</p>
<pre><code>from .. import storage
</code></pre>
<p>and </p>
<pre><code>from ..__init__ import storage
</code></pre>
<p>but it still can't work well
when I use <code>from app import storage</code> and <code>from .. import storage</code>
it grow up like this : </p>
<pre><code>Traceback (most recent call last):
File "run.py", line 1, in <module>
from app import create_app
File "/home/lc/workspace/homeworkAdminSystem/app/__init__.py", line 2, in <module>
from .main import main as main_blueprint
File "/home/lc/workspace/homeworkAdminSystem/app/main/__init__.py", line 5, in <module>
from . import views, errors
File "/home/lc/workspace/homeworkAdminSystem/app/main/views.py", line 5, in <module>
from .. import storage
ImportError: cannot import name storage
</code></pre>
<p>and when I tryed <code>from ..__init__ import storage</code>
it appear :</p>
<pre><code>Traceback (most recent call last):
File "run.py", line 1, in <module>
from app import create_app
File "/home/lc/workspace/homeworkAdminSystem/app/__init__.py", line 2, in <module>
from .main import main as main_blueprint
File "/home/lc/workspace/homeworkAdminSystem/app/main/__init__.py", line 5, in <module>
from . import views, errors
File "/home/lc/workspace/homeworkAdminSystem/app/main/views.py", line 6, in <module>
from ..__init__ import storage
File "/home/lc/workspace/homeworkAdminSystem/app/__init__.py", line 3, in <module>
from .auth import auth as auth_blueprint
File "/home/lc/workspace/homeworkAdminSystem/app/auth/__init__.py", line 5, in <module>
from . import views
File "/home/lc/workspace/homeworkAdminSystem/app/auth/views.py", line 4, in <module>
from ..models import db, User, Homework, Score
File "/home/lc/workspace/homeworkAdminSystem/app/models.py", line 3, in <module>
from .__init__ import login_manager
ImportError: cannot import name login_manager
</code></pre>
<p>and here is my models(app/models) in it I used <code>from .__init__ import login_manager</code> but it worked well, so I am confuse of it ,so how can I import storage in my views.py?</p>
| 1 | 2016-10-10T10:21:14Z | 39,959,951 | <p>You need to put your storage initialisation outside of the <code>create_app</code> function.</p>
<p>The <code>storage</code> variable right now is only accessible inside the <code>create_app</code> function. </p>
| 0 | 2016-10-10T13:54:00Z | [
"python",
"flask",
"flask-extensions"
] |
hangman: UnboundLocalError: local variable referenced before assignment | 39,956,149 | <p>I made a program to play hangman. I got pretty far but no matter how many times i try to fix it or make a different variation, the shell just comes up with the same thing.</p>
<p><code>UnboundLocalError: local variable '' referenced before assignment.
</code></p>
<p>I'm fairly new so can you make the answers as simple as possible. (or just a de-bugged version). </p>
<pre><code>import random
tries = 12
def intro ():
print ('the size of your word is '+str(size))
print ('you have ' + str(tries) + ' tries')
# word == car output == '***'
print (output)
def guesses ():
guess = ('it')
while len(guess) > 1:
guess = str(input('pick a letter '))
if guess not in word:
print ('incorrect')
tries = tries - 1
print ('you have ' + str(tries) + ' tries')
if guess in word:
print ('correct!!')
tries = tries - 1
position = word.index(guess)
output = output[:position] + guess + output[position+1:]
print ('you have ' + str(tries) + ' tries')
print ('this is a game of hangman where you get a word')
print ('that you have to guess letter by letter')
print ('')
print ('')
word_list = ['jazz', 'whale', 'surgery', 'love']
word = random.choice(word_list)
size = len(word)
output = '*' * size
intro ()
while output != word or tries != 0:
guesses ()
print (output)
</code></pre>
| -2 | 2016-10-10T10:24:58Z | 39,956,337 | <p>I think you are missing a <strong>global</strong> statement such as</p>
<pre><code>def guesses ():
global tries
#... some of your code...
#and now this line will work! :)
tries = tries - 1
</code></pre>
<p>this kind of error usually comes up when you see code like this:</p>
<pre><code>def f():
x = x + 1
</code></pre>
<p>without a <strong>global</strong> statement </p>
<p>That said - try not to use <strong>global</strong> at all but to pass parameters to the function such as :</p>
<pre><code>def guesses (tries):
#now tries is a local variable and the next line works
tries = tries - 1
</code></pre>
| -1 | 2016-10-10T10:36:20Z | [
"python",
"debugging"
] |
hangman: UnboundLocalError: local variable referenced before assignment | 39,956,149 | <p>I made a program to play hangman. I got pretty far but no matter how many times i try to fix it or make a different variation, the shell just comes up with the same thing.</p>
<p><code>UnboundLocalError: local variable '' referenced before assignment.
</code></p>
<p>I'm fairly new so can you make the answers as simple as possible. (or just a de-bugged version). </p>
<pre><code>import random
tries = 12
def intro ():
print ('the size of your word is '+str(size))
print ('you have ' + str(tries) + ' tries')
# word == car output == '***'
print (output)
def guesses ():
guess = ('it')
while len(guess) > 1:
guess = str(input('pick a letter '))
if guess not in word:
print ('incorrect')
tries = tries - 1
print ('you have ' + str(tries) + ' tries')
if guess in word:
print ('correct!!')
tries = tries - 1
position = word.index(guess)
output = output[:position] + guess + output[position+1:]
print ('you have ' + str(tries) + ' tries')
print ('this is a game of hangman where you get a word')
print ('that you have to guess letter by letter')
print ('')
print ('')
word_list = ['jazz', 'whale', 'surgery', 'love']
word = random.choice(word_list)
size = len(word)
output = '*' * size
intro ()
while output != word or tries != 0:
guesses ()
print (output)
</code></pre>
| -2 | 2016-10-10T10:24:58Z | 39,956,357 | <p>For starters, <code>output</code> is undefined. Note that you never assign to, or otherwise define <code>output</code> before you use it.
Second, I can't help but to notice you try to use names defined inside of a function outside of it. There are two problems with this:</p>
<ul>
<li><p>Names defined inside of a function do not belong to the global scope </p></li>
<li><p>Even if they did, function <code>guesses</code> executes after you've tried to use an undefined name <code>guess</code></p></li>
</ul>
<p>Take a look at <a href="https://docs.python.org/3/reference/executionmodel.html" rel="nofollow">this</a>.
I know coding is fun and it's tempting to start writing right away, but If this is your first programming language, don't rush it. If you go slowly and get the hang of Python ( or any other language, excluding some esoteric languages ), you'll be able to transition to any other language easily. Take it slow!</p>
| 0 | 2016-10-10T10:37:32Z | [
"python",
"debugging"
] |
hangman: UnboundLocalError: local variable referenced before assignment | 39,956,149 | <p>I made a program to play hangman. I got pretty far but no matter how many times i try to fix it or make a different variation, the shell just comes up with the same thing.</p>
<p><code>UnboundLocalError: local variable '' referenced before assignment.
</code></p>
<p>I'm fairly new so can you make the answers as simple as possible. (or just a de-bugged version). </p>
<pre><code>import random
tries = 12
def intro ():
print ('the size of your word is '+str(size))
print ('you have ' + str(tries) + ' tries')
# word == car output == '***'
print (output)
def guesses ():
guess = ('it')
while len(guess) > 1:
guess = str(input('pick a letter '))
if guess not in word:
print ('incorrect')
tries = tries - 1
print ('you have ' + str(tries) + ' tries')
if guess in word:
print ('correct!!')
tries = tries - 1
position = word.index(guess)
output = output[:position] + guess + output[position+1:]
print ('you have ' + str(tries) + ' tries')
print ('this is a game of hangman where you get a word')
print ('that you have to guess letter by letter')
print ('')
print ('')
word_list = ['jazz', 'whale', 'surgery', 'love']
word = random.choice(word_list)
size = len(word)
output = '*' * size
intro ()
while output != word or tries != 0:
guesses ()
print (output)
</code></pre>
| -2 | 2016-10-10T10:24:58Z | 39,958,351 | <p>Apart for your snippet's indentation being off (remember that in python indentation is part of the syntax so take care about this when posting snippets), your main problem is with global vs local namespace. </p>
<p>The global namespace holds "top level" names (names defined at the top level of your script / module, IOW outside a function), the local namespace ("local" to a function's body) holds names defined within the function's body <em>and</em> the function's arguments if any. </p>
<p>When a name is used <em>but not defined</em> within a function's body, it is looked up in the global namespace, so a function can access names that have not been explicitely defined in it's local namespace. </p>
<p><strong>BUT</strong> - and here comes the tricky part: "defined within the function's body" means there is an assignment to that name within the function (using one of "=", "+=", "-=", "/=" etc) <em>anywhere</em> in the function's body - the fact that there's a synonym in the global namespace doesn't magically make the name global, so if you really want to assign to a global name within a function (which is almost always a very bad idea, google "globals evil" for more on this), you have to <em>explicitely</em> tell Python this name should be considered global using the <code>global</code> statement, ie:</p>
<pre><code>bar = 42
def foo():
global bar
bar = "baaz"
</code></pre>
<p>Trying to assign to global name without declaring it as global will always make the name local. If you don't try to access that name before the assignement, you will have no explicit error (the program is technically correct) but you may not have the expected result since the global name won't be affected (which a logical error, and usually harder to debug), ie:</p>
<pre><code>>>> baaz = 42
>>> def foo():
... baaz = 84
...
>>> print(baaz)
42
>>> foo()
>>> print baaz
42
>>>
</code></pre>
<p>But if you try to access the name before the line where it's defined, you will get this <code>UnboundLocalError</code>, because (by definition) before the assignment the (local) name is not bound to any value:</p>
<pre><code>>>> baaz = 42
>>> def foo():
... print(baaz) # wont print the global 'baaz' but raise an UnboundLocalError
... baaz = 84 # because this line defines `baaz` as a local
...
>>> foo()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in foo
UnboundLocalError: local variable 'baaz' referenced before assignment
</code></pre>
<p>Now you can check your own code and find the at least three places where you <em>do</em> have this pattern (hint: in assignments, the right hand side of the <code>=</code> symbol is executed <em>before</em> the assignment itself).</p>
<p>You <em>could</em> (technically) "solve" this using the <code>global</code> statement but this is definitly <em>not</em> the right thing to do, at least if you hope to learn to write good (ie: readable, maintainable) code. </p>
<p>The good news is that you actually almost never have to modify a global variable (and I'm saying this from years of experience writing / maintaining real life full-blown applications) - you just have to 1/ pass relevant arguments to your functions and 2/ return relevant values from your functions. The top-level code of your scripts / module should only contains imports and functions / classes / constants defitions, and if it's a script a "main" function and a call to this function.</p>
<p>As an example here's a quick rewrite of your script without a single global variable - there's still a lot of room for improvement but at least it works, and it works without globals:</p>
<pre><code>import random
def intro(tries, size):
print ('the size of your word is {}'.format(size))
print ('you have {} tries'.format(tries))
def guesses(word, tries, output):
guess = ('it')
while len(guess) > 1:
guess = str(raw_input('pick a letter '))
if guess not in word:
print('incorrect')
tries = tries - 1
print('you have {} tries'.format(tries))
else:
print('correct!!')
tries = tries - 1
print('you have {} tries'.format(tries))
position = word.index(guess)
output = output[:position] + guess + output[position+1:]
return tries, output
def main():
print ('this is a game of hangman where you get a word')
print ('that you have to guess letter by letter')
print ('')
print ('')
word_list = ['jazz', 'whale', 'surgery', 'love']
word = random.choice(word_list)
size = len(word)
output = '*' * size
tries = 12
intro(tries, size)
while not (output == word or tries == 0):
tries, output = guesses(word, tries, output)
print(output)
main()
</code></pre>
| 0 | 2016-10-10T12:30:23Z | [
"python",
"debugging"
] |
Vectorise Python code | 39,956,313 | <p>I have coded a kriging algorithm but I find it quite slow. Especially, do you have an idea on how I could vectorise the piece of code in the cons function below:</p>
<pre><code>import time
import numpy as np
B = np.zeros((200, 6))
P = np.zeros((len(B), len(B)))
def cons():
time1=time.time()
for i in range(len(B)):
for j in range(len(B)):
P[i,j] = corr(B[i], B[j])
time2=time.time()
return time2-time1
def corr(x,x_i):
return np.exp(-np.sum(np.abs(np.array(x) - np.array(x_i))))
time_av = 0.
for i in range(30):
time_av+=cons()
print "Average=", time_av/100.
</code></pre>
<hr>
<p>Edit: Bonus questions</p>
<ol>
<li>What happens to the broadcasting solution if I want <code>corr(B[i], C[j])</code> with C the same dimension than B</li>
<li><p>What happens to the scipy solution if my p-norm orders are an array:</p>
<pre><code>p=np.array([1.,2.,1.,2.,1.,2.])
def corr(x, x_i):
return np.exp(-np.sum(np.abs(np.array(x) - np.array(x_i))**p))
</code></pre>
<p>For 2., I tried <code>P = np.exp(-cdist(B, C,'minkowski', p))</code> but scipy is expecting a scalar.</p></li>
</ol>
| 3 | 2016-10-10T10:35:21Z | 39,956,406 | <p>Your problem seems very simple to vectorize. For each pair of rows of <code>B</code> you want to compute</p>
<pre><code>P[i,j] = np.exp(-np.sum(np.abs(B[i,:] - B[j,:])))
</code></pre>
<p>You can make use of array broadcasting and introduce a third dimension, summing along the last one:</p>
<pre><code>P2 = np.exp(-np.sum(np.abs(B[:,None,:] - B),axis=-1))
</code></pre>
<p>The idea is to reshape the first occurence of <code>B</code> to shape <code>(N,1,M)</code> while the second <code>B</code> is left with shape <code>(N,M)</code>. With array broadcasting, the latter is equivalent to <code>(1,N,M)</code>, so</p>
<pre><code>B[:,None,:] - B
</code></pre>
<p>is of shape <code>(N,N,M)</code>. Summing along the last index will then result in the <code>(N,N)</code>-shape correlation array you're looking for.</p>
<hr>
<p>Note that if you were using <code>scipy</code>, you would be able to do this using <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.cdist.html" rel="nofollow"><code>scipy.spatial.distance.cdist</code></a> (or, equivalently, a combination of <code>scipy.spatial.distance.pdist</code> and <code>scipy.spatial.distance.squareform</code>), without unnecessarily computing the lower triangular half of this symmetrix matrix. Using <a href="http://stackoverflow.com/users/3293881/divakar">@Divakar</a>'s suggestion in comments for the simplest solution this way:</p>
<pre><code>from scipy.spatial.distance import cdist
P3 = 1/np.exp(cdist(B, B, 'minkowski',1))
</code></pre>
<p><code>cdist</code> will compute the Minkowski distance in 1-norm, which is exactly the sum of the absolute values of coordinate differences.</p>
| 4 | 2016-10-10T10:40:50Z | [
"python",
"numpy",
"vectorization"
] |
Django DRF serializer on PrimaryKeyRelatedField | 39,956,348 | <p>Question about PrimaryKeyRelatedField serialization in Django DRF version 3.4.7.</p>
<h1>models</h1>
<pre><code>class UserModel(AbstractEmailUser):
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self):
return str(self.email)
class Conversation(models.Model):
admin = models.ForeignKey('UserModel', db_index=True, related_name='admin_user')
patient = models.ForeignKey('UserModel', db_index=True)
subject = models.CharField(max_length=255, db_index=True)
user_reply = models.BooleanField(default=False)
admin_seen = models.BooleanField(default=False)
expire = models.DateTimeField()
conversation_type = models.ForeignKey('ConversationType', db_index=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self):
return str(self.admin)
class ConversationMessages(models.Model):
text = models.TextField(db_index=True)
conversation = models.ForeignKey('Conversation', db_index=True, related_name='msg_conv')
user = models.ForeignKey('UserModel', db_index=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self):
return str(self.user)
class ConversationFiles(models.Model):
message = models.ForeignKey('ConversationMessages', db_index=True, related_name='message')
file = models.FileField(upload_to='conversations', db_index=True)
def __str__(self):
return str(self.user)
</code></pre>
<p>Every model has related field for Rest Framework.
Logic is create conversation, then take ID from conversation and save message model.</p>
<h1>serialize's</h1>
<pre><code>class MessagesSerializer(serializers.ModelSerializer):
text = serializers.CharField(required=False)
conversation = serializers.PrimaryKeyRelatedField(queryset=Conversation.objects.all(), required=False)
user = serializers.PrimaryKeyRelatedField(queryset=UserModel.objects.all(), required=False)
class Meta:
model = ConversationMessages
class ConversationSerializer(serializers.ModelSerializer):
admin = serializers.PrimaryKeyRelatedField(queryset=UserModel.objects.all(), required=False)
msg_conv = MessagesSerializer()
class Meta:
model = Conversation
def create(self, validated_data):
msg_conv = validated_data.pop('msg_conv', None)
admin_user = Conversation.objects.create(**validated_data)
ConversationMessages.objects.create(conversation_id=Conversation.objects.get(id=admin_user.id).id, **msg_conv)
return admin_user
</code></pre>
<p>Serializer is problem on POST method. Everything works great POST object create data in database, but problem is when serializer save object i get this message: <strong>'RelatedManager' object has no attribute 'conversation'</strong>.</p>
<h1>View</h1>
<pre><code>class ConversationView(APIView):
authentication_classes = (JSONWebTokenAuthentication,)
@parser_classes((FormParser, MultiPartParser, FileUploadParser))
def post(self, request):
admin = request.user.id
data = request.data
my_time = datetime.datetime.strptime('07/05/15', '%m/%d/%y')
my_time = my_time.replace(hour=23, minute=59)
data['admin'] = admin
data['expire'] = my_time
data['msg_conv']['user'] = admin
serializer = ConversationSerializer(data=data)
if serializer.is_valid():
serializer.save()
return Response(data={'success': True, 'user': serializer.data}, status=status.HTTP_200_OK)
else:
return Response(data={'success': False, 'msg': serializer.errors}, status=status.HTTP_400_BAD_REQUEST)
</code></pre>
<h1>POST json</h1>
<pre><code>{
"subject":"aloha",
"conversation_type":1,
"patient":3,
"msg_conv":{
"text":"ovo je neki teks"
}
}
</code></pre>
<p>Can't figure out how to return data from serializer to view.</p>
<p>Django version : 1.10.2
Python: 3.4.3</p>
| 0 | 2016-10-10T10:36:59Z | 39,957,989 | <p>The issue is there:</p>
<pre><code>class ConversationSerializer(serializers.ModelSerializer):
msg_conv = MessagesSerializer()
</code></pre>
<p>By doing this, you are saying that <code>Conversation</code> has a FK to <code>Message</code>. Therefore DRF tries to do the mapping and fails because it's the oposit.</p>
<p>You just need to add the <code>many=True</code> argument to let DRF knows this is a reversed FK.</p>
| 1 | 2016-10-10T12:10:01Z | [
"python",
"json",
"django",
"serialization",
"django-rest-framework"
] |
aiohttp how to log access log? | 39,956,400 | <p>I am trying to get a basic logger for aiohttp working, but there are simply no log messages being logged. Note_ logging custom messages works as expected.</p>
<pre><code>async def main_page(request: web.Request):
return "hello world"
def setup_routes(app):
app.router.add_get('/', main_page)
async def init(loop):
# load config from yaml file in current dir
conf = load_config(str(pathlib.Path('.') / 'async_config.yml'))
# setup application and extensions
app = web.Application(loop=loop)
# setup views and routes
setup_routes(app)
host, port = conf['host'], conf['port']
app['gmt_file'] = _get_gmt_file()
return app, host, port
LOG_FORMAT = '%a %l %u %t "%r" %s %b "%{Referrer}i" "%{User-Agent}i"'
log_file = "log.text"
handler = handlers.TimedRotatingFileHandler(log_file, when='midnight',
backupCount=5)
handler.setLevel(logging.DEBUG)
formatter = logging.Formatter(LOG_FORMAT)
handler.setFormatter(formatter)
handler.name = "file_log"
loop = asyncio.get_event_loop()
app, host, port = loop.run_until_complete(init(loop))
logging.getLogger("aiohttp").addHandler(handler)
# todo host ziehen per aiohttp methods, so we are externally visible.
web.run_app(app, host=host, port=port)
</code></pre>
| 1 | 2016-10-10T10:40:11Z | 39,979,270 | <p><code>LOG_FORMAT</code> should be "%s" if any.
<code>'%a %l %u %t "%r" %s %b "%{Referrer}i" "%{User-Agent}i"'</code> is a valid parameter for <code>.make_handler(access_log_format=...)</code> call, not <code>logging.Formatter</code>.</p>
<p>As first step I suggest setting up root logger and after that going down to error/access logs.
Perhaps access log worth own private file like <code>access.log</code>. To achieving this you need to setup a handler for <code>aiohttp.access</code> logger, not for top-level <code>aiohttp</code>.</p>
| 0 | 2016-10-11T14:12:35Z | [
"python",
"aiohttp"
] |
Python argparse - arguments strip off when bash special character is passed as argument | 39,956,435 | <p>I writing CLI tool using argparse.</p>
<p>Below is my code snippet:</p>
<pre><code>parser.ArgumentParser()
parser.add_argument('--username')
parser.add_argument('--password')
args = parser.parse_args()
print(args.password)
</code></pre>
<p>I run the script on my Mac:</p>
<p><code>>>> prog.py --username xyz --password abc$xyz</code></p>
<p>Output:</p>
<p><code>>>> abc</code></p>
<p>I know it's bash shell that interprets '$xyz' as a bash variable and tries to substitute '$xyz'</p>
<p>Is there are way I can get around this without enclosing the password in quotes? </p>
| 1 | 2016-10-10T10:42:23Z | 39,956,503 | <p>You can put a backslash in front of the <code>$</code>: <code>prog.py --username xyz --password abc\$xyz</code>.</p>
<p>Otherwise, no. You correctly observed that it is bash that is doing this so, by the time Python/argparse receives the command, there is nothing that can be done.</p>
| -1 | 2016-10-10T10:46:02Z | [
"python",
"bash",
"argparse"
] |
Simpy Resource : Get ID? | 39,956,444 | <p>I have two airport runways as a Simpy Resource:</p>
<pre><code>runway = simpy.Resource(env, capacity=2) # two runways
</code></pre>
<p>This works all fine, but how can I access the runway id (1 or 2) so that I can have an output such as 'Plane #1 taking off from runway #1'?</p>
| 0 | 2016-10-10T10:42:47Z | 39,971,073 | <p>You canât (officially). Internally, the slots are just a list so you could in theory use the list index of the Request.</p>
<p>Alternatively, you might use <code>Store</code> and put two "Runway" objects into it. These objects have (of course) an ID an can also carry additional information (whatever you can imagine).</p>
| 0 | 2016-10-11T05:38:00Z | [
"python",
"simpy"
] |
Django Patch Side effect IntegrityError not being raised | 39,956,479 | <p>I have the following view, which excepts POST requests, and serializes an objects data (a Draftschedule) to create a new copy (a FrozenSchedule):</p>
<pre><code>from reports.tasks import create_frozen_schedule
def freeze_schedule(request, pk):
"""Valid post request will freeze a Draft Schedule serializing its data"""
client = get_object_or_404(Client, draftschedule=pk)
try:
# Serialize data into a FrozenSchedule object
frozenschedule = create_frozen_schedule(pk, request.user.id)
except IntegrityError:
# Warn user if action failed
messages.warning(request, "A Schedule of this Type already exists")
return redirect(client.draftschedule)
else:
# If Schedule is Frozen successfully
messages.success(request, "Schedule Frozen")
return redirect(frozenschedule)
</code></pre>
<p>I'm trying to write a test to assert certain things happen after an IntegrityError is raised. I'm struggling to understand why it's failing, it's not immediately obvious to me where I'm going wrong since I'm fairly inexperienced with mocking / patching.</p>
<p>I've tried to mock the <code>create_frozen_schedule</code> function to raise an IntegrityError when called:</p>
<pre><code>def setUp(self):
self.url = reverse(
'reports:draftschedule-freeze',
args=[self._client.draftschedule.pk]
)
super(TestFreezeSchedule, self).setUp()
@patch('reports.tasks.create_frozen_schedule')
def test_freeze_schedule_with_conflict(self, mock_freeze):
mock_freeze.side_effect = IntegrityError
with self.assertRaises(IntegrityError):
self.client.post(self.url)
# More unit tests following same premise...
</code></pre>
<p>But I end up with the following error:</p>
<pre><code>.......................................................................................F............
======================================================================
FAIL: test_freeze_schedule_with_conflict (reports.tests.test_views.TestFreezeSchedule)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/usr/lib/python3.4/unittest/mock.py", line 1136, in patched
return func(*args, **keywargs)
File "/home/jwe/piesup2/reports/tests/test_views.py", line 495, in test_freeze_schedule_with_conflict
self.client.post(self.url)
AssertionError: IntegrityError not raised
----------------------------------------------------------------------
</code></pre>
<p>Points to note:</p>
<ul>
<li>I'm able to replicate this error outside of tests on my actual Django site.</li>
<li>I've purposely omitted the <code>create_frozen_schedule</code> code since the
serialization is quite long-winded and it's my understanding that the
implementation details shouldn't matter anyway since I'm mocking the
function.</li>
<li><p>The purpose of the IntegrityError itself is to prevent duplicate <code>FrozenSchedule</code> objects, whose Meta class looks as follows: </p>
<pre><code>class Meta:
# ...
unique_together = ('client', 'data',)
</code></pre></li>
</ul>
<p>Any ideas why the side effect isn't being raised?</p>
| 0 | 2016-10-10T10:44:45Z | 39,956,582 | <p>Your view catches IntegrityError and returns a redirect. The client post, which is what your test calls, doesn't raise an error at all.</p>
<p>Rather, you should be testing that the actions in the except block happen: is the warning set, and does the post redirect to the draft schedule instead of the frozen one.</p>
| 1 | 2016-10-10T10:50:48Z | [
"python",
"django",
"mocking"
] |
Seaching big files using list in Python - How can improve the speed? | 39,956,510 | <p>I have a folder with 300+ .txt files with total size of 15GB+. These files contain tweets. Each line is a different tweet. I have a list of keywords I'd like to search the tweets for. I have created a script that searches each line of every file for every item on my list. If the tweet contains the keyword, then it writes the line into another file. This is my code: </p>
<pre><code># Search each file for every item in keywords
print("Searching the files of " + filename + " for the appropriate keywords...")
for file in os.listdir(file_path):
f = open(file_path + file, 'r')
for line in f:
for key in keywords:
if re.search(key, line, re.IGNORECASE):
db.write(line)
</code></pre>
<p>This is the format each line has: </p>
<pre><code>{"created_at":"Wed Feb 03 06:53:42 +0000 2016","id":694775753754316801,"id_str":"694775753754316801","text":"me with Dibyabhumi Multiple College students https:\/\/t.co\/MqmDwbCDAF","source":"\u003ca href=\"http:\/\/www.facebook.com\/twitter\" rel=\"nofollow\"\u003eFacebook\u003c\/a\u003e","truncated":false,"in_reply_to_status_id":null,"in_reply_to_status_id_str":null,"in_reply_to_user_id":null,"in_reply_to_user_id_str":null,"in_reply_to_screen_name":null,"user":{"id":5981342,"id_str":"5981342","name":"Lava Kafle","screen_name":"lkafle","location":"Kathmandu, Nepal","url":"http:\/\/about.me\/lavakafle","description":"@deerwalkinc 24000+ tweeps bigdata #Team #Genomics http:\/\/deerwalk.com #Genetic #Testing #population #health #management #BigData #Analytics #java #hadoop","protected":false,"verified":false,"followers_count":24742,"friends_count":23169,"listed_count":1481,"favourites_count":147252,"statuses_count":171880,"created_at":"Sat May 12 04:49:14 +0000 2007","utc_offset":20700,"time_zone":"Kathmandu","geo_enabled":true,"lang":"en","contributors_enabled":false,"is_translator":false,"profile_background_color":"EDECE9","profile_background_image_url":"http:\/\/abs.twimg.com\/images\/themes\/theme3\/bg.gif","profile_background_image_url_https":"https:\/\/abs.twimg.com\/images\/themes\/theme3\/bg.gif","profile_background_tile":false,"profile_link_color":"088253","profile_sidebar_border_color":"FFFFFF","profile_sidebar_fill_color":"E3E2DE","profile_text_color":"634047","profile_use_background_image":true,"profile_image_url":"http:\/\/pbs.twimg.com\/profile_images\/677805092859420672\/kzoS-GZ__normal.jpg","profile_image_url_https":"https:\/\/pbs.twimg.com\/profile_images\/677805092859420672\/kzoS-GZ__normal.jpg","profile_banner_url":"https:\/\/pbs.twimg.com\/profile_banners\/5981342\/1416802075","default_profile":false,"default_profile_image":false,"following":null,"follow_request_sent":null,"notifications":null},"geo":null,"coordinates":null,"place":null,"contributors":null,"is_quote_status":false,"retweet_count":0,"favorite_count":0,"entities":{"hashtags":[],"urls":[{"url":"https:\/\/t.co\/MqmDwbCDAF","expanded_url":"http:\/\/fb.me\/Yj1JW9bJ","display_url":"fb.me\/Yj1JW9bJ","indices":[45,68]}],"user_mentions":[],"symbols":[]},"favorited":false,"retweeted":false,"possibly_sensitive":false,"filter_level":"low","lang":"en","timestamp_ms":"1454482422661"}
</code></pre>
<p>The script works but <strong>it takes a lot of time</strong>. For ~40 keywords it needs more than 2 hours. Obviously my code is not optimized. What can I do to improve the speed? </p>
<p>p.s. I have read some relevant questions regarding searching and speed but I suspect that the problem in my script lies in the fact that I'm using a list for the keywords. I've tried some of the suggested solutions but to no avail. </p>
| 1 | 2016-10-10T10:46:29Z | 39,956,830 | <h2>1) External library</h2>
<p>If you're willing to lean on external libraries (and time to execute is more important than the one-off time cost to install), you might be able to gain some speed by loading each file into a simple Pandas DataFrame and performing the keyword search as a vector operation. To get the matching tweets, you would do something like:</p>
<pre><code>import pandas as pd
dataframe_from_text = pd.read_csv("/path/to/file.txt")
matched_tweets_index = dataframe_from_text.str.match("keyword_a|keyword_b")
dataframe_from_text[matched_tweets_index] # Uses the boolean search above to filter the full dataframe
# You'd then have a mini dataframe of matching tweets in `dataframe_from_text`.
# You could loop through these to save them out to a file using the `.to_dict(orient="records")` format.
</code></pre>
<p>Dataframe operations within Pandas can be really quick so might be worth investigating.</p>
<h2>2) Group your regex</h2>
<p>Looks like you're not logging which keyword you matched against. If this is true, you could group your keywords into a single regex query like so:</p>
<pre><code>for line in f:
keywords_combined = "|".join(keywords)
if re.search(keywords_combined, line, re.IGNORECASE):
db.write(line)
</code></pre>
<p>I've not tested this but by reducing the number of loops per line, that could trim some time off.</p>
| 1 | 2016-10-10T11:05:34Z | [
"python",
"list",
"python-3.x",
"search",
"twitter"
] |
Seaching big files using list in Python - How can improve the speed? | 39,956,510 | <p>I have a folder with 300+ .txt files with total size of 15GB+. These files contain tweets. Each line is a different tweet. I have a list of keywords I'd like to search the tweets for. I have created a script that searches each line of every file for every item on my list. If the tweet contains the keyword, then it writes the line into another file. This is my code: </p>
<pre><code># Search each file for every item in keywords
print("Searching the files of " + filename + " for the appropriate keywords...")
for file in os.listdir(file_path):
f = open(file_path + file, 'r')
for line in f:
for key in keywords:
if re.search(key, line, re.IGNORECASE):
db.write(line)
</code></pre>
<p>This is the format each line has: </p>
<pre><code>{"created_at":"Wed Feb 03 06:53:42 +0000 2016","id":694775753754316801,"id_str":"694775753754316801","text":"me with Dibyabhumi Multiple College students https:\/\/t.co\/MqmDwbCDAF","source":"\u003ca href=\"http:\/\/www.facebook.com\/twitter\" rel=\"nofollow\"\u003eFacebook\u003c\/a\u003e","truncated":false,"in_reply_to_status_id":null,"in_reply_to_status_id_str":null,"in_reply_to_user_id":null,"in_reply_to_user_id_str":null,"in_reply_to_screen_name":null,"user":{"id":5981342,"id_str":"5981342","name":"Lava Kafle","screen_name":"lkafle","location":"Kathmandu, Nepal","url":"http:\/\/about.me\/lavakafle","description":"@deerwalkinc 24000+ tweeps bigdata #Team #Genomics http:\/\/deerwalk.com #Genetic #Testing #population #health #management #BigData #Analytics #java #hadoop","protected":false,"verified":false,"followers_count":24742,"friends_count":23169,"listed_count":1481,"favourites_count":147252,"statuses_count":171880,"created_at":"Sat May 12 04:49:14 +0000 2007","utc_offset":20700,"time_zone":"Kathmandu","geo_enabled":true,"lang":"en","contributors_enabled":false,"is_translator":false,"profile_background_color":"EDECE9","profile_background_image_url":"http:\/\/abs.twimg.com\/images\/themes\/theme3\/bg.gif","profile_background_image_url_https":"https:\/\/abs.twimg.com\/images\/themes\/theme3\/bg.gif","profile_background_tile":false,"profile_link_color":"088253","profile_sidebar_border_color":"FFFFFF","profile_sidebar_fill_color":"E3E2DE","profile_text_color":"634047","profile_use_background_image":true,"profile_image_url":"http:\/\/pbs.twimg.com\/profile_images\/677805092859420672\/kzoS-GZ__normal.jpg","profile_image_url_https":"https:\/\/pbs.twimg.com\/profile_images\/677805092859420672\/kzoS-GZ__normal.jpg","profile_banner_url":"https:\/\/pbs.twimg.com\/profile_banners\/5981342\/1416802075","default_profile":false,"default_profile_image":false,"following":null,"follow_request_sent":null,"notifications":null},"geo":null,"coordinates":null,"place":null,"contributors":null,"is_quote_status":false,"retweet_count":0,"favorite_count":0,"entities":{"hashtags":[],"urls":[{"url":"https:\/\/t.co\/MqmDwbCDAF","expanded_url":"http:\/\/fb.me\/Yj1JW9bJ","display_url":"fb.me\/Yj1JW9bJ","indices":[45,68]}],"user_mentions":[],"symbols":[]},"favorited":false,"retweeted":false,"possibly_sensitive":false,"filter_level":"low","lang":"en","timestamp_ms":"1454482422661"}
</code></pre>
<p>The script works but <strong>it takes a lot of time</strong>. For ~40 keywords it needs more than 2 hours. Obviously my code is not optimized. What can I do to improve the speed? </p>
<p>p.s. I have read some relevant questions regarding searching and speed but I suspect that the problem in my script lies in the fact that I'm using a list for the keywords. I've tried some of the suggested solutions but to no avail. </p>
| 1 | 2016-10-10T10:46:29Z | 39,956,886 | <p><strong>Why it's slow</strong></p>
<p>You are regex searching through a json dump, which is not always a good idea. For example, if you keywords include words like user, time, profile and image each line will result in a match because the json format for tweets has all these terms as dictionary keys. </p>
<p>Besides the raw JSON is huge, each tweet will be more than 1kb in size (this one is 2.1kb) but the only part that's relevent in your sample is:</p>
<pre><code>"text":"me with Dibyabhumi Multiple College students https:\/\/t.co\/MqmDwbCDAF",
</code></pre>
<p>And this is less than 100 bytes, a typical tweet is still less than 140 characters despite recent changes to the API.</p>
<p><strong>Things to try:</strong></p>
<p>pre compile the regex as suggested by <a href="http://stackoverflow.com/users/2141635/padraic-cunningham">Padraic Cunningham</a> </p>
<p>Option 1. Load this data into a postgresql JSONB field. JSONB fields are indexable and can be searched very quickly</p>
<p>Option 2. Load this into any old database, with the context of the text field having it's own column so that this column can be searched easily.</p>
<p>Option 3. last but not least, extract just the <code>text</code> field into it's own file. You can have a CSV file where the first column is the screen name and the second is the text of the tweet. Your 15GB will be shrunk to about 1GB</p>
<p>In short what you are doing now is searching the whole farm for the needle when you only need to search the haystack. </p>
| 1 | 2016-10-10T11:08:15Z | [
"python",
"list",
"python-3.x",
"search",
"twitter"
] |
Python read input lines through function call | 39,956,534 | <p>My code below works perfectly to receive my input data (list.txt) and return lines between 2 and 5 to the screen. </p>
<pre><code>def get_list():
file = open('list.txt', 'r')
lines = file.read().splitlines()[2:5]
print (lines)
get_list()
</code></pre>
<p>However I am required to implement something where I can call the function like:</p>
<pre><code>get_list()[2:5]
</code></pre>
<p>and this would print between lines 2 and 5 instead. Can anyone suggest a possible way I can do this? Thanks!</p>
| 1 | 2016-10-10T10:47:50Z | 39,956,580 | <p>Just return lines !</p>
<pre><code>def get_list():
file = open('list.txt', 'r')
lines = file.read().splitlines()
return lines
</code></pre>
| 0 | 2016-10-10T10:50:44Z | [
"python",
"file",
"text",
"input"
] |
Python read input lines through function call | 39,956,534 | <p>My code below works perfectly to receive my input data (list.txt) and return lines between 2 and 5 to the screen. </p>
<pre><code>def get_list():
file = open('list.txt', 'r')
lines = file.read().splitlines()[2:5]
print (lines)
get_list()
</code></pre>
<p>However I am required to implement something where I can call the function like:</p>
<pre><code>get_list()[2:5]
</code></pre>
<p>and this would print between lines 2 and 5 instead. Can anyone suggest a possible way I can do this? Thanks!</p>
| 1 | 2016-10-10T10:47:50Z | 39,956,626 | <pre><code>def get_list():
with open('list.txt', 'r') as file:
lines = file.read().splitlines()
return lines
print(get_list()[2:5])
</code></pre>
| 1 | 2016-10-10T10:52:44Z | [
"python",
"file",
"text",
"input"
] |
Python read input lines through function call | 39,956,534 | <p>My code below works perfectly to receive my input data (list.txt) and return lines between 2 and 5 to the screen. </p>
<pre><code>def get_list():
file = open('list.txt', 'r')
lines = file.read().splitlines()[2:5]
print (lines)
get_list()
</code></pre>
<p>However I am required to implement something where I can call the function like:</p>
<pre><code>get_list()[2:5]
</code></pre>
<p>and this would print between lines 2 and 5 instead. Can anyone suggest a possible way I can do this? Thanks!</p>
| 1 | 2016-10-10T10:47:50Z | 39,957,053 | <p>As I mentioned in the question comments, this is <em>not</em> a sensible thing to do, but here's how it can be done. To test this code I created a text file containing the integers 0 to 9, using the GNU coreutils command <code>seq</code>:</p>
<pre><code>seq 0 9 >list.txt
</code></pre>
<p>And here's the Python code:</p>
<pre><code>class AutoPrint(object):
def __init__(self, data):
self.data = data
def __getitem__(self, idx):
for row in self.data[idx]:
print(row)
def get_list(fname):
with open('list.txt') as f:
data = f.read().splitlines()
return AutoPrint(data)
get_list('list.txt')[2:5]
</code></pre>
<p><strong>output</strong></p>
<pre><code>2
3
4
</code></pre>
<p>But <em>please</em> don't do crazy stuff like this in real code! My <code>__getitem__</code> method returns <code>None</code>; a proper <code>__getitem__</code> is supposed to return the selected item(s). And it shouldn't have crazy side-effects, like printing stuff. OTOH, I guess while you're developing the code it <em>can</em> be handy for it to print (or log) stuff so that you know that it's doing what you expect it to do. </p>
| 1 | 2016-10-10T11:18:58Z | [
"python",
"file",
"text",
"input"
] |
Create a custom URL and outputting HTML form data | 39,956,590 | <p>For my first Flask project I wanted to create a basic Flask app using Riot Game's API for League of Legends. I've got all the processing of API working but I'm having trouble going about outputting it.</p>
<p>I take the input from a form on one page.</p>
<pre><code><form class="navbar-form navbar-left" action="{{ url_for('current_game_output') }}" method="POST">
<div class="form-group">
<input type="text" class="form-control" placeholder="Summoner Name" name="summoner_name">
<select class="form-control" name="region">
<option value="oce">Oceanic</option>
<option value="na">North America</option>
<option value="euw">Europe West</option>
</select>
</div>
<button type="submit" class="btn btn-default" value="Send">Submit</button>
</form>
</code></pre>
<p>And I am trying to output the data returned from the API onto the next page.</p>
<pre><code>{% extends "header.html" %}
{% block body %}
<h3> Team 2 </h3>
<table class="table table-bordered" width="50%">
<tr>
<th width="48%">Summoner Name</th>
<th width="48%">Champion</th>
<th width="4%">Pic</th>
</tr>
{% for player in team1 %}
<tr>
<td>{{ player[0] }}</td>
<td>{{ player[1] }}</td>
<td><img width="20px" src="{{ url_for('static', filename='images/championIcons/') }}{{ player[1].replace(" ", "") }}_Square_0.png"></td>
</tr>
{% endfor %}
</table>
<h3> Team 1 </h3>
<table class="table table-bordered" width="50%">
<tr>
<th width="48%">Summoner Name</th>
<th width="48%">Champion</th>
<th width="4%">Pic</th>
</tr>
{% for player in team2 %}
<tr>
<td>{{ player[0] }}</td>
<td>{{ player[1] }}</td>
<td><img width="20px" src="{{ url_for('static', filename='images/championIcons/') }}{{ player[1].replace(" ", "") }}_Square_0.png"></td>
</tr>
{% endfor %}
</table>
{% endblock %}
</code></pre>
<p>I'd like the URL of the output page to be dynamic'/currentgame/region/username' but keep getting errors when trying to do so. </p>
<p>Relevant part of my views.py file (hidden my api key):</p>
<pre><code>@app.route('/header')
def header():
return render_template("header.html")
@app.route('/current')
def current():
return render_template("current.html")
@app.route('/currentgame/<region>/<name>', methods=['POST'])
def current_game_output(region, name):
region = request.form['region']
summoner_name = request.form['summoner_name']
api = RiotAPI('APIKEYGOESHERE', region)
team1, team2 = current_game_data(summoner_name, region, api)
return render_template("output.html",team1=team1,team2=team2)
</code></pre>
<p>Any help/pointers on the best way to output/return the data would be appreciated.
Thanks</p>
| 0 | 2016-10-10T10:51:05Z | 39,956,684 | <p>You should post the error as well.</p>
<p>In a quick looks this should be fixed:</p>
<pre><code>@app.route('/currentgame/<string:region>/<string:name>', methods=['POST'])
def current_game_output(region, name):
region = request.form['region']
summoner_name = request.form['summoner_name']
api = RiotAPI('APIKEYGOESHERE', region)
team1, team2 = current_game_data(summoner_name, region, api)
return render_template("output.html",team1=team1,team2=team2)
</code></pre>
<p>Change route to <code>/currentgame/<string:region>/<string:name></code></p>
| 0 | 2016-10-10T10:56:01Z | [
"python",
"forms",
"python-3.x",
"flask"
] |
Insertion sort not working - list index out of range | 39,956,663 | <p>Trying to create insertion sort but receive an error...</p>
<p>Don't really know why it is happening. It always tends to miss 37 aswell</p>
<pre><code>numbers = [45,56,37,79,46,18,90,81,50]
def insertionSort(items):
Tsorted = []
Tsorted.append(items[0])
items.remove(items[0])
for i in range(0,len(items)):
print (Tsorted)
if items[i] > Tsorted[len(Tsorted)-1]:
Tsorted.append(items[i])
else:
Tsorted[len(Tsorted)-2] = items[i]
items.remove(items[i])
insertionSort(numbers)
</code></pre>
<p>Error:</p>
<pre><code> if items[i] > Tsorted[len(Tsorted)-1]:
IndexError: list index out of range
</code></pre>
| 0 | 2016-10-10T10:54:49Z | 39,956,837 | <p>You are removing elements from <code>items</code> over the course of the loop; thus, <code>i</code> may become a value that was a valid index in the original <code>items</code>, but is no longer in the shortened one.</p>
<p>If you need to remove elements from <code>items</code>, it looks like you should wait until the loop is finished.</p>
| 0 | 2016-10-10T11:05:48Z | [
"python",
"python-2.7",
"insertion-sort"
] |
Insertion sort not working - list index out of range | 39,956,663 | <p>Trying to create insertion sort but receive an error...</p>
<p>Don't really know why it is happening. It always tends to miss 37 aswell</p>
<pre><code>numbers = [45,56,37,79,46,18,90,81,50]
def insertionSort(items):
Tsorted = []
Tsorted.append(items[0])
items.remove(items[0])
for i in range(0,len(items)):
print (Tsorted)
if items[i] > Tsorted[len(Tsorted)-1]:
Tsorted.append(items[i])
else:
Tsorted[len(Tsorted)-2] = items[i]
items.remove(items[i])
insertionSort(numbers)
</code></pre>
<p>Error:</p>
<pre><code> if items[i] > Tsorted[len(Tsorted)-1]:
IndexError: list index out of range
</code></pre>
| 0 | 2016-10-10T10:54:49Z | 39,956,838 | <p>First thing: you are removing items from the Array that you are iterating inside the loop here: <code>items.remove(items[i])</code>. This is generally not a good idea.</p>
<p>Second: This algorithm doesn't implement insertion sort, even if you fix the deletion issue. You should review the algorithm, e.g. here <a href="https://en.wikipedia.org/wiki/Insertion_sort" rel="nofollow">Insertion sort in Wikipedia</a>. Thre is another loop required to find the right insertion place.</p>
<p>Third: in the else case, you are overwriting instead of inserting values.</p>
| 1 | 2016-10-10T11:05:51Z | [
"python",
"python-2.7",
"insertion-sort"
] |
Insertion sort not working - list index out of range | 39,956,663 | <p>Trying to create insertion sort but receive an error...</p>
<p>Don't really know why it is happening. It always tends to miss 37 aswell</p>
<pre><code>numbers = [45,56,37,79,46,18,90,81,50]
def insertionSort(items):
Tsorted = []
Tsorted.append(items[0])
items.remove(items[0])
for i in range(0,len(items)):
print (Tsorted)
if items[i] > Tsorted[len(Tsorted)-1]:
Tsorted.append(items[i])
else:
Tsorted[len(Tsorted)-2] = items[i]
items.remove(items[i])
insertionSort(numbers)
</code></pre>
<p>Error:</p>
<pre><code> if items[i] > Tsorted[len(Tsorted)-1]:
IndexError: list index out of range
</code></pre>
| 0 | 2016-10-10T10:54:49Z | 39,956,844 | <p>That's because you're calling <code>tems.remove()</code>. Your code fails when i=4 and <code>items=[37, 46, 90, 50]</code>. </p>
<p>So they already has no an element with index <code>4</code> but with <code>3</code> since indexing starts with 0.</p>
| 0 | 2016-10-10T11:06:13Z | [
"python",
"python-2.7",
"insertion-sort"
] |
Insertion sort not working - list index out of range | 39,956,663 | <p>Trying to create insertion sort but receive an error...</p>
<p>Don't really know why it is happening. It always tends to miss 37 aswell</p>
<pre><code>numbers = [45,56,37,79,46,18,90,81,50]
def insertionSort(items):
Tsorted = []
Tsorted.append(items[0])
items.remove(items[0])
for i in range(0,len(items)):
print (Tsorted)
if items[i] > Tsorted[len(Tsorted)-1]:
Tsorted.append(items[i])
else:
Tsorted[len(Tsorted)-2] = items[i]
items.remove(items[i])
insertionSort(numbers)
</code></pre>
<p>Error:</p>
<pre><code> if items[i] > Tsorted[len(Tsorted)-1]:
IndexError: list index out of range
</code></pre>
| 0 | 2016-10-10T10:54:49Z | 39,957,029 | <p><code>range(0,len(items)</code> will only be calculated the first time your code hits your for-loop, at which state <code>len(list) = 8</code>. Which means that you wlil iterate</p>
<pre><code>for i in [0,1,2,3,4,5,6,7]
#Do stuff...
</code></pre>
<p>But at the same time you remove items from your list in each loop. So when hitting i = 4, you have iterated your loop 4 times and the length of you <code>item</code>-list is only 4, which means that <code>items[4]</code>
no longer exists.</p>
| 0 | 2016-10-10T11:17:02Z | [
"python",
"python-2.7",
"insertion-sort"
] |
Reject or loop over user input if two conditions not met | 39,956,782 | <p>I am a real beginner with Python, although I am loving every minute of it so far.</p>
<p>I am making a little program that takes user input and then does stuff with it. My issue is that the numbers the user inputs have to </p>
<p>(1) All add up to not more than one (i.e. a1+ a2+ a3 \leq 1)</p>
<p>(2) Each individually be < 1.</p>
<p>Here is my code thus far (just the essential middle bit):</p>
<pre><code> num_array = list()
a1 = raw_input('Enter percentage a (in decimal form): ')
a2 = raw_input('Enter percentage b (in decimal form): ')
...
an = raw_input('Enter percentage n (in decimal form): ')
li = [a1, a2, ... , an]
for s in li:
num_array.append(float(s))
</code></pre>
<p>And I would love to build in something to make it demand the user re-inputs things if their inputs either exceed the requirement that </p>
<p>a1+a2+a3 >1</p>
<p>or that a1>1, a2>1, a3>1 etc.</p>
<p>I have a feeling this would be really easy to implement, but with my limited knowledge I am stuck!</p>
<p>Any help would be much appreciated :-)</p>
| 2 | 2016-10-10T11:01:59Z | 39,956,909 | <pre><code>input_list = []
input_number = 1
while True:
input_list.append(raw_input('Enter percentage {} (in decimal form):'.format(input_number))
if float(input_list[-1]) > 1: # Last input is larger than one, remove last input and print reason
input_list.remove(input_list[-1])
print('The input is larger than one.')
continue
total = sum([float(s) for s in input_list])
if total > 1: # Total larger than one, remove last input and print reason
input_list.remove(input_list[-1])
print('The sum of the percentages is larger than one.')
continue
if total == 1: # if the sum equals one: exit the loop
break
input_number += 1
</code></pre>
| 4 | 2016-10-10T11:09:21Z | [
"python",
"loops",
"input"
] |
Python "trouble shooting machine " needs fixing | 39,956,833 | <p>The following code is designed to be an automated troubleshooter in Python.</p>
<pre><code># Welcoming the user to the program
print("Hello this is a automated mobile phone troubleshooter ")
print("The code will ask you a few questions try to answer them to the best of your ability") # Explaining what the code will do
# A list storing all the questions the code will ask the user
questions = ["Is there a problem with your hardware or is do you need technical assistance. Please type technical assistance or hardware",
"Have you dropped your phone recently? Please type Yes or No",
"Is your phone able to charge? please type Yes or No",
"Is your phone a iphone? Please type yes or no",
"Does your phone keep freezing? Please type yes or no",
"Can your phone connect to wifi? please type either yes or no",
"Have you gotten your phone wet? ",
"Is the phone's screen cracked or broken? ",
"Is there a problem with the camera? ",
"Is the problem with phone fixed? "]
# A list containing all the solutions that will be given to the user
solutions = ["This troubleshooter is only for hardware problems please call 01474 709853 for technical assistance",
"Please try turning it off and on again",
"Try changing the cable you charge the phone with",
"Please hold the lock button and home button for 5 seconds this causes a force restart",
"Try deleting some data to make your phone run faster E.G. Delete applications",
"Try restarting your router",
"Put your phone in a bowl of rice overnight",
"Take the phone to the manufacturer's store",
"Uninstall any third party apps or applications that you have downloaded since the camera has not been working",
"Please take the phone to your local phone manufacturers store and ask them for help"]
answers = ["technical assistance","yes","no","yes","yes","no","yes","yes","yes","no"]
validation = ["hardware","no","yes","no","no","yes","no","no","no","yes"]
answer = "a"
# Creating a loop and making the variable loop go from 0 to 9
for loop in range(0,10):
while answer != answers[loop] and answer != validation[loop]:
answer = input(questions[loop])
# Turning the user's answer and turning it to lowercase making sure the IF statement gets the right answer
answer = answer.lower()
if answer == answers[loop]:
# prints the solution the problem
print(solutions[loop])
else goto
print("Thank you for using the automated troubleshooting program goodbye")
</code></pre>
<p>I can't get this code to run properly as it can take a max input of two questions before it ends, is there any way someone can help?</p>
| -6 | 2016-10-10T11:05:41Z | 39,957,633 | <p>Whats about doing it with "if statements" and raw_input ? </p>
<pre><code>x = raw_input("Is there a problem with your hardware or is do you need technical assistance. Please type technical assistance or hardware")
if x == ("technical assistant"):
print("This troubleshooter is only for hardware problems please call 01474 709853 for technical assistance")
if x == ("hardware"):
x1=raw_input("Have you dropped your phone recently? Please type Yes or No")
if x1 == ("No"):
x2=raw_input("Is your phone able to charge? Please type Yes or No")
</code></pre>
<p>and so on... </p>
| -1 | 2016-10-10T11:51:38Z | [
"python"
] |
Python: decorator/wrapper for try/except statement | 39,956,960 | <p>I have some blocks of code which need to be wrapped by function.</p>
<pre><code>try:
if config.DEVELOPMENT == True:
# do_some_stuff
except:
logger.info("Config is not set for development")
</code></pre>
<p>Then I'll do again:</p>
<pre><code>try:
if config.DEVELOPMENT == True:
# do_some_another_stuff
except:
logger.info("Config is not set for development")
</code></pre>
<p>So, how can I wrap this "do_some_stuff" and "do_some_another_stuff"?</p>
<p>I'm trying to write function with contextmanager:</p>
<pre><code>@contextmanager
def try_dev_config(name):
try:
if name is not None:
yield
except Exception as e:
print "not dev config"
with try_dev_config("config.DEVELOPMENT"):
# do_some_stuff
</code></pre>
<p>And I got an error:</p>
<blockquote>
<p>RuntimeError: generator didn't yield</p>
</blockquote>
| 0 | 2016-10-10T11:12:26Z | 39,967,851 | <p>You could pass in a function.</p>
<pre><code>boolean = True
def pass_this_in():
print("I just did some stuff")
def the_try_except_bit(function):
try:
if boolean:
function()
except:
print("Excepted")
# Calling the above code
the_try_except_bit(pass_this_in)
</code></pre>
<p>If you want to reduce the "pass_this_in" definition bit, then you can use <a href="http://www.secnetix.de/olli/Python/lambda_functions.hawk" rel="nofollow">lambda function definitions</a>:</p>
<pre><code>pass_this_in = lambda : print("I just did some stuff")
</code></pre>
| 0 | 2016-10-10T22:43:41Z | [
"python",
"try-catch",
"wrapper",
"decorator"
] |
Python: decorator/wrapper for try/except statement | 39,956,960 | <p>I have some blocks of code which need to be wrapped by function.</p>
<pre><code>try:
if config.DEVELOPMENT == True:
# do_some_stuff
except:
logger.info("Config is not set for development")
</code></pre>
<p>Then I'll do again:</p>
<pre><code>try:
if config.DEVELOPMENT == True:
# do_some_another_stuff
except:
logger.info("Config is not set for development")
</code></pre>
<p>So, how can I wrap this "do_some_stuff" and "do_some_another_stuff"?</p>
<p>I'm trying to write function with contextmanager:</p>
<pre><code>@contextmanager
def try_dev_config(name):
try:
if name is not None:
yield
except Exception as e:
print "not dev config"
with try_dev_config("config.DEVELOPMENT"):
# do_some_stuff
</code></pre>
<p>And I got an error:</p>
<blockquote>
<p>RuntimeError: generator didn't yield</p>
</blockquote>
| 0 | 2016-10-10T11:12:26Z | 39,993,645 | <p>I am not sure that a context manager is the good method to achieve what you want. The context manager goal is to provide a mecanism to open/instantiate a resource, give access to it (or not) and close/clean it automatically when you no more need it.</p>
<p>IMHO, what you need is a <a href="http://thecodeship.com/patterns/guide-to-python-function-decorators/" rel="nofollow">decorator</a>.
A decorator aims at executing code around a function call. It would force you to put each block of code in a function but I don't think it is so difficult. You can implement it like this:</p>
<pre><code>class Config(object):
"""for demonstration purpose only: used to have a config.DEVELOPMENT value"""
DEVELOPMENT = True
class Logger(object):
"""for demonstration purpose only: used to have a logger.info method"""
@staticmethod
def info(msg):
print("Logged: {}".format(msg))
def check_dev_config(config, logger):
def dev_config_checker(func):
def wrapper(*args, **kwargs):
try:
if config.DEVELOPMENT:
func(*args, **kwargs)
except Exception as err:
logger.info(
"Config is not set for developpement: {}".format(err))
return wrapper
return dev_config_checker
@check_dev_config(Config, Logger)
def do_stuff_1():
print("stuff 1 done")
@check_dev_config(Config, Logger)
def do_stuff_2():
raise Exception("stuff 2 failed")
do_stuff_1()
do_stuff_2()
</code></pre>
<p>This code prints</p>
<pre><code>stuff 1 done
Logged: Config is not set for developpement: stuff 2 failed
</code></pre>
<p>Explanations:</p>
<ul>
<li>The <code>check_dev_config</code> function is actually a decorator generator which accepts the <code>config</code> and the <code>logger</code> as arguments.</li>
<li>It returns the <code>dev_config_checker</code> function which is an actual (and parameterised) decorator, and which accepts a function to decorate as argument.</li>
<li>This decorator returns a <code>wrapper</code> function which will actually run code around the decorated function call. In this function, the decorated function is called inside a <code>try/except</code> structure and only if the <code>config.DEVELOPMENT</code> is evaluated to True. In case of exception, the <code>logger</code> is used to log an information.</li>
<li>Each block of code to decorate is put into a function (<code>do_stuff_1</code>, <code>do_stuff_2</code> and decorated with the <code>check_dev_config</code> decorator generator, giving it the <code>config</code> and the <code>logger</code>.</li>
<li>When decorated functions are called, they are called via their decorator and not directly. As you can see, the <code>do_stuff_2</code> exception has been catched and the a message has been logged.</li>
</ul>
| 0 | 2016-10-12T08:12:36Z | [
"python",
"try-catch",
"wrapper",
"decorator"
] |
How to capture the ZPL ^HV ouotput | 39,957,025 | <p>I need help implementing the ^HV ZPL command and to capture it as the host.</p>
<p>I want to read the TID and encode it to the EPC using Python, i can send print and encode command to the printer but how do i read back from it ?</p>
<p>If I'm using the "Direct Communication" program in the Zebra Setup Utilities tool i can get the TID back in the "Data received" window.</p>
<p>Ive tried using TCP/IP but i dont know how to pull the info just to print</p>
<p>But how can i capture it using python ?</p>
<p>Thanks !</p>
| 0 | 2016-10-10T11:16:49Z | 39,965,941 | <p>Communicating with a Zebra printer over TCP is the same as any other TCP connection. If the question is how to use the ^HV command, it is usually put into a stored format. The response happens when you use the format to print. Here's a snippet I modified from <a href="https://wiki.python.org/moin/TcpCommunication" rel="nofollow">wiki.python.org</a>.</p>
<pre><code>#!/usr/bin/env python
import socket
TCP_IP = '127.0.0.1'
TCP_PORT = 9100
BUFFER_SIZE = 1024
FORMAT = "^XA^DFE:TEST.ZPL^FO30,30^A0N,50,50^FN1^FS^HV1,15,[,],^FS^XZ"
PRINT = "^XA^XFE:TEST.ZPL^FN1^FDHELLO WORLD^FS^XZ"
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((TCP_IP, TCP_PORT))
s.send(FORMAT)
s.send(PRINT)
data = s.recv(BUFFER_SIZE)
s.close()
print "received data:", data
</code></pre>
| 1 | 2016-10-10T20:05:28Z | [
"python",
"rfid",
"zebra-printers",
"zpl",
"zpl-ii"
] |
Python - difference between self.method, lambda: self.method() and self.method() on startup | 39,957,044 | <p>In order to understand the difference in use of method calls, I wrote a MVC in python 2.7. Here is the code:</p>
<pre><code>import Tkinter as tk
class Model(object):
def __init__(self, *args, **kwargs):
# dict
self.data = {}
# -- >values
self.data["Value_One"] = tk.IntVar()
self.data["Value_Two"] = tk.IntVar()
self.data["Value_Three"] = tk.IntVar()
# --> texts
self.data["Text_Label_val_One"] = tk.StringVar()
self.data["Text_Label_val_Two"] = tk.StringVar()
self.data["Text_Label_val_Three"] = tk.StringVar()
class Control(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs) # init
tk.Tk.wm_title(self, "Testing Grounds") # title
self.model = Model()
self.view = View(parent = self, controller = self)
self.view.pack(fill = 'both', expand = True)
def set_labels_text(self):
self.model.data["Text_Label_val_One"].set("Value_One is set to: {0}".format(self.model.data["Value_One"].get()))
self.model.data["Text_Label_val_Two"].set("Value_Two is set to: {0}".format(self.model.data["Value_Two"].get()))
self.model.data["Text_Label_val_Three"].set("Value_Three is set to: {0}".format(self.model.data["Value_Three"].get()))
def set_value_one(self):
self.model.data["Value_One"].set(1)
def set_value_two(self):
self.model.data["Value_Two"].set(2)
def set_value_three(self):
self.model.data["Value_Three"].set(3)
class View(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
self.buttons()
self.labels()
def buttons(self):
set_v_one = tk.Button(self, text = "Set Value One To 1", command = lambda: self.controller.set_value_one())
set_v_one.pack(fill = 'x', expand = True)
set_v_two = tk.Button(self, text = "Set Value Two To 2", command = self.controller.set_value_two())
set_v_two.pack(fill = 'x', expand = True)
set_v_three = tk.Button(self, text = "Set Value Three To 3", command = self.controller.set_value_three)
set_v_three.pack(fill = 'x', expand = True)
update_lbl_two = tk.Button(self, text = "Update Labels", command = self.controller.set_labels_text)
update_lbl_two.pack(fill = 'x')
def labels(self):
label_one = tk.Label(self, textvariable = self.controller.model.data["Value_One"])
label_one.pack(fill = 'x', expand = True)
label_two = tk.Label(self, textvariable = self.controller.model.data["Value_Two"])
label_two.pack(fill = 'x', expand = True)
label_three = tk.Label(self, textvariable = self.controller.model.data["Value_Three"])
label_three.pack(fill = 'x', expand = True)
label_val_one = tk.Label(self, textvariable = self.controller.model.data["Text_Label_val_One"])
label_val_one.pack(fill = 'x', expand = True)
label_val_two = tk.Label(self, textvariable = self.controller.model.data["Text_Label_val_Two"])
label_val_two.pack(fill = 'x', expand = True)
label_val_three = tk.Label(self, textvariable = self.controller.model.data["Text_Label_val_Three"])
label_val_three.pack(fill = 'x', expand = True)
if __name__ == "__main__":
app = Control()
app.mainloop()
</code></pre>
<p>If one executes it and hits the button to update the labels, the result is the following:</p>
<p><a href="http://i.stack.imgur.com/GIRrD.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/GIRrD.jpg" alt="enter image description here"></a></p>
<p>As one can see, <code>model.self.data["Value_One"]</code> is not set on startup, due to the use of <code>lambda</code>, which I thought to be a nameless function, which can only return one value and nothing more. Here it seems to inhibit the initial call of the method by the command line of button <code>set_v_one</code>.</p>
<p>In the case of <code>model.self.data["Value_Two"]</code>, the value is updated on startup. I'd think thats because the function is called, when the command line of the button is read and the button created, due to the active call or initialization of the method via brakets <code>()</code>, because it does happen, even when one doesn't pack the button.</p>
<p>For <code>model.self.data["Value_Three"]</code>, the value is also not updated on startup. This is, as I'd think, caused by the method <code>set_value_three(self)</code> of the controller bound to the command line, but not initialized, due to the lack of calling for it by using the brakets <code>()</code>.</p>
<p>After pressing the buttons <code>set_v_one</code> and <code>set_v_three</code>, the values get properly updated, as indicated by the corresponding labels <code>label_one</code> and <code>label_three</code>. </p>
<p>Even though I'm using these method calls a lot, I couldn't yet fully understand, how they work in detail. If someone could clarify this or point me to a good source I just haven't found yet, it would be much appreciated.</p>
| 0 | 2016-10-10T11:18:10Z | 39,957,247 | <p>All in all, there is no mystery here. </p>
<p>The command argument of the Button constructor takes a callback, i.e. a function that will be executed when the button is pressed. You do this for buttons 1 and 3. So when the corresponding buttons are clicked, the function (be it the lambda or the bound method) is called and the labels are updated. With button two, you actually execute the method that sets the value of the second label and assigning the command argument the result of that method call (which will be None). This is in violation of the API as far as I understand and should probably result in an error. </p>
<p>To sum it up, your confusion seems to stem from mixing up a function (an object that can be executed) and its invocation (the action of executing a function). </p>
| 2 | 2016-10-10T11:29:19Z | [
"python",
"lambda",
"method-call"
] |
Python Daemon dies | 39,957,122 | <p>I created a Daemon process with these lib<a href="https://www.python.org/dev/peps/pep-3143/" rel="nofollow">linktosite</a>
I connect trough ssh and start the process with python myDaemon.py start.</p>
<p>I use a loop within the daemon method to do my tasks. But as soon as I logout the daemon stops(dies).</p>
<p>Does this happen because I save the PID file on my user and not in the root folder?</p>
<p>Anyone a idea. I can deliver code but now on Thread creation.(+3h)</p>
| -1 | 2016-10-10T11:22:41Z | 39,957,558 | <p>Use the shebang line in your <code>python</code> script. Make it executable using the command.
chmod +x test.py
Use no hangup to run a program in background even if you close your terminal.</p>
<pre><code>nohup /path/to/test.py &
</code></pre>
<p>Do not forget to use <code>&</code> to put it in background.</p>
<p>To see the process again, use in terminal,</p>
<pre><code>ps ax | grep test.py
</code></pre>
<p><a href="http://askubuntu.com/questions/396654/how-to-run-the-python-program-in-the-background-in-ubuntu-machine">Answer</a></p>
<p><a href="http://stackoverflow.com/questions/4705564/python-script-as-linux-service-daemon?rq=1">Another way would be actually make it an upstart script</a></p>
| -1 | 2016-10-10T11:47:02Z | [
"python",
"linux",
"daemon"
] |
Read list of zlib archives | 39,957,136 | <p>I have a file that contains many zlib archives in itself.
Structure of the file looks like:</p>
<pre><code>+-------------------------+
|+-----------------------+|
|| CMF+FLG (78DA) ||
|+-----------------------+|
|+-----------------------+|
||...compressed data 1...||
|+-----------------------+|
|+-----------------------+|
|| ADLER32 ||
|+-----------------------+|
|
|+-----------------------+|
|| CMF+FLG (78DA) ||
|+-----------------------+|
|+-----------------------+|
||...compressed data 2...||
|+-----------------------+|
|+-----------------------+|
|| ADLER32 ||
|+-----------------------+|
|
|+-----------------------+|
|| CMF+FLG (78DA) ||
|+-----------------------+|
|+-----------------------+|
||...compressed data 3...||
|+-----------------------+|
|+-----------------------+|
|| ADLER32 ||
|+-----------------------+|
| |
|.........................|
| |
|+-----------------------+|
|| CMF+FLG (78DA) ||
|+-----------------------+|
|+-----------------------+|
||...compressed data n...||
|+-----------------------+|
|+-----------------------+|
|| ADLER32 ||
|+-----------------------+|
+-------------------------+
</code></pre>
<p>And I need iterate over all those archive and extract them.
I tried following code but this extracts only first archive from file.</p>
<pre><code>for filename in sys.argv[1:]:
with open(filename, 'r') as compressed:
with open(filename + '-decompressed', 'w') as expanded:
data = zlib.decompress(compressed.read())
expanded.write(data)
</code></pre>
| -2 | 2016-10-10T11:23:24Z | 39,960,680 | <p>You should be able to use a series of decompression objects like this:</p>
<pre><code>import zlib
with open(filename, 'rb') as compressed:
data = compressed.read()
file_no = 0
while data:
d = zlib.decompressobj()
with open('{}_decompressed.{}'.format(filename, file_no), 'wb') as f:
f.write(d.decompress(data))
data = d.unused_data
file_no += 1
</code></pre>
<p>This will take a single file containing multiple concatenated zlib compressed files and decompress each one to a separate file with <em>"_decompressed.n"</em> appended to the original file name.</p>
<p>The key is to use the decompression object's <code>unused_data</code> attribute to determine whether there remains any uncompressed data in the string.</p>
| 2 | 2016-10-10T14:32:23Z | [
"python",
"file",
"zlib"
] |
Pandas does not drop nan | 39,957,341 | <p>I have the following group</p>
<pre><code> unemp nobsRel measure rank nobsRel2 nobsCumSummed
year foo
2000 8010 0.000024 0.000167 1.0 348.0 0.000167 0.980176
4950 0.000264 0.003630 1.0 349.0 0.003630 0.983806
2540 0.000438 0.011027 1.0 350.0 0.011027 0.994833
9830 0.000118 0.000118 NaN NaN 0.000118 0.994952
9920 0.005048 0.005048 NaN NaN 0.005048 1.000000
</code></pre>
<p>Here's what happens when I try to drop duplicates:</p>
<p>In[104]: test.drop_duplicates(subset='rank')
Out[104]: </p>
<pre><code> unemp nobsRel measure rank nobsRel2 nobsCumSummed
year foo
2000 8010 0.000024 0.000167 1.0 348.0 0.000167 0.980176
4950 0.000264 0.003630 1.0 349.0 0.003630 0.983806
2540 0.000438 0.011027 1.0 350.0 0.011027 0.994833
9830 0.000118 0.000118 NaN NaN 0.000118 0.994952
</code></pre>
<p>Why is the last row still there? It is missing!</p>
<pre><code>In[105]: np.isnan(test.loc[(2000, 9830), 'rank'])
Out[105]:
True
</code></pre>
<p>I'm on <code>pandas</code> 0.19.0</p>
| 0 | 2016-10-10T11:34:59Z | 39,957,438 | <p>Sadly it appears that <code>drop_duplicates</code> doesn't do what you want. It removes duplicates, but not the original row that the duplicates are a duplicate of ...</p>
<p>Fortunately that can be overridden with a <code>keep=False</code> option to the call.</p>
| 1 | 2016-10-10T11:40:38Z | [
"python",
"pandas"
] |
Pandas does not drop nan | 39,957,341 | <p>I have the following group</p>
<pre><code> unemp nobsRel measure rank nobsRel2 nobsCumSummed
year foo
2000 8010 0.000024 0.000167 1.0 348.0 0.000167 0.980176
4950 0.000264 0.003630 1.0 349.0 0.003630 0.983806
2540 0.000438 0.011027 1.0 350.0 0.011027 0.994833
9830 0.000118 0.000118 NaN NaN 0.000118 0.994952
9920 0.005048 0.005048 NaN NaN 0.005048 1.000000
</code></pre>
<p>Here's what happens when I try to drop duplicates:</p>
<p>In[104]: test.drop_duplicates(subset='rank')
Out[104]: </p>
<pre><code> unemp nobsRel measure rank nobsRel2 nobsCumSummed
year foo
2000 8010 0.000024 0.000167 1.0 348.0 0.000167 0.980176
4950 0.000264 0.003630 1.0 349.0 0.003630 0.983806
2540 0.000438 0.011027 1.0 350.0 0.011027 0.994833
9830 0.000118 0.000118 NaN NaN 0.000118 0.994952
</code></pre>
<p>Why is the last row still there? It is missing!</p>
<pre><code>In[105]: np.isnan(test.loc[(2000, 9830), 'rank'])
Out[105]:
True
</code></pre>
<p>I'm on <code>pandas</code> 0.19.0</p>
| 0 | 2016-10-10T11:34:59Z | 39,957,443 | <p>The <code>drop_duplicates()</code>method drops the duplicates except the first one (by default). However, you can choose which one to keep by changing the parameter <strong>keep</strong> setting it to <code>last</code>, <code>first</code> or <code>False</code>. Look at the <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.drop_duplicates.html" rel="nofollow">documentation here</a></p>
<p>Try this out : </p>
<pre><code>test.drop_duplicates(subset='rank', keep=False)
</code></pre>
| 4 | 2016-10-10T11:40:57Z | [
"python",
"pandas"
] |
Split string of expression | 39,957,476 | <p>I want to split string like</p>
<pre><code>Expression = "((((324+17)*3)/((936-51)+124))-((13*(72-41))+6))"
</code></pre>
<p>I use str.split() but it split the number like: "3 2 4 + 1 7"</p>
<p>output:</p>
<pre><code>"( ( ( ( 324 + 17 ) * 3 ) / ( ( 936 - 51 ) + 124 ) ) - ( ( 13 * ( 72 - 41 ) ) + 6 ) )"
</code></pre>
| -1 | 2016-10-10T11:43:06Z | 39,957,885 | <p>I think what you nee is to insert space in between every non numeric characters. Split wont be able to do the that job for you and you could use re.sub for the same.</p>
<p>This is what I could come up quickly and there could be better expression to do this in single iteration but it will give you a idea </p>
<pre><code>import re
Expression = "((((324+17)*3)/((936-51)+124))-((13*(72-41))+6))"
# Insert space after every non numeric characters
str = re.sub("([^0-9])", r'\1 ', Expression).strip()
#Insert space after numeric characters which are followed by non numeric characters
str = re.sub("([0-9])([^0-9])", r'\1 \2', str).strip()
print(str)
</code></pre>
<p><strong>Output</strong><br>
<code>( ( ( ( 324 + 17 ) * 3 ) / ( ( 936 - 51 ) + 124 ) ) - ( ( 13 * ( 72 - 41 ) ) + 6 ) )</code></p>
| 2 | 2016-10-10T12:04:56Z | [
"python"
] |
Split string of expression | 39,957,476 | <p>I want to split string like</p>
<pre><code>Expression = "((((324+17)*3)/((936-51)+124))-((13*(72-41))+6))"
</code></pre>
<p>I use str.split() but it split the number like: "3 2 4 + 1 7"</p>
<p>output:</p>
<pre><code>"( ( ( ( 324 + 17 ) * 3 ) / ( ( 936 - 51 ) + 124 ) ) - ( ( 13 * ( 72 - 41 ) ) + 6 ) )"
</code></pre>
| -1 | 2016-10-10T11:43:06Z | 39,958,085 | <p>You could use a dictionary to replace certain characters by their padded equivalents:</p>
<pre><code>>>> Expression = "((((324+17)*3)/((936-51)+124))-((13*(72-41))+6))"
>>> d = {'(':'( ', ')':' )', '+': ' + ', '-': ' - ', '*': ' * ', '/': ' / '}
>>> ''.join(d[c] if c in d else c for c in Expression)
'( ( ( ( 324 + 17 ) * 3 ) / ( ( 936 - 51 ) + 124 ) ) - ( ( 13 * ( 72 - 41 ) ) + 6 ) )'
</code></pre>
<p>Note that the padding dictionary pads <code>(</code> with one space to the right, <code>)</code> with one space to the left, and the operators by spacing on both sides. This prevents over-padding with nested parentheses.</p>
| 0 | 2016-10-10T12:15:04Z | [
"python"
] |
Split string of expression | 39,957,476 | <p>I want to split string like</p>
<pre><code>Expression = "((((324+17)*3)/((936-51)+124))-((13*(72-41))+6))"
</code></pre>
<p>I use str.split() but it split the number like: "3 2 4 + 1 7"</p>
<p>output:</p>
<pre><code>"( ( ( ( 324 + 17 ) * 3 ) / ( ( 936 - 51 ) + 124 ) ) - ( ( 13 * ( 72 - 41 ) ) + 6 ) )"
</code></pre>
| -1 | 2016-10-10T11:43:06Z | 39,959,303 | <p>You're looking to <a href="https://docs.python.org/2/library/tokenize.html" rel="nofollow">tokenize</a> the string. For a Python expression you could do it using the tokenize module, or for a plainer form you could use various search functions. Here are two examples:</p>
<pre><code>>>> expression = "((((324+17)*3)/((936-51)+124))-((13*(72-41))+6))"
>>> import re
>>> re.findall('[0-9]+|.', expression)
['(', '(', '(', '(', '324', '+', '17', ')', '*', '3', ')', '/', '(', '(', '936', '-', '51', ')', '+', '124', ')', ')', '-', '(', '(', '13', '*', '(', '72', '-', '41', ')', ')', '+', '6', ')', ')']
>>> import tokenize
>>> [t.string for t in tokenize.tokenize(iter([expression.encode('utf-8')]).__next__)
... if t.type not in (tokenize.ENCODING, tokenize.ENDMARKER)]
['(', '(', '(', '(', '324', '+', '17', ')', '*', '3', ')', '/', '(', '(', '936', '-', '51', ')', '+', '124', ')', ')', '-', '(', '(', '13', '*', '(', '72', '-', '41', ')', ')', '+', '6', ')', ')']
</code></pre>
<p>The <code>iter([bytes]).__next__</code> part is required because tokenize normally reads out of files, and has no shortcut for a single string. </p>
| 0 | 2016-10-10T13:20:42Z | [
"python"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.