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
Python selenium firefox browser launch error
39,305,226
<p>I am trying to launch Firefox (48.0.2) using Selenium with Python 3.5 on my mac using the following code:</p> <pre><code>from selenium import webdriver browser = webdriver.Firefox() browser.get('http://bbc.co.uk') </code></pre> <p>However, Firefox launches without going to the specified webpage and times out with the following error message:</p> <pre><code>Traceback (most recent call last): File "/Users/anthonyperera/Documents/Python/AutomatePython/seleniumexample.py", line 2, in &lt;module&gt; browser = webdriver.Firefox() File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/selenium/webdriver/firefox/webdriver.py", line 80, in __init__ self.binary, timeout) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/selenium/webdriver/firefox/extension_connection.py", line 52, in __init__ self.binary.launch_browser(self.profile, timeout=timeout) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/selenium/webdriver/firefox/firefox_binary.py", line 68, in launch_browser self._wait_until_connectable(timeout=timeout) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/selenium/webdriver/firefox/firefox_binary.py", line 108, in _wait_until_connectable % (self.profile.path)) selenium.common.exceptions.WebDriverException: Message: Can't load the profile. Profile Dir: /var/folders/6n/_xgjldp12r59c6gdvgb46nsm0000gn/T/tmpwlxtjbt4 If you specified a log_file in the FirefoxBinary constructor, check it for details. </code></pre>
0
2016-09-03T09:11:20Z
39,564,083
<p>I had the same issue and I solved it. Firefox 48+ doesn't support <code>webdriver.Firefox()</code>. </p> <p>My environment:<br> MacOS 10.11.6, python 3.5.2, firefox 48.0.2, Django 1.10, selenium 2.53.6 </p> <pre><code>from selenium import webdriver from selenium.webdriver.common.desired_capabilities import DesiredCapabilities caps = DesiredCapabilities.FIREFOX caps["marionette"] = True caps["binary"] = "/Applications/Firefox.app/Contents/MacOS/firefox-bin" browser = webdriver.Firefox(capabilities=caps) browser.get('http://bbc.co.uk') </code></pre> <p>This is what I was trying<br> 1. download <code>geckodriver</code>.<a href="https://github.com/mozilla/geckodriver/releases" rel="nofollow">https://github.com/mozilla/geckodriver/releases</a>. <code>v.0.10.0</code>is for <code>selenium 3(beta)</code>. if you use <code>selenium 2.xx</code>, download <code>v.0.9.0</code><br> 2. open <code>~/.bash_profile</code>. you can edit it by <code>$ vim ~/.bash_profile</code>.<br> 3. add PATH like..<br> <code>export PATH=$PATH:/path/to/your/.../geckodriver-v0.9.0-mac</code><br> 4. <code>geckodriver</code> under the folder <code>geckodriver-v0.9.0-mac</code>, rename it to <code>wires</code><br> 5. restart shell<br> 6. check the version<br> <code>$ wires --version</code><br> 7. and run above the code! </p> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Mozilla/QA/Marionette/WebDriver" rel="nofollow">webdriver-mozilla</a></li> </ul>
0
2016-09-19T01:08:43Z
[ "python", "selenium", "firefox" ]
Using re.sub capture groups
39,305,278
<p>Apologies for the simple question but Im struggling with this:</p> <pre><code>str = 'EURGBP' print (re.sub(r'\EUR(GBP)', r'\1', str)) </code></pre> <p>returns</p> <pre><code>GBP </code></pre> <p>but</p> <pre><code>print (re.sub(r'\(EUR)(GBP)', r'\2,\1', str)) </code></pre> <p>gives me <code>error: unbalanced parenthesis at position 5</code></p> <p>I am simply trying to capture both elements enclosed in parenthesis and print them out in reversed order using re like this:</p> <pre><code>GBPEUR </code></pre> <p>Can someone please show me what I am doing wrong?</p>
1
2016-09-03T09:17:34Z
39,305,298
<p>Don't escape the paren as <code>\(</code> means you are literally searching for a <code>(</code> in the string so the closing <code>)</code> has no matching opening <code>(</code>, escaping the <code>E</code> worked as you were looking for the literal <code>E</code>, also just use <code>r'\2\1'</code> unless you want them also separated by a comma:</p> <pre><code>In [1]: import re In [2]: s = 'EURGBP' In [3]: re.sub(r'(EUR)(GBP)', r'\2\1', s) Out[3]: 'GBPEUR' </code></pre>
1
2016-09-03T09:20:21Z
[ "python" ]
Destroying a PyCapsule object
39,305,286
<p>According to <a href="https://docs.python.org/3.4/c-api/capsule.html?highlight=capsule" rel="nofollow">documentation</a>, the third argument to <code>PyCapsule_New()</code> can specify a destructor, which I assume should be called when the capsule is destroyed.</p> <pre><code>void mapDestroy(PyObject *capsule) { lash_map_simple_t *map; fprintf(stderr, "Entered destructor\n"); map = (lash_map_simple_t*)PyCapsule_GetPointer(capsule, "MAP_C_API"); if (map == NULL) return; fprintf(stderr, "Destroying map %p\n", map); lashMapSimpleFree(map); free(map); } static PyObject * mapSimpleInit_func(PyObject *self, PyObject *args) { unsigned int w; unsigned int h; PyObject *pymap; lash_map_simple_t *map = (lash_map_simple_t*)malloc(sizeof(lash_map_simple_t)); pymap = PyCapsule_New((void *)map, "MAP_C_API", mapDestroy); if (!PyArg_ParseTuple(args, "II", &amp;w, &amp;h)) return NULL; lashMapSimpleInit(map, &amp;w, &amp;h); return Py_BuildValue("O", pymap); } </code></pre> <p>However, when I instantiate the object and delete it or exit from Python console, the destructor doesn't seem to be called:</p> <pre><code>&gt;&gt;&gt; a = mapSimpleInit(10,20) &gt;&gt;&gt; a &lt;capsule object "MAP_C_API" at 0x7fcf4959f930&gt; &gt;&gt;&gt; del(a) &gt;&gt;&gt; a = mapSimpleInit(10,20) &gt;&gt;&gt; a &lt;capsule object "MAP_C_API" at 0x7fcf495186f0&gt; &gt;&gt;&gt; quit() lash@CANTANDO ~/programming/src/liblashgame $ </code></pre> <p>My guess is that it has something to do with the <code>Py_BuildValue()</code> returning a new reference to the "capsule", which upon deletion doesn't affect the original. Anyway, how would I go about ensuring that the object is properly destroyed?</p> <p>Using Python 3.4.3 [GCC 4.8.4] (on linux)</p>
5
2016-09-03T09:18:15Z
39,542,417
<p><code>Py_BuildValue("O", thingy)</code> will just increment the refcount for <code>thingy</code> and return it – the docs say that it returns a “new reference” but that is not quite true when you pass it an existing <code>PyObject*</code>. </p> <p>If these functions of yours – the ones in your question, that is – are all defined in the same translation unit, the destructor function will likely have to be declared <code>static</code> (so its full signature would be <code>static void mapDestroy(PyObject* capsule);</code>) to ensure that the Python API can look up the functions’ address properly when it comes time to call the destructor.</p> <p>… You don’t have to use a <code>static</code> function, as long as the destructor’s address in memory is valid. For example, I’ve successfully used <a href="https://github.com/fish2000/libimread/blob/master/python/im/include/pycapsule.hpp#L18-L30" rel="nofollow">a C++ non-capturing lambda as a destructor</a>, as non-capturing C++ lambdas can be converted to function pointers; if you want to use another way of obtaining and handing off a function pointer for your capsule destructor that works better for you, by all means go for it.</p>
0
2016-09-17T02:51:09Z
[ "python", "c", "cpython" ]
Sorting based on individual columns of lists in a dictionary
39,305,356
<p>I have a dictionary of lists in the following format.</p> <pre><code>b = {'a': [1, 1, 1], 'c': [1, 0, 0], 'b': [1, 0, 1], 'e': [0, 0, 1], 'd': [0, 0, 0], 'g': [0, 1, 1], 'f': [0, 1, 0], 'h': [1, 1, 0] } </code></pre> <p>What I am looking to do is to sort the lists and display the dictionary based on the columns of the lists. The first column should be sorted, next the second column should be sorted with the third column in the last.</p> <p>I want my list like this.</p> <pre><code>b = {'d': [0, 0, 0], 'e': [0, 0, 1], 'f': [0, 1, 0], 'g': [0, 1, 1], 'c': [1, 0, 0], 'b': [1, 0, 1], 'h': [1, 1, 0], 'a': [1, 1, 1] } </code></pre> <p>I can do the sort of the first value of the list like this.</p> <pre><code>sorted(b.items(), key=lambda e:e[1][0]) </code></pre> <p>and similarly do the second and the third. However, if I sort the first column, the second and third would not be sorted.</p> <p>So, I did this.</p> <pre><code>sorted(b.items(), key=lambda e:e[1]) </code></pre> <p>which gives me the right answer. But I am not sure how this is working. </p> <p>Second, if I do,</p> <pre><code>sorted(b.values(), reverse=True, key=lambda e:e[0]) </code></pre> <p>Here, it sorts only the first column of the values while the rest two columns are not sorted.</p> <p>I have my answer, but I am looking for explanations of this is working for some cases and does not work for others.</p> <p>Thanks in advance.</p>
0
2016-09-03T09:27:23Z
39,305,400
<p>This:</p> <pre><code>sorted(b.items(), key=lambda e:e[1]) </code></pre> <p>Works because it uses the entirety of each list as the key for comparison. Python knows how to "lexicographically" compare lists by default, meaning it compares the first element, then if those are equal it proceeds to the next element. Just like sorting words alphabetically.</p>
1
2016-09-03T09:33:08Z
[ "python", "sorting", "dictionary" ]
Sorting based on individual columns of lists in a dictionary
39,305,356
<p>I have a dictionary of lists in the following format.</p> <pre><code>b = {'a': [1, 1, 1], 'c': [1, 0, 0], 'b': [1, 0, 1], 'e': [0, 0, 1], 'd': [0, 0, 0], 'g': [0, 1, 1], 'f': [0, 1, 0], 'h': [1, 1, 0] } </code></pre> <p>What I am looking to do is to sort the lists and display the dictionary based on the columns of the lists. The first column should be sorted, next the second column should be sorted with the third column in the last.</p> <p>I want my list like this.</p> <pre><code>b = {'d': [0, 0, 0], 'e': [0, 0, 1], 'f': [0, 1, 0], 'g': [0, 1, 1], 'c': [1, 0, 0], 'b': [1, 0, 1], 'h': [1, 1, 0], 'a': [1, 1, 1] } </code></pre> <p>I can do the sort of the first value of the list like this.</p> <pre><code>sorted(b.items(), key=lambda e:e[1][0]) </code></pre> <p>and similarly do the second and the third. However, if I sort the first column, the second and third would not be sorted.</p> <p>So, I did this.</p> <pre><code>sorted(b.items(), key=lambda e:e[1]) </code></pre> <p>which gives me the right answer. But I am not sure how this is working. </p> <p>Second, if I do,</p> <pre><code>sorted(b.values(), reverse=True, key=lambda e:e[0]) </code></pre> <p>Here, it sorts only the first column of the values while the rest two columns are not sorted.</p> <p>I have my answer, but I am looking for explanations of this is working for some cases and does not work for others.</p> <p>Thanks in advance.</p>
0
2016-09-03T09:27:23Z
39,305,403
<pre><code>sorted(b.items(), key=lambda e:e[1]) </code></pre> <p>works because the lambda is returning the whole lists, e.g. <code>[1, 1, 1]</code>, <code>[1, 0, 0]</code>. Python's default rule for sorting lists is exactly what you need, it will sort lists by the first 'column' or entry in the list, if two lists have the same first item, then they will be sorted by the second item, and so on.</p>
1
2016-09-03T09:33:26Z
[ "python", "sorting", "dictionary" ]
what is wrong with my code in my continous 1's python program?
39,305,428
<p>so i am a newbie so be easy on me i was just trying to solve a problem in hackerrank.com in which i must get the max number of continous 1's in a binary representation of number and i made it but it is not working Heres the Code</p> <p>the updated code is below</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>import statistics # Get the input using the variable Getinput Getinput = int(input()) # def a function names 1 seq def one_seq(n): main = [] # get the binary of the number taken into input # convert the binary number to a string number = "{0:b}".format(n) # i = 0 i = 0 # sub_main =[] sub_main = [] #a while loop while i != len(number)-1: #if number[i] == "1": if number[i] == "1": sub_main.append(number[i]) #else definately 0 so append sub_main to main and sub_main = [] else: main.append(sub_main) sub_main = [] i+=1 # greatest 1 = len(x) for element in main #greatest_one = [len(element) for element in main ] greatest_one = [len(element) for element in main] #return greatest_one return max(greatest_one) print(len(one_seq(Getinput)))</code></pre> </div> </div> </p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>import statistics # Get the input using the variable Getinput # def a function names 1 seq def one_seq(n): main = [] # get the binary of the number taken into input # convert the binary number to a string number = str("{0:b}".format(n)) # i = 0 i = 0 # sub_main =[] sub_main = [] #a while loop set to True while i != len(number): #if number[i] == 1: if number[i] == 1: sub_main.append(number[i]) #else definately 0 so append sub_main to main and sub_main = [] else: main.append(sub_main) sub_main = [] continue i+=1 # greatest 1 = len(x) for element in main greatest_one = [len(element) for element in main ] return statistics.mode(greatest_one) one_seq(2) </code></pre> </div> </div> </p>
-3
2016-09-03T09:36:53Z
39,305,534
<p>You're close. I'll annotate your mistakes to point you in the right direction,</p> <pre><code>import statistics def one_seq(n): main = [] number = str("{0:b}".format(n)) i = 0 sub_main = [] while i != len(number): if number[i] == 1: # you want to check against the string '1' not the number 1 sub_main.append(number[i]) else: main.append(sub_main) sub_main = [] continue # this will skip the i+=1 and cause an infinite loop i+=1 greatest_one = [len(element) for element in main ] return statistics.mode(greatest_one) # There's no reason to use mode here. # You want the greatest element in the list # Not the most common. </code></pre> <p>Remember if you get stuck you can always insert prints everywhere.</p> <h3>Ints and strings</h3> <pre><code>number = 11 # binary 1100101 binary = str("{0:b}".format(number)) print(binary[0] == 1) # prints False print(binary[0] == '1') # prints True </code></pre> <p>The important thing to keep in mind is that the variable binary is a <code>str</code>. In Python a string is written 'hello' or '0', while an int is written 0 or 1 or 3562. When an int is compared to a string using == it will always return False.</p> <h3>The meaning of continue</h3> <pre><code>while True: print('This be printed over and over') continue print('This will never be printed') </code></pre> <p>Continue skips the rest of an iteration of a loop.</p> <h3>Finding the max of a list</h3> <pre><code>mylist = [8, 2, 4, 68, 7] largest = max(mylist) print(largest) # prints 68 </code></pre> <h1>The solution</h1> <pre><code>def one_seq(n): main = [] number = str("{0:b}".format(n)) print(number) i = 0 sub_main = [] while i != len(number): if number[i] == '1': # Changed 1 to '1' sub_main.append(number[i]) else: main.append(sub_main) sub_main = [] # Removed continue i+=1 main.append(sub_main) # This is something I missed earlier # this fixes an issue with numbers # ending with 1s. greatest_one = [len(element) for element in main ] return max(greatest_one) # Used max instead of mode </code></pre> <h1>Simplified</h1> <p>I would probably write it like this</p> <pre><code>def one_seq(n): current = 0 longest = 0 for digit in '{0:b}'.format(n): if digit == '1': current += 1 else: longest = max(current, longest) current = 0 longest = max(current, longest) return longest </code></pre>
1
2016-09-03T09:48:07Z
[ "python" ]
embed python in c++, crashes on "import shutil"
39,305,523
<p>I have a complete example on embedding python in c++ below. I compile/link it on Linux against Python 2.7.</p> <p>It takes one parameter (a filename) which is then loaded and executed.</p> <p>All this basically works but if in the code there is: import shutils</p> <p>Then executing the code fails with a bus error.</p> <p>It seems this is related to the underlying "import collections".</p> <p>The code that I load runs normally when I just execute it as a python script.</p> <p>Has anybody got a hint why the code crashes? The code is made up from several examples and should just normally work.</p> <p>Here is the C++ code:</p> <pre><code>#include "Python.h" // must be first #include "structmember.h" #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #define QWE printf("%s %i\n", __FUNCTION__, __LINE__); #define LIBPY_NAMESPACE "app" #define LIBPY_TYPE "App" #define LIBPY_FQTYPE LIBPY_NAMESPACE "." LIBPY_TYPE static PyObject* globals; static PyObject* locals; static PyObject* mod; static PyObject* app_class; static PyObject* AppError; typedef struct { PyObject_HEAD } AppObject; static PyObject* app_func1(AppObject* self, PyObject* args) { PyObject* ret; int p1, p2; if(PyArg_ParseTuple(args, "dd", &amp;p1, &amp;p2)) { // try { ret = Py_BuildValue("(i,i,i,i)", 13, 17, 19, 11 + p1 + p2); return ret; /* } catch(RiException&amp; e) { PyErr_SetString(RiError, e.what()); } */ } return NULL; } static PyObject* app_func2(AppObject* self, PyObject* args) { PyObject* ret; ret = Py_BuildValue("(i,i,i,i)", 4, 13, 17, 19); return ret; } static PyObject* app_filename(AppObject* self, PyObject* args) { PyObject* ret; const char* c = "a filename"; // ret = Py_BuildValue("(i,i,i,i)", 4, 13, 17, 19); ret = Py_BuildValue("s", c); return ret; } static PyMethodDef app_global_methods[] = { {"filename", (PyCFunction)app_filename, METH_VARARGS, "an example for a global function"}, // get file name {NULL, NULL, 0, NULL} }; static PyMethodDef app_methods[] = { {"func1", (PyCFunction)app_func1, METH_VARARGS, "a test function 1."}, {"func2", (PyCFunction)app_func2, METH_NOARGS, "a test function 2."} }; static PyMemberDef app_members[] = { // {"width", T_INT, offsetof(RiMem, w), 0, ""}, {NULL} }; static PyObject* app_repr(PyObject* par) { AppObject* self = (AppObject*)par; return PyString_FromFormat("&lt;%s %i&gt;", "wx Application", 4); } static PyObject* app_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { AppObject *self; QWE; self = (AppObject *)type-&gt;tp_alloc(type, 0); if(self != NULL) { // self-&gt;app = NULL; } return (PyObject *)self; } static int app_init(AppObject* self, PyObject* args, PyObject* kwds) { // self-&gt;app = m_app; QWE; PyErr_Clear(); // PyErr_SetString(RiError, "some error happened"); return 0; } static void app_dealloc(AppObject* self) { QWE; /* if(self-&gt;app != NULL) { // delete the app self-&gt;app = NULL; } */ self-&gt;ob_type-&gt;tp_free((PyObject*)self); } static PyTypeObject AppType = { PyObject_HEAD_INIT(NULL) 0, /*ob_size*/ LIBPY_FQTYPE, /*tp_name*/ sizeof(AppObject), /*tp_basicsize*/ 0, /*tp_itemsize*/ (destructor)app_dealloc, /*tp_dealloc*/ 0, /*tp_print*/ 0, /*tp_getattr*/ 0, /*tp_setattr*/ 0, /*tp_compare*/ app_repr, /*tp_repr*/ 0, /*tp_as_number*/ 0, /*tp_as_sequence*/ 0, /*tp_as_mapping*/ 0, /*tp_hash */ 0, /*tp_call*/ 0, /*tp_str*/ 0, /*tp_getattro*/ 0, /*tp_setattro*/ 0, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/ "An example application", /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ app_methods, /* tp_methods */ app_members, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ (initproc)app_init, /* tp_init */ 0, /* tp_alloc */ app_new, /* tp_new */ }; void init_py(void) { Py_SetProgramName("qwe"); Py_Initialize(); #if 0 globals = PyDict_New(); PyDict_SetItemString(globals, "__builtins__", PyEval_GetBuiltins()); #else globals = PyModule_GetDict(PyImport_AddModule("__main__")); #endif printf("globals %p\n", globals); /* if (PyType_Ready(&amp;AppType) &lt; 0) { return; } */ mod = Py_InitModule3(LIBPY_NAMESPACE, app_global_methods, "an example app module"); locals = PyModule_GetDict(mod); Py_INCREF(&amp;AppType); PyModule_AddObject(mod, LIBPY_TYPE, (PyObject *)&amp;AppType); PyModule_AddIntConstant(mod, "CONST1", 11); PyModule_AddIntConstant(mod, "CONST2", 13); app_class = PyObject_GetAttrString(mod, LIBPY_TYPE); AppError = PyErr_NewException((char*)LIBPY_FQTYPE "Error", NULL, NULL); Py_INCREF(AppError); PyModule_AddObject(mod, LIBPY_TYPE "Error", AppError); // PyRun_SimpleString("from time import time,ctime\nprint 'Today is',ctime(time())\n"); // Py_Finalize(); } char* load_file(const char* fname) { FILE* fd; long pos; size_t len; char* data; fd = fopen(fname, "rb"); assert(fd != NULL); fseek(fd, 0, SEEK_END); pos = ftell(fd); fseek(fd, 0, SEEK_SET); data = (char*)malloc(pos+1); assert(data != NULL); len = fread(data, 1, pos, fd); assert(len == (size_t)pos); data[pos] = 0; return data; } int main(int argc, char** argv) { char* c; PyObject* val; printf("Hi there\n"); if(argc != 2) { printf("need one parameter\n"); exit(-1); } init_py(); c = load_file(argv[1]); printf("script &lt;%s&gt;\n", c); QWE; #if 1 PyRun_SimpleString(c); #else val = PyRun_String(c, Py_file_input, globals, locals); QWE; if(val == NULL) { PyErr_Print(); } else { Py_DECREF(val); } #endif QWE; return 0; } </code></pre> <p>A Python script that fails is:</p> <pre><code>#! /usr/bin/python #coding: latin-1 #from app import * import os import shutil import sys import stat import fnmatch import collections #print filename() </code></pre> <p>So when compiling the code and then calling it with a parameter (file containing the python code) it results in a bus error.</p> <p>Compiling the code above as C or C++ gives the same result. I'm interested in getting it to work with C++.</p> <p>Can anybody at least reproduce the problem?</p>
0
2016-09-03T09:47:20Z
39,305,657
<p>May be it is related to GIL problem, try this: <a href="https://docs.python.org/3/c-api/init.html#non-python-created-threads" rel="nofollow">https://docs.python.org/3/c-api/init.html#non-python-created-threads</a></p>
0
2016-09-03T10:00:58Z
[ "python", "c++", "python-2.7", "embed" ]
embed python in c++, crashes on "import shutil"
39,305,523
<p>I have a complete example on embedding python in c++ below. I compile/link it on Linux against Python 2.7.</p> <p>It takes one parameter (a filename) which is then loaded and executed.</p> <p>All this basically works but if in the code there is: import shutils</p> <p>Then executing the code fails with a bus error.</p> <p>It seems this is related to the underlying "import collections".</p> <p>The code that I load runs normally when I just execute it as a python script.</p> <p>Has anybody got a hint why the code crashes? The code is made up from several examples and should just normally work.</p> <p>Here is the C++ code:</p> <pre><code>#include "Python.h" // must be first #include "structmember.h" #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #define QWE printf("%s %i\n", __FUNCTION__, __LINE__); #define LIBPY_NAMESPACE "app" #define LIBPY_TYPE "App" #define LIBPY_FQTYPE LIBPY_NAMESPACE "." LIBPY_TYPE static PyObject* globals; static PyObject* locals; static PyObject* mod; static PyObject* app_class; static PyObject* AppError; typedef struct { PyObject_HEAD } AppObject; static PyObject* app_func1(AppObject* self, PyObject* args) { PyObject* ret; int p1, p2; if(PyArg_ParseTuple(args, "dd", &amp;p1, &amp;p2)) { // try { ret = Py_BuildValue("(i,i,i,i)", 13, 17, 19, 11 + p1 + p2); return ret; /* } catch(RiException&amp; e) { PyErr_SetString(RiError, e.what()); } */ } return NULL; } static PyObject* app_func2(AppObject* self, PyObject* args) { PyObject* ret; ret = Py_BuildValue("(i,i,i,i)", 4, 13, 17, 19); return ret; } static PyObject* app_filename(AppObject* self, PyObject* args) { PyObject* ret; const char* c = "a filename"; // ret = Py_BuildValue("(i,i,i,i)", 4, 13, 17, 19); ret = Py_BuildValue("s", c); return ret; } static PyMethodDef app_global_methods[] = { {"filename", (PyCFunction)app_filename, METH_VARARGS, "an example for a global function"}, // get file name {NULL, NULL, 0, NULL} }; static PyMethodDef app_methods[] = { {"func1", (PyCFunction)app_func1, METH_VARARGS, "a test function 1."}, {"func2", (PyCFunction)app_func2, METH_NOARGS, "a test function 2."} }; static PyMemberDef app_members[] = { // {"width", T_INT, offsetof(RiMem, w), 0, ""}, {NULL} }; static PyObject* app_repr(PyObject* par) { AppObject* self = (AppObject*)par; return PyString_FromFormat("&lt;%s %i&gt;", "wx Application", 4); } static PyObject* app_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { AppObject *self; QWE; self = (AppObject *)type-&gt;tp_alloc(type, 0); if(self != NULL) { // self-&gt;app = NULL; } return (PyObject *)self; } static int app_init(AppObject* self, PyObject* args, PyObject* kwds) { // self-&gt;app = m_app; QWE; PyErr_Clear(); // PyErr_SetString(RiError, "some error happened"); return 0; } static void app_dealloc(AppObject* self) { QWE; /* if(self-&gt;app != NULL) { // delete the app self-&gt;app = NULL; } */ self-&gt;ob_type-&gt;tp_free((PyObject*)self); } static PyTypeObject AppType = { PyObject_HEAD_INIT(NULL) 0, /*ob_size*/ LIBPY_FQTYPE, /*tp_name*/ sizeof(AppObject), /*tp_basicsize*/ 0, /*tp_itemsize*/ (destructor)app_dealloc, /*tp_dealloc*/ 0, /*tp_print*/ 0, /*tp_getattr*/ 0, /*tp_setattr*/ 0, /*tp_compare*/ app_repr, /*tp_repr*/ 0, /*tp_as_number*/ 0, /*tp_as_sequence*/ 0, /*tp_as_mapping*/ 0, /*tp_hash */ 0, /*tp_call*/ 0, /*tp_str*/ 0, /*tp_getattro*/ 0, /*tp_setattro*/ 0, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/ "An example application", /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ app_methods, /* tp_methods */ app_members, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ (initproc)app_init, /* tp_init */ 0, /* tp_alloc */ app_new, /* tp_new */ }; void init_py(void) { Py_SetProgramName("qwe"); Py_Initialize(); #if 0 globals = PyDict_New(); PyDict_SetItemString(globals, "__builtins__", PyEval_GetBuiltins()); #else globals = PyModule_GetDict(PyImport_AddModule("__main__")); #endif printf("globals %p\n", globals); /* if (PyType_Ready(&amp;AppType) &lt; 0) { return; } */ mod = Py_InitModule3(LIBPY_NAMESPACE, app_global_methods, "an example app module"); locals = PyModule_GetDict(mod); Py_INCREF(&amp;AppType); PyModule_AddObject(mod, LIBPY_TYPE, (PyObject *)&amp;AppType); PyModule_AddIntConstant(mod, "CONST1", 11); PyModule_AddIntConstant(mod, "CONST2", 13); app_class = PyObject_GetAttrString(mod, LIBPY_TYPE); AppError = PyErr_NewException((char*)LIBPY_FQTYPE "Error", NULL, NULL); Py_INCREF(AppError); PyModule_AddObject(mod, LIBPY_TYPE "Error", AppError); // PyRun_SimpleString("from time import time,ctime\nprint 'Today is',ctime(time())\n"); // Py_Finalize(); } char* load_file(const char* fname) { FILE* fd; long pos; size_t len; char* data; fd = fopen(fname, "rb"); assert(fd != NULL); fseek(fd, 0, SEEK_END); pos = ftell(fd); fseek(fd, 0, SEEK_SET); data = (char*)malloc(pos+1); assert(data != NULL); len = fread(data, 1, pos, fd); assert(len == (size_t)pos); data[pos] = 0; return data; } int main(int argc, char** argv) { char* c; PyObject* val; printf("Hi there\n"); if(argc != 2) { printf("need one parameter\n"); exit(-1); } init_py(); c = load_file(argv[1]); printf("script &lt;%s&gt;\n", c); QWE; #if 1 PyRun_SimpleString(c); #else val = PyRun_String(c, Py_file_input, globals, locals); QWE; if(val == NULL) { PyErr_Print(); } else { Py_DECREF(val); } #endif QWE; return 0; } </code></pre> <p>A Python script that fails is:</p> <pre><code>#! /usr/bin/python #coding: latin-1 #from app import * import os import shutil import sys import stat import fnmatch import collections #print filename() </code></pre> <p>So when compiling the code and then calling it with a parameter (file containing the python code) it results in a bus error.</p> <p>Compiling the code above as C or C++ gives the same result. I'm interested in getting it to work with C++.</p> <p>Can anybody at least reproduce the problem?</p>
0
2016-09-03T09:47:20Z
39,358,193
<p>I found 2 errors in my code above, one is that app_methods has no end entry that tells python where to stop interpreting the list.</p> <p>The other one is that it is really necessary to call PyType_Ready(&amp;AppType). I used the code above before and back then (I think with Python 2.6) using PyType_Ready() was creating a bus error.</p> <p>It is also important to use pythonx.y-config --cflags / --ldflags when compiling the code.</p>
0
2016-09-06T21:35:53Z
[ "python", "c++", "python-2.7", "embed" ]
Ending a Python TCP connection
39,305,686
<p>I'm new to socket programming and currently trying to learn it using Python</p> <p>Currently I'm confused over when a receiving application knows when the sending application finished sending data.</p> <p>For example, in Python, reading from a TCP socket is done using </p> <pre><code>socket.recv(bufsize [, flags]) </code></pre> <p>which returns a bytearray of the data received. if there is more data (e.g. in the buffer), we simply call this method again. My current pattern looks like this.</p> <pre><code>while True: buffer = socket.recv(1024) file.write(buffer) </code></pre> <p>However, how do I know when the peer has stopped sending data and exit the loop? Because if this method returns 0 bytes, there's 2 possibilities:</p> <ol> <li><p>the buffer is empty, and the peer is still sending data</p></li> <li><p>the buffer is empty, the peer has closed </p></li> </ol> <p>My question is, how does the receiving application differentiate between scenario 1 and 2</p>
0
2016-09-03T10:05:02Z
39,306,398
<p>buffer will return an empty array only if the client closes the connection.</p> <p>If the client sends nothing, since TCP call is blocking in your case, the program stays blocked forever on <code>recv</code> until data arrives or connection is closed (in which case data arrives empty).</p> <p>(It's the same thing when you read a file on disk: you read data until data returns empty string/byte array: then you know you reached the end of the file)</p>
0
2016-09-03T11:28:29Z
[ "python", "sockets", "networking", "tcp" ]
Read file into dataframe spliting the text after the first word in python
39,305,748
<p>I have a file of strings <code>file.txt</code>, where the first word is a class name and the rest is a description, like the following:</p> <pre><code>n01440764 tench, Tinca tinca n01443537 goldfish, Carassius auratus n01484850 great white shark, white shark, man-eater, man-eating shark, Carcharodon carcharias </code></pre> <p>I would like to read the file into a dataframe of two columns <code>df['class']</code> with the class and <code>df['description']</code> with the rest of the content.</p>
1
2016-09-03T10:13:11Z
39,306,040
<p>You could do:</p> <pre><code>df = pd.read_csv(data, sep='\s{2,}', engine='python', names=['col']) df['class'] = df['col'].str.split().apply(lambda x: x[0]) # Splitting on first occurence of whitespace df['description'] = df['col'].str.join('').apply(lambda x: x.split(' ',1)[1]) del(df['col']) print (df) class description 0 n01440764 tench, Tinca tinca 1 n01443537 goldfish, Carassius auratus 2 n01484850 great white shark, white shark, man-eater, man... </code></pre>
1
2016-09-03T10:45:27Z
[ "python", "pandas", "dataframe" ]
matplotlib.use required before other imports clashes with pep8. Ignore or fix?
39,305,810
<p>I have a pythonscript that starts like this:</p> <pre><code>#!/usr/bin/env python import matplotlib matplotlib.use("Agg") from matplotlib.dates import strpdate2num import numpy as np import pylab as pl from cmath import rect, phase </code></pre> <p>It works like a charm, but my editor complains: <code>E402 module level import not at top of file [pep8]</code>.</p> <p>If I move the <code>matplotlib.use("Agg")</code> down, the script will not work.</p> <p>Should I just ignore the error? Or is there a way to fix this?</p> <p><strong>EDIT :</strong> I'm aware that PEP8 says that this is only a suggestion and it may be ignored, but I'm hoping that there exists a nice way to initialise modules without breaking PEP8 guidelines, as I don't think I can make my editor ignore this rule on a per-file-basis.</p> <p><strong>EDIT2 :</strong> I'm using Atom with linter-pylama</p>
0
2016-09-03T10:20:19Z
39,316,470
<p>The solution depends on the <code>linter</code> that is being used. </p> <p>In my case I am using <code>pylama</code> </p> <p>The manual for this <code>linter</code> suggests adding <code># noqa</code> to the end of a line containing an error you wish to suppress.</p> <p>Other linters will have different mechanisms.</p>
0
2016-09-04T11:33:58Z
[ "python", "matplotlib", "pep8" ]
Can I scrape the raw data from highcharts.js?
39,305,877
<p>I want to scrape the data from a page that shows a graph using <code>highcharts.js</code>, and thus I finished to parse all the pages to get to the <a href="http://www.worldweatheronline.com/brussels-weather-averages/be.aspx" rel="nofollow">following page</a>. However, the last page, the one that displays the dataset, uses <code>highcharts.js</code> to show the graph, which it seems to be near impossible to access to the raw data.</p> <p>I use Python 3.5 with BeautifulSoup.</p> <p>Is it still possible to parse it? If so how can I scrape it?</p>
1
2016-09-03T10:27:27Z
39,306,382
<p>The data is in a script tag. You can get the script tag using bs4 and a regex. You could also extract the data using a regex but I like using <a href="https://github.com/scrapinghub/js2xml" rel="nofollow">/js2xml</a> to parse js functions into a xml tree:</p> <pre><code>from bs4 import BeautifulSoup import requests import re import js2xml soup = BeautifulSoup(requests.get("http://www.worldweatheronline.com/brussels-weather-averages/be.aspx").content, "html.parser") script = soup.find("script", text=re.compile("Highcharts.Chart")).text # script = soup.find("script", text=re.compile("precipchartcontainer")).text if you want precipitation data parsed = js2xml.parse(script) print js2xml.pretty_print(parsed) </code></pre> <p>That gives you:</p> <pre><code>&lt;program&gt; &lt;functioncall&gt; &lt;function&gt; &lt;identifier name="$"/&gt; &lt;/function&gt; &lt;arguments&gt; &lt;funcexpr&gt; &lt;identifier/&gt; &lt;parameters/&gt; &lt;body&gt; &lt;var name="chart"/&gt; &lt;functioncall&gt; &lt;function&gt; &lt;dotaccessor&gt; &lt;object&gt; &lt;functioncall&gt; &lt;function&gt; &lt;identifier name="$"/&gt; &lt;/function&gt; &lt;arguments&gt; &lt;identifier name="document"/&gt; &lt;/arguments&gt; &lt;/functioncall&gt; &lt;/object&gt; &lt;property&gt; &lt;identifier name="ready"/&gt; &lt;/property&gt; &lt;/dotaccessor&gt; &lt;/function&gt; &lt;arguments&gt; &lt;funcexpr&gt; &lt;identifier/&gt; &lt;parameters/&gt; &lt;body&gt; &lt;assign operator="="&gt; &lt;left&gt; &lt;identifier name="chart"/&gt; &lt;/left&gt; &lt;right&gt; &lt;new&gt; &lt;dotaccessor&gt; &lt;object&gt; &lt;identifier name="Highcharts"/&gt; &lt;/object&gt; &lt;property&gt; &lt;identifier name="Chart"/&gt; &lt;/property&gt; &lt;/dotaccessor&gt; &lt;arguments&gt; &lt;object&gt; &lt;property name="chart"&gt; &lt;object&gt; &lt;property name="renderTo"&gt; &lt;string&gt;tempchartcontainer&lt;/string&gt; &lt;/property&gt; &lt;property name="type"&gt; &lt;string&gt;spline&lt;/string&gt; &lt;/property&gt; &lt;/object&gt; &lt;/property&gt; &lt;property name="credits"&gt; &lt;object&gt; &lt;property name="enabled"&gt; &lt;boolean&gt;false&lt;/boolean&gt; &lt;/property&gt; &lt;/object&gt; &lt;/property&gt; &lt;property name="colors"&gt; &lt;array&gt; &lt;string&gt;#FF8533&lt;/string&gt; &lt;string&gt;#4572A7&lt;/string&gt; &lt;/array&gt; &lt;/property&gt; &lt;property name="title"&gt; &lt;object&gt; &lt;property name="text"&gt; &lt;string&gt;Average Temperature (°c) Graph for Brussels&lt;/string&gt; &lt;/property&gt; &lt;/object&gt; &lt;/property&gt; &lt;property name="xAxis"&gt; &lt;object&gt; &lt;property name="categories"&gt; &lt;array&gt; &lt;string&gt;January&lt;/string&gt; &lt;string&gt;February&lt;/string&gt; &lt;string&gt;March&lt;/string&gt; &lt;string&gt;April&lt;/string&gt; &lt;string&gt;May&lt;/string&gt; &lt;string&gt;June&lt;/string&gt; &lt;string&gt;July&lt;/string&gt; &lt;string&gt;August&lt;/string&gt; &lt;string&gt;September&lt;/string&gt; &lt;string&gt;October&lt;/string&gt; &lt;string&gt;November&lt;/string&gt; &lt;string&gt;December&lt;/string&gt; &lt;/array&gt; &lt;/property&gt; &lt;property name="labels"&gt; &lt;object&gt; &lt;property name="rotation"&gt; &lt;number value="270"/&gt; &lt;/property&gt; &lt;property name="y"&gt; &lt;number value="40"/&gt; &lt;/property&gt; &lt;/object&gt; &lt;/property&gt; &lt;/object&gt; &lt;/property&gt; &lt;property name="yAxis"&gt; &lt;object&gt; &lt;property name="title"&gt; &lt;object&gt; &lt;property name="text"&gt; &lt;string&gt;Temperature (°c)&lt;/string&gt; &lt;/property&gt; &lt;/object&gt; &lt;/property&gt; &lt;/object&gt; &lt;/property&gt; &lt;property name="tooltip"&gt; &lt;object&gt; &lt;property name="enabled"&gt; &lt;boolean&gt;true&lt;/boolean&gt; &lt;/property&gt; &lt;/object&gt; &lt;/property&gt; &lt;property name="plotOptions"&gt; &lt;object&gt; &lt;property name="spline"&gt; &lt;object&gt; &lt;property name="dataLabels"&gt; &lt;object&gt; &lt;property name="enabled"&gt; &lt;boolean&gt;true&lt;/boolean&gt; &lt;/property&gt; &lt;/object&gt; &lt;/property&gt; &lt;property name="enableMouseTracking"&gt; &lt;boolean&gt;false&lt;/boolean&gt; &lt;/property&gt; &lt;/object&gt; &lt;/property&gt; &lt;/object&gt; &lt;/property&gt; &lt;property name="series"&gt; &lt;array&gt; &lt;object&gt; &lt;property name="name"&gt; &lt;string&gt;Average High Temp (°c)&lt;/string&gt; &lt;/property&gt; &lt;property name="color"&gt; &lt;string&gt;#FF8533&lt;/string&gt; &lt;/property&gt; &lt;property name="data"&gt; &lt;array&gt; &lt;number value="6"/&gt; &lt;number value="8"/&gt; &lt;number value="11"/&gt; &lt;number value="14"/&gt; &lt;number value="19"/&gt; &lt;number value="21"/&gt; &lt;number value="23"/&gt; &lt;number value="23"/&gt; &lt;number value="19"/&gt; &lt;number value="15"/&gt; &lt;number value="9"/&gt; &lt;number value="6"/&gt; &lt;/array&gt; &lt;/property&gt; &lt;/object&gt; &lt;object&gt; &lt;property name="name"&gt; &lt;string&gt;Average Low Temp (°c)&lt;/string&gt; &lt;/property&gt; &lt;property name="color"&gt; &lt;string&gt;#4572A7&lt;/string&gt; &lt;/property&gt; &lt;property name="data"&gt; &lt;array&gt; &lt;number value="2"/&gt; &lt;number value="2"/&gt; &lt;number value="4"/&gt; &lt;number value="6"/&gt; &lt;number value="10"/&gt; &lt;number value="12"/&gt; &lt;number value="14"/&gt; &lt;number value="14"/&gt; &lt;number value="11"/&gt; &lt;number value="8"/&gt; &lt;number value="5"/&gt; &lt;number value="2"/&gt; &lt;/array&gt; &lt;/property&gt; &lt;/object&gt; &lt;/array&gt; &lt;/property&gt; &lt;/object&gt; &lt;/arguments&gt; &lt;/new&gt; &lt;/right&gt; &lt;/assign&gt; &lt;/body&gt; &lt;/funcexpr&gt; &lt;/arguments&gt; &lt;/functioncall&gt; &lt;/body&gt; &lt;/funcexpr&gt; &lt;/arguments&gt; &lt;/functioncall&gt; &lt;/program&gt; </code></pre> <p>So to get all the data:</p> <pre><code>In [28]: from bs4 import BeautifulSoup In [29]: import requests In [30]: import re In [31]: import js2xml In [32]: from itertools import repeat In [33]: from pprint import pprint as pp In [34]: soup = BeautifulSoup(requests.get("http://www.worldweatheronline.com/brussels-weather-averages/be.aspx").content, "html.parser") In [35]: script = soup.find("script", text=re.compile("Highcharts.Chart")).text In [36]: parsed = js2xml.parse(script) In [37]: data = [d.xpath(".//array/number/@value") for d in parsed.xpath("//property[@name='data']")] In [38]: categories = parsed.xpath("//property[@name='categories']//string/text()") In [39]: output = list(zip(repeat(categories), data)) In [40]: pp(output) [(['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'], ['6', '8', '11', '14', '19', '21', '23', '23', '19', '15', '9', '6']), (['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'], ['2', '2', '4', '6', '10', '12', '14', '14', '11', '8', '5', '2'])] </code></pre> <p>Like I said you could just use a regex but <em>js2xml</em> I find is more reliable as erroneous spaces etc.. won't break it.</p>
1
2016-09-03T11:26:47Z
[ "javascript", "python", "highcharts", "web-scraping", "beautifulsoup" ]
python lib for custom hash function
39,305,939
<p>I need a hash function to take a sequence of decimal numbers and return a decimal number as hash value.</p> <p>for example:</p> <pre><code>&gt;&gt; def my_simple_hash(*args): return reduce(lambda x1, x2: 2*x1 + x2, args) &gt;&gt;&gt; my_simple_hash(1,3,4) 14 &gt;&gt;&gt; my_simple_hash(1,4,3) 15 &gt;&gt;&gt; my_simple_hash(4,3,1) 23 </code></pre> <p>My questions are:</p> <ol> <li>does python has a built-in lib to do this more efficiently? </li> <li>how could I make the output hash value in a relative small range?</li> </ol> <p>Question 2 explanation:</p> <p>because 1, 3, 4 has six different combinations as following:</p> <pre><code>1,3,4 1,4,3 3,1,4 3,4,1 4,1,3 4,3,1 </code></pre> <p>the corresponding output is <code>[14, 15, 18, 21, 21, 23]</code>, and I expect the hash values of the <code>six</code> output would be something like <code>[1,2,3,4,6]</code>(a small range)</p> <p>any suggestions would be appreciated. thanks in advance :-)</p>
0
2016-09-03T10:33:13Z
39,306,163
<p>If you just want to hash a number sequence you can do</p> <pre><code>def my_hash(*args): return hash(args) </code></pre> <p>which returns the <a href="https://docs.python.org/3/library/functions.html#hash" rel="nofollow">hash</a> (for the current run of the program) of the args-tuple (<code>hash</code> is fast and well tested for builtin-types) - but this is still most often a large number.</p> <p>For getting a smaller value you can take the modulo like</p> <pre><code>def my_hash(*args): return hash(args)%10 # or whatever number you like </code></pre> <p>Actually you could also use</p> <pre><code>def my_hash(*args): return sum(args)%10 # or whatever number you like </code></pre> <p>which doesnt change between runs of the program but <code>sum</code> does not distribute the results evenly at all.</p> <p><strong>Warning: These are not cryptographical hashes</strong></p>
1
2016-09-03T11:01:40Z
[ "python" ]
openshift is looking for 'wsgi' application, I don't want 'wsgi'
39,305,964
<p>I don't know if you know about this website (as I can't read your mind), but <code>openshift</code> is it. It is a web-hosting website. You can use <code>python</code> or whatever for server-side.</p> <p>The problem is <code>openshift</code> is looking for a <code>wsgi</code> application. But I am using <code>websockets</code> with <code>tornado</code> so I can't use <code>wsgi</code>. How does I make <code>openshift</code> not look for <code>wsgi</code>, but any type of <code>applicaiton</code>? Or does the website only support that.</p> <p>The error message I am seeing is:</p> <pre><code>'wsgi.py' does not contain WSGI application 'application' </code></pre> <p>I really need a server with <code>websockets</code>, I am planning on creating a multiplayer online game with <code>javascript</code> using websockets.</p> <p>Thanks for the help, everyone.</p>
0
2016-09-03T10:37:13Z
39,307,124
<p>Put your application in <code>app.py</code>. This will allow you to run whatever you want. See:</p> <ul> <li><a href="http://blog.dscpl.com.au/2015/08/running-async-web-applications-under.html" rel="nofollow">http://blog.dscpl.com.au/2015/08/running-async-web-applications-under.html</a></li> </ul>
2
2016-09-03T12:54:41Z
[ "python", "openshift", "tornado", "redhat" ]
Plotting particles positions over time
39,306,175
<p>I have drawn one position(x,y,z) of N particles in an enclosed volume.</p> <pre><code>x[i] = random.uniform(a,b) ... </code></pre> <p>I also found the constant velocity(vx,vy,vz) of the N particles.</p> <pre><code>vx[i] = random.gauss(mean,sigma) ... </code></pre> <p>Now I want to find the position of the N(=100) particles over time. I used the Euler-Cromer method to this.</p> <pre><code>delta_t = linspace(0,2,n-1) n = 1000 v[0] = vx;... r[0] = x;... for i in range(n-1): v[i+1,:] = v[i,:] r[i+1,:] = r[i,:] + delta_t*v[i+1,:] t[i+1] = t[i] + delta_t </code></pre> <p>But I want to find the position over time for every particle. How can I do this? Also, how do I plot the particles position over time in 3D?</p>
0
2016-09-03T11:02:35Z
39,307,006
<p>To find the position of the particles at a given time you can use the following code:</p> <pre><code>import numpy as np # assign random positions in the box 0,0,0 to 1,1,1 x = np.random.random((100,3)) # assign random velocities in the range around 0 v = np.random.normal(size=(100,3)) # define function to project the position in time according to # laws of motion. x(t) = x_0 + v_0 * t def position(x_0, v_0, t): return x_0 + v_0*t # get new position at time = 3.2 position(x, v, 3.2) </code></pre>
0
2016-09-03T12:42:29Z
[ "python", "simulation", "particles" ]
using len() in Pandas dataframe
39,306,229
<p>This is the look of my <code>dataframe</code>:</p> <p><img src="http://i.stack.imgur.com/9C22C.png" alt="dataframe"> and I want to list a list of senators whose surname is more than 9 characters long</p> <p>So I think the code should be like this:</p> <pre><code>df[len(df.Surname) &gt;9 ] </code></pre> <p>but there will be a compile error, where did I go wrong?</p>
2
2016-09-03T11:09:13Z
39,306,330
<p>You want that <code>len</code> function to work on strings but you passed a Series. It returns a single value that shows the length of that series. Therefore, <code>len(df['Surname']) &gt; 9</code> returns a True or False. In return, <code>df[len(df['Surname'] &gt; 9]</code> is evaluated as <code>df[True]</code> or <code>df[False]</code>.</p> <p>Instead, you should do something like</p> <pre><code>df[df['Surname'].str.len() &gt; 9] </code></pre> <p>Here, with str accessor, len method is applied to all elements in that Series.</p>
4
2016-09-03T11:21:40Z
[ "python", "pandas", "dataframe" ]
using len() in Pandas dataframe
39,306,229
<p>This is the look of my <code>dataframe</code>:</p> <p><img src="http://i.stack.imgur.com/9C22C.png" alt="dataframe"> and I want to list a list of senators whose surname is more than 9 characters long</p> <p>So I think the code should be like this:</p> <pre><code>df[len(df.Surname) &gt;9 ] </code></pre> <p>but there will be a compile error, where did I go wrong?</p>
2
2016-09-03T11:09:13Z
39,306,524
<p>Have a look at the python <a href="https://docs.python.org/3.4/library/functions.html#filter" rel="nofollow">filter</a> function. It does exactly what you want.</p> <pre><code>df = [ {"Surname": "Bullock-ish"}, {"Surname": "Cash"}, {"Surname": "Reynolds"}, ] longnames = list(filter(lambda s: len(s["Surname"]) &gt; 9, df)) print(longnames) &gt;&gt;[{'Surname': 'Bullock-ish'}] </code></pre> <p>Sytse</p>
0
2016-09-03T11:44:23Z
[ "python", "pandas", "dataframe" ]
Efficiently retrieve data (all in one batch ideally) with mongengine in Python 3
39,306,369
<p>Let's say I have class User which inherits from the Document class (I am using Mongoengine). Now, I want to retrieve all users signed up after some timestamp. Here is the method I am using:</p> <pre><code>def get_users(cls, start_timestamp): return cls.objects(ts__gte=start_timestamp) </code></pre> <p>1000 documents are returned in 3 seconds. This is extremely slow. I have done similar queries in SQL in a couple of miliseconds. I am new to MongoDB and No-SQL in general, so I guess I am doing something terribly wrong.</p> <p>I suspect the retrieval is slow because it is done in several batches. I read somewhere that for PyMongo the batch size is 101, but I do not know if that is same for Mongoengine. </p> <p>Can I change the batch size, so I could get all documents at once. I will know approximately how much data will be retrieved in total. </p> <p>Any other suggestions are very welcome.</p> <p>Thank you! </p>
0
2016-09-03T11:25:07Z
39,325,324
<p>As you suggest there is no way that it should take 3 seconds to run this query. However, the issue is not going to be the performance of the pymongo driver, some things to consider:</p> <ul> <li>Make sure that the <code>ts</code> field is included in the <a href="http://mongoengine-odm.readthedocs.io/guide/defining-documents.html#indexes" rel="nofollow">indexes</a> for the user collection</li> <li>Mongoengine does some aggressive de-referencing so if the 1000 returned user documents have one or more <code>ReferenceField</code> then each of those results in additional queries. <a href="http://mongoengine-odm.readthedocs.io/guide/querying.html#query-efficiency-and-performance" rel="nofollow">There are ways to avoid this.</a></li> <li>Mongoengine provides <a href="http://mongoengine-odm.readthedocs.io/guide/querying.html#aggregation" rel="nofollow">a direct interface</a> to the pymongo method for the <a href="https://docs.mongodb.com/manual/aggregation/#aggregation-pipeline" rel="nofollow">mongodb aggregation framework</a> this is <strong>by far the most efficient way to query mongodb</strong></li> <li>mongodb <a href="https://groups.google.com/forum/#!topic/mongodb-announce/HWfqcK1T034" rel="nofollow">recently released</a> an official python ODM <a href="https://github.com/mongodb/pymodm" rel="nofollow">pymodm</a> in part to provide better default performance than mongoengine</li> </ul>
2
2016-09-05T07:01:50Z
[ "python", "mongodb", "mongoengine" ]
Using variables to insert
39,306,469
<p>I am new to cassandra and trying to insert in Cassandra keyspace using Python. I have a table mytablecassandra created with cql:</p> <pre><code>cqlsh:mykeyspace&gt;&gt;CREATE TABLE mytablecassandra(user text PRIMARY KEY, friendlist list&lt;text&gt;); </code></pre> <p>Here I read a text file and have variables <code>auser</code> and <code>afriend</code></p> <p>Where these variable have values like</p> <p><code>auser = 'ABC'</code> and <code>afriend = ['DEF','GHI','JKL']</code></p> <p>Now I want to insert these variables in my Cassandra table</p> <pre><code>from cassandra.cluster import Cluster cluster = Cluster() session = cluster.connect('mykeyspace') CQLString = """INSERT INTO mytablecassandra(user,friendlist) VALUES (auser, afriend)""" session.execute(CQLString); </code></pre> <p>And get the error</p> <blockquote> <p>ErrorMessage code=2000 [Syntax error in CQL query] no viable alternative at input ')'</p> </blockquote>
0
2016-09-03T11:37:59Z
39,306,610
<p>Your strings don't get expanded in place that way, nor is it really the recommended way (that way lies SQL injection attacks often). Instead you should make your query string have place holders for the values like</p> <pre><code>CQLString = "INSERT INTO mytablecassandra (user, friendlist) VALUES (%s,%s)" </code></pre> <p>then execute it and pass the values in like</p> <pre><code>session.execute(CQLString, (auser,afriend)) </code></pre>
1
2016-09-03T11:55:53Z
[ "python", "cassandra", "insert" ]
Upload image to S3 with python webapp2
39,306,568
<p>I want to upload the image to Amazon S3. I am using webapp2 python. After some exploration i find out that boto could be useful to upload the images to S3. I installed the boto but when i import it the following error occurred:</p> <pre><code> File "C:\Program Files (x86)\Google\google_appengine\google\appengine\tools\devappserver2\python\sandbox.py", line 964, in load_module raise ImportError('No module named %s' % fullname) ImportError: No module named _winreg </code></pre> <p>Import Code:</p> <pre><code>import boto s3 = boto.connect_s3() </code></pre> <p>Python version: 2.7 | Boto latest version.</p> <p>I did not found any example which can help me to start. I am going to use the S3 service for the first time. Can any body help me with it or suggest me any other method which i can use</p> <p>Thank You.</p>
0
2016-09-03T11:49:38Z
39,309,089
<p>Your code seems to have a dependency on the <a href="https://docs.python.org/2/library/_winreg.html" rel="nofollow">_winreg</a> module, as evinced by the error message</p> <blockquote> <p>ImportError: No module named _winreg</p> </blockquote> <p>Since you're running your code on the AppEngine within Windows, the issue may be happening because your code needs Windows registry access, and it is unable to access the _winreg module because AppEngine's sandbox blocks the access. You can find some answers <a href="http://stackoverflow.com/questions/28640983/unable-to-import-winreg-in-python-2-7-9-virtual-environment">here</a>.</p> <p>Try running your code in a local Python environment rather than under AppEngine, and see if that fixes the issue.</p>
0
2016-09-03T16:33:42Z
[ "python", "google-app-engine", "amazon-web-services", "amazon-s3", "boto" ]
Flask blueprint url not found
39,306,579
<p>I'm trying to create a flask app using blueprints, so I have this structure:</p> <pre><code>myapp/ __init__.py static/ templates/ site/ index.html register.html layout.html views/ __init__.py site.py models.py </code></pre> <p><strong>__init__.py</strong></p> <pre><code>from flask import Flask from .views.site import site app = Flask(__name__) app.register_blueprint(site) </code></pre> <p><strong>views/site.py</strong></p> <pre><code>from flask import Blueprint, render_template site = Blueprint('site', __name__) site.route('/') def index(): return render_template('site/index.html') site.route('/register/') def register(): return render_template('site/register.html') </code></pre> <p>When I run the app, and try to go to any of the routes I have, the only thing I gest is a "404 Not Found" and I don't really know what I'm doing wrong, because I'm doing exactly what this book says: <a href="http://exploreflask.com/en/latest/blueprints.html" rel="nofollow" title="Explore Flask - Blueprints">Explore Flask - Blueprints</a></p> <p>Thanks in advance.</p>
-1
2016-09-03T11:51:12Z
39,306,708
<p>You have to prepend <code>@</code> to <code>site.route</code> like the following.</p> <pre><code>from flask import Blueprint, render_template site = Blueprint('site', __name__) @site.route('/') def index(): return render_template('site/index.html') @site.route('/register/') def register(): return render_template('site/register.html') </code></pre>
2
2016-09-03T12:07:21Z
[ "python", "flask" ]
Filter protocols in python
39,306,592
<p>I'm trying to filter certain packets with protocols using user input from a given pcap file and than move the packets to a new pcap file.</p> <p>That the code I made so far: </p> <pre><code># =================================================== # Imports # =================================================== from scapy.all import * from scapy.utils import PcapWriter """ your going to need to install the modules below """ from Tkinter import Tk from tkFileDialog import askopenfilename # =================================================== # Constants # =================================================== #OS commands: #~~~~~~~~~~~~~ if "linux2" in sys.platform: """ linux based system clear command """ CLEAR_COMMAND = "clear" elif "win32" in sys.platform: """ windows based system clear command """ CLEAR_COMMAND = "cls" elif "cygwin" in sys.platform: """ crygwin based clear command """ CLEAR_COMMAND = "printf \"\\033c\"" elif "darwin" in sys.platform: """ mac OS X based clear command """ CLEAR_COMMAND = "printf \'\\33c\\e[3J\'" #Usage string: #~~~~~~~~~~~~~~ FILE_STRING = "please choose a pcap file to use" BROWSE_STRING = "press any key to browser files\n" BAD_PATH_STRING = "bad file please try agien\n" BAD_INPUT_STRING = "bad input please try agien\n" PROTOCOL_STRING = "please enter the protocol you wish to filter\n" NAME_STRING = "please enter the new pcap file name\n" # =================================================== # Code # =================================================== def filter_pcap(): """ filtering from the given pcap file a protocol the user chooce (from any layer in the OSI model) and than asks for a new pcap file name, than filters the given protocol to a new pcap file :param none :return nothing: """ path = file_browse() i = 0 filtertype = raw_input(PROTOCOL_STRING) name = raw_input(NAME_STRING) packs = rdpcap(path) for i in range(len(packs)): if filtertype in packs[i]: wrpcap(name +".pcap", packs[i]) def file_browse(): """ Purpose: It will allow the user to browse files on his computer than it will check if the path is ok and will return it :returns - the path to the chosen pcap file """ path = "test" while ".pcap" not in path: print FILE_STRING raw_input(BROWSE_STRING) os.system(CLEAR_COMMAND) Tk().withdraw() path = askopenfilename() if ".pcap" not in path: print BAD_PATH_STRING return path filter_pcap() </code></pre> <p>Now the problem is that I'm failing to filter the packets correctly.</p> <p>The code need to filter protocols from any layer and any kind.</p> <p>I have checked that thread: <a href="http://stackoverflow.com/questions/2247140/how-can-i-filter-a-pcap-file-by-specific-protocol-using-python">How can I filter a pcap file by specific protocol using python?</a></p> <p>But as you can see it was not answered and the user added the problems I had in the edit, if any one could help me it would be great</p> <p><strong>Example for how it should work:</strong> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~</p> <ol> <li>lets say i use the file "sniff" as my first pcap file and it has 489 packets when 200 from those packets are http packets.</li> </ol> <p>now there is that print:</p> <pre><code>please enter the protocol you wish to filter 'http' </code></pre> <p>and than there is the print: </p> <pre><code>please enter the new pcap file name 'new' </code></pre> <p>the user input was 'http' now the program will search for every packet that run on http protocol and will create a new pcap file called 'new.pcap'.</p> <p>the file 'new.pcap' will contain 200 http packets.</p> <p>now that thing should work with any protocol on the OSI model including protocols like IP, TCP, Ethernet and so on (all the protocols in the ascii model).</p> <p>I have found out that wireshark command line has the option -R and tshark has .protocols, but it dont really work... Can any one check that?</p> <p>edit: i found pyshark but i dont know how to write with it</p>
1
2016-09-03T11:52:58Z
39,316,230
<p>I don't believe that scapy has any functions or methods to support application layer protocols in the way that you are after. However, using sport and dport as a filter will do the trick (provided you are going to see/are expecting default ports). </p> <p>Try something like this:</p> <pre><code>def filter_pcap(filtertype = None): ..... snip ..... # Static Dict of port to protocol values. Like so: protocols = {'http': 80, 'ssh': 22, 'telnet': 21} # Check to see if it is in the list while filtertype not in protocols: filtertype = raw_input(PROTOCOL_STRING) # Name for output file name = raw_input(NAME_STRING) # Read Input File packs = rdpcap(path) # Filters to only TCP packets for packet in packs[TCP]: # Filter only the proto (aka Port) that we want if protocols[filtertype] in packet.sport or protocols[filtertype] in packet.dport : # Write to file wrpcap(name +".pcap", packet) </code></pre>
0
2016-09-04T11:06:06Z
[ "python", "filter", "protocols", "wireshark" ]
Multiple save in model object django
39,306,599
<p>I use driver cassandra for my db backend in django , here is my problem :</p> <p>when I wanna run multiple save in a model object instance , the first one save successfully but the others save wont update my record , here is a example :</p> <pre><code>obj = Mymodel.objects.get(id=2) obj.field1 = 2 obj.save() obj.field2 = 3 obj.save() # this save don't work </code></pre> <p>am I doying right or for every update i should refresh my model object like this :</p> <pre><code>obj = Mymodel.objects.get(id=obj.id) </code></pre> <p>regards</p>
0
2016-09-03T11:53:47Z
39,306,693
<p>Use <code>refresh_from_db</code> method on <code>obj</code> after first save. <a href="https://docs.djangoproject.com/en/1.8/ref/models/instances/#refreshing-objects-from-database" rel="nofollow">Link to docs</a></p> <pre><code>obj.refresh_from_db() </code></pre>
0
2016-09-03T12:05:45Z
[ "python", "django", "cassandra" ]
How to remove defined text (http headers) from a text file
39,306,737
<p>I have a data set of documents containing http headers. I want to go through these documents remove these headers while leaving rest of the text. How can I do that?</p> <pre><code>WARC/1.0 WARC-Type: response WARC-Date: 2012-02-10T21:58:44Z WARC-TREC-ID: clueweb12-0000wb-76-38422 WARC-IP-Address: 207.241.148.80 WARC-Payload-Digest: sha1:W6JMWCNM43FDYNW466OADMH2KDGKJCGR WARC-Target-URI: http://someurl.http WARC-Record-ID: &lt;urn:uuid:5a783f09-f0d8-4564-8f3a-c0d1ace7177b&gt; Content-Type: application/http; msgtype=response Content-Length: 26043 HTTP/1.1 200 OK Date: Fri, 10 Feb 2012 21:58:45 GMT Server: Apache Vary: * PRAGMA: no-cache P3P: CP="IDC DSP COR DEVa TAIa OUR BUS UNI" Cache-Control: max-age=-3600 Expires: Fri, 10 Feb 2012 20:58:45 GMT Connection: close Content-Type: text/html </code></pre>
0
2016-09-03T12:10:34Z
39,307,895
<p>This will do what you say you want. It will leave the original file alone and put the cleaned version into a new file.</p> <pre><code>datafile = 'test1.txt' outputfile = 'output.txt' with open(outputfile, encoding='utf-8', mode='w') as outfile: with open(datafile, encoding='utf-8', mode='r') as infile: foundhdrstart = False for line in infile: if line.strip() == 'WARC/1.0': foundhdrstart = True if foundhdrstart is False: outfile.write(line) if line.strip() == 'Content-Type: text/html': foundhdrstart = False </code></pre>
1
2016-09-03T14:15:47Z
[ "python" ]
twitter bot on heroku error "No web processes running" method=GET path="/favicon.ico"
39,306,809
<p>I made a twitter bot in <code>python 3.5</code> using <code>tweepy</code> which updates status about the New followers everyday. The code runs smoothly on IDLE. I tried to deploy the bot on heroku but it keeps throwing error in the logs :</p> <pre><code>at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" dyno= connect= service= status=503 bytes= </code></pre> <p>After going through similar questions, I tried the commands like :</p> <pre><code>heroku ps:scale web=1 </code></pre> <p>but to no avail. Here is my python program named <code>bot.py</code></p> <pre><code>import tweepy import sys import time import os non_bmp_map = dict.fromkeys(range(0x10000, sys.maxunicode + 1), 0xfffd) CONSUMER_KEY = '' CONSUMER_SECRET = '' ACCESS_TOKEN = '' ACCESS_TOKEN_SECRET = '' auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET) auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET) api = tweepy.API(auth) count=1 Past_Followers = 0 Current_Followers = 0 while(count&gt;0): variable1 = api.get_user('USERNAME') Past_Followers = variable1.followers_count api.update_status(status='Follower count is '+str(Past_Followers)) time.sleep(86400) variable2 = api.get_user('USERNAME') Current_Followers = variable2.followers_count api.update_status(status='Total Followers '+str(Current_Followers)) api.update_status(status='New Followers Today = '+str(Current_Followers - Past_Followers)) count=count+1 print(count) </code></pre> <p>requirements.txt : <code>tweepy==3.5.0</code> ; runtime.txt : <code>python-3.5.2</code> and Procfile : <code>worker: python bot.py </code> <strong>Edit</strong> : Worked using <code>heroku ps:scale worker=1</code></p>
0
2016-09-03T12:21:10Z
39,306,937
<p>The problem is you are trying to run your web process, when the bot is a worker. You want to <code>ps:scale worker=1</code> instead of <code>ps:scale web=1</code>. Web is for processes with <code>web:</code> in your Procfile and they have to be web apps.</p>
0
2016-09-03T12:34:12Z
[ "python", "python-3.x", "heroku", "twitter", "tweepy" ]
Page hangs on Ajax request to GAE
39,306,811
<p>I've created a page that interacts with an app written with Python on GAE, to return JSON data (via JSONP, because Cross-origin stuff). However, no matter what method I use, the page always hangs and data never actually makes it to the screen. It runs just fine if I request the stuff by typing the appspot URL into my address bar, though.</p> <p>Here's the main part of le code.</p> <p>Python main.py (on GAE)</p> <pre><code>def retrieve_data(self): # Retrieve data from some API, manipulate and return result. # Note: I'm not using this handler for the request. # It's just there in case I need it. class MainHandler(webapp2.RequestHandler): def get(self): data = retrieve_data(self) self.response.headers["Content-Type"] = "application/json" self.response.out.write( json.dumps(data) ) # I'm using this handler for the JSONP request. class JSONPHandler(webapp2.RequestHandler): def get(self): data = retrieve_data(self) self.response.headers["Content-Type"] = "application/json" self.response.out.write( "%s(%s)" % (urllib2.unquote(self.request.get("callback")), json.dumps(data)) ) app = webapp2.WSGIApplication([ ('/', MainHandler), ('/jsonp', JSONPHandler) ], debug=True) </code></pre> <p>index.js (Not hosted on GAE)</p> <pre><code>function add(data) { // Sort data, add to DOM. } $.ajax({ type: "GET", dataType: "jsonp", url: "(APPSPOT URL)/jsonp", success: function(data) { add(data) } }); </code></pre> <p>I've also tried $.get, creating a script tag with a src pointing to the appspot link, and other XMLHTTPRequest methods people described, but none seem to work. If I tell success to just console.log the data, it will do so after a few seconds of running.</p> <p>So, is there something wrong with the code? Am I missing something in main.py, or am I AJAXing it wrong?</p>
0
2016-09-03T12:21:17Z
39,307,846
<p>I used this code to receive cross-origin json request POST data in my webapp2 handler:</p> <pre><code>def options(self): self.response.headers['Access-Control-Allow-Origin'] = '*' self.response.headers['Access-Control-Allow-Headers'] = '*' self.response.headers['Access-Control-Allow-Methods'] = 'POST, OPTIONS' def post(self): self.response.headers['Access-Control-Allow-Origin'] = '*' self.response.headers['Access-Control-Allow-Headers'] = '*' self.response.headers['Access-Control-Allow-Methods'] = 'POST, OPTIONS' data = self.request.body args = json.loads(data) </code></pre>
0
2016-09-03T14:10:47Z
[ "javascript", "jquery", "python", "ajax", "google-app-engine" ]
Python Shellexecute windows api with Ctypes over TCP/IP
39,306,920
<p>I have question about running windows API's over TCP/IP protocol. For example, I want to bring remote machine's cmd.exe to other machine (Like Netcat, fully simulating cmd.exe over TCP/IP) . I searched online for doing it with python but couldn't find anything helpful. I can do this using subprocess and other python capabilities but it lacks user-interface problem. I used this kind of code:</p> <pre><code>import socket import subprocess import ctypes HOST = '192.168.1.22' PORT = 443 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((HOST, PORT)) while 1: #send initial cmd.exe banner to remote machine s.send(ctypes.windll.Shell32.ShellExecuteA(None,"open","cmd.exe",None,None,0)) #accept user input data = s.recv(1024) #pass it again to Shellexecute api to execute and return output to remote machine, fully simulating original CMD over TCP/IP s.close() </code></pre> <p>Look at to this picture: <a href="http://i.stack.imgur.com/qI48a.jpg" rel="nofollow">Running CMD over TCP/IP using NetCat tool</a></p>
0
2016-09-03T12:32:51Z
39,339,749
<p>I'm not sure what your need is based on your description is, but I'll try to help you :). </p> <p>If all you want is to activate the CMD.exe on a remote machine with a port being open, you would maybe like to look into a "server script" that will execute any command passed to it. i.e.</p> <pre><code>class MyTCPHandler(socketserver.BaseRequestHandler): """ The RequestHandler class for our server. It is instantiated once per connection to the server, and must override the handle() method to implement communication to the client. """ def handle(self): # self.request is the TCP socket connected to the client self.data = self.request.recv(1024).strip() print("{} wrote:".format(self.client_address[0])) print(self.data) error_code = os.system(self.data.decode('UTF-8')) # just send back the error code so we know if it executed correctly self.request.sendall(error_code) if __file__ is '__main__': HOST, PORT = "localhost", 9999 # Create the server, binding to localhost on port 9999 server = socketserver.TCPServer((HOST, PORT), MyTCPHandler) # Activate the server; this will keep running until you # interrupt the program with Ctrl-C server.serve_forever() </code></pre> <p>*ref :<a href="https://docs.python.org/3.4/library/socketserver.html" rel="nofollow">https://docs.python.org/3.4/library/socketserver.html</a> I don't need to mention that this is really not secure...</p> <p>if you really want to pass it to python on the server side, I think I would put everything received on the socket in a tmp file and execute python over it. Like Ansible do.</p> <p>Let me know if that helped you!</p>
0
2016-09-06T02:24:44Z
[ "python", "windows", "network-programming", "tcp-ip", "netcat" ]
Python EOF error when loop
39,306,922
<p>I need to write a python code to print the input like this:</p> <pre><code>while (True): output = raw_input() print output </code></pre> <p>But when I want to end the loop,I used Ctrl_D,and it says:</p> <pre><code> File "./digits.py", line 6, in &lt;module&gt; output = raw_input() EOFError </code></pre> <p>How can I solve it? If possible please give me some simple way because this is the first time I write in python.</p>
0
2016-09-03T12:33:02Z
39,306,983
<p>Have you considered putting a keyword check in your loop?</p> <pre><code>while (True): output = raw_input() if str(output) == "exit": break print output </code></pre>
-2
2016-09-03T12:39:50Z
[ "python", "eoferror" ]
Python EOF error when loop
39,306,922
<p>I need to write a python code to print the input like this:</p> <pre><code>while (True): output = raw_input() print output </code></pre> <p>But when I want to end the loop,I used Ctrl_D,and it says:</p> <pre><code> File "./digits.py", line 6, in &lt;module&gt; output = raw_input() EOFError </code></pre> <p>How can I solve it? If possible please give me some simple way because this is the first time I write in python.</p>
0
2016-09-03T12:33:02Z
39,307,077
<p>The <code>EOFError</code> is an exception that can be caught with <code>try</code>-<code>except</code>. Here we break the loop using the <code>break</code> keyword if an <code>EOFError</code> is thrown:</p> <pre><code>while True: try: output = raw_input() except EOFError: break print(output) </code></pre>
3
2016-09-03T12:49:24Z
[ "python", "eoferror" ]
Jupyter Notebook BeautifulSoup ImportError
39,306,948
<p>I am new to python dev and have recently installed a fresh, 64-bit version of anaconda (with python v. 2.7.12) yesterday (<a href="https://www.continuum.io/downloads#windows" rel="nofollow">https://www.continuum.io/downloads#windows</a>) on my windows 8 machine. I immediately launched the Jupyter Notebook instance that came with anaconda and expected that I be able to use BeautifulSoup. Upon executing this line in my notebook.ipynb file: <code>from bs4 import BeautifulSoup</code> I received an <code>ImportError</code>: </p> <pre><code>ImportError Traceback (most recent call last) &lt;ipython-input-12-cbb98e44f096&gt; in &lt;module&gt;() 9 #from yelp.oauth1_authenticator import Oauth1Authenticator 10 ---&gt; 11 from bs4 import BeautifulSoup C:\Users\xxx\Anaconda2\lib\site-packages\bs4\__init__.py in &lt;module&gt;() 33 import warnings 34 ---&gt; 35 from .builder import builder_registry, ParserRejectedMarkup 36 from .dammit import UnicodeDammit 37 from .element import ( C:\Users\xxx\Anaconda2\lib\site-packages\bs4\builder\__init__.py in &lt;module&gt;() 313 # to take precedence over html5lib, because it's faster. And we only 314 # want to use HTMLParser as a last result. --&gt; 315 from . import _htmlparser 316 register_treebuilders_from(_htmlparser) 317 try: C:\Users\xxx\Anaconda2\lib\site-packages\bs4\builder\_htmlparser.py in &lt;module&gt;() 8 ] 9 ---&gt; 10 from HTMLParser import HTMLParser 11 12 try: ImportError: cannot import name HTMLParser </code></pre> <p>What I've tried:</p> <ul> <li>pip install HTMLParser</li> <li>pip install bs4</li> <li>Uninstalling and installing beautifulsoup4 and beautifulsoup packages available in the anaconda navigator. </li> <li>conda install HTMLParser --> resulted in package not found on anaconda repos error</li> <li>conda install bs4 --> resulted in package not found on anaconda repos error</li> </ul> <p>I have been trying to get this set up working without virtual environments in the notebook. I thought it would be possible to get it working with the root env.</p> <p>Any help with this issue would be much appreciated!</p>
0
2016-09-03T12:35:21Z
39,322,276
<p>I just restarted my PC and Jupyter Notebook detected the HTMLParser module. Not sure what I did to actually fix it - but I'm guessing the answer is one of the following steps I listed in my original question then restarting and launching Jupyter again. </p>
0
2016-09-04T23:18:08Z
[ "python", "beautifulsoup", "anaconda" ]
List comprehensions adding a value to an element based on a condition
39,306,952
<p>I have written code that returns the unique prime number factors of a given number.Here is that code. This code does not consider that 1 is a unique prime number. The <code>factorial3</code> is the function that returns a list of factorials for any given number.</p> <pre><code> def factorials(n): x=[j for j in range(1, ((n/2)+1)) if n%j==0] x.append(n) return x n=input() numbers=[] for i in range(n): numbers.append(input()) count=[0 for j in numbers] for i,k in enumerate(numbers): for j in factorial3(k): if factorial3(j)==[1,j]: count[i]+=1 </code></pre> <p>The list <code>count</code> gives me the unique prime numbers of numbers inputted.</p> <p>For example, for 2 number 10, 20,the factors are [2,5,10] and [2,5, 10, 20]. However, the unique prime factors are [2,5] and [2,5] respectively. And hence, the count is [2,2]</p> <p>I am trying to achieve the same with list comprehensions but have failed so far.This are the things that I have tried so far.</p> <pre><code>c=[0 for i in numbers] new=[i+1 for i,k in enumerate(numbers) for j in factorial3(k) if factorial3(j)==[1,j]] print new new1=[c[i]+1 for i,k in enumerate(numbers) for j in factorial3(k) if factorial3(j)==[1,j]] print new1 </code></pre> <p>I am almost there, just missing the one thing cuts down the iteration just once.</p>
0
2016-09-03T12:35:41Z
39,307,109
<p>If you want the prime number factors, then simply go up to square root, rather than the whole range.</p> <p>Replace your first line:</p> <pre><code>c=[0 for i in numbers] </code></pre> <p>with:</p> <pre><code>c=[0 for i in numbers**0.5] </code></pre>
0
2016-09-03T12:53:01Z
[ "python" ]
List comprehensions adding a value to an element based on a condition
39,306,952
<p>I have written code that returns the unique prime number factors of a given number.Here is that code. This code does not consider that 1 is a unique prime number. The <code>factorial3</code> is the function that returns a list of factorials for any given number.</p> <pre><code> def factorials(n): x=[j for j in range(1, ((n/2)+1)) if n%j==0] x.append(n) return x n=input() numbers=[] for i in range(n): numbers.append(input()) count=[0 for j in numbers] for i,k in enumerate(numbers): for j in factorial3(k): if factorial3(j)==[1,j]: count[i]+=1 </code></pre> <p>The list <code>count</code> gives me the unique prime numbers of numbers inputted.</p> <p>For example, for 2 number 10, 20,the factors are [2,5,10] and [2,5, 10, 20]. However, the unique prime factors are [2,5] and [2,5] respectively. And hence, the count is [2,2]</p> <p>I am trying to achieve the same with list comprehensions but have failed so far.This are the things that I have tried so far.</p> <pre><code>c=[0 for i in numbers] new=[i+1 for i,k in enumerate(numbers) for j in factorial3(k) if factorial3(j)==[1,j]] print new new1=[c[i]+1 for i,k in enumerate(numbers) for j in factorial3(k) if factorial3(j)==[1,j]] print new1 </code></pre> <p>I am almost there, just missing the one thing cuts down the iteration just once.</p>
0
2016-09-03T12:35:41Z
39,320,273
<p>I was able to achieve what I wanted to with the code below.</p> <pre><code>new1=[i+1 for i,k in enumerate(numbers) for j in factorial3(k) if factorial3(j)==[1,j]] c1={} for i in new1: if i not in c1: c1[i]=1 else: c1[i]+=1 sortedc=[v for k,v in sorted(c1.items(), key=lambda x:x[0])] x=zip(numbers, sortedc) </code></pre> <p>This code does not return the correct value for 1 and works perfectly fine with all other positive integers. I manually added the factorial for 1 towards the end of code.</p>
0
2016-09-04T18:38:58Z
[ "python" ]
Python Extract Text between two strings into Excel
39,306,972
<p>I have a text file like this</p> <pre><code>blablablabla blablablabla Start Hello World End blablabla </code></pre> <p>I want to extract the strings between Start and End and write them into an Excel cell. My code thus far looks like this:</p> <pre><code>import xlsxwriter workbook = xlsxwriter.Workbook("Test1.xlsx") worksheet = workbook.add_worksheet() flist = open("TextTest.txt").readlines() parsing = False for line in flist: if line.startswith("End"): parsing = False if parsing: worksheet.write(1,1,line) if line.startswith("Start"): parsing = True workbook.close() </code></pre> <p>However it returns only an empty workbook. What am I doing wrong?</p>
0
2016-09-03T12:37:47Z
39,307,154
<p>First of all, you seem to be always writing in the line number 1</p> <p>Second, the numeration starts at 0</p> <p>With these two small changes, this should do what you want :</p> <pre><code>parsing = False linewrite=0 for line in liste: if line.startswith("End"): parsing = False if parsing: worksheet.write(linewrite,0,line) print line, linewrite+=1 if line.startswith("Start"): parsing = True workbook.close() </code></pre>
1
2016-09-03T12:57:28Z
[ "python", "excel", "text" ]
Python Extract Text between two strings into Excel
39,306,972
<p>I have a text file like this</p> <pre><code>blablablabla blablablabla Start Hello World End blablabla </code></pre> <p>I want to extract the strings between Start and End and write them into an Excel cell. My code thus far looks like this:</p> <pre><code>import xlsxwriter workbook = xlsxwriter.Workbook("Test1.xlsx") worksheet = workbook.add_worksheet() flist = open("TextTest.txt").readlines() parsing = False for line in flist: if line.startswith("End"): parsing = False if parsing: worksheet.write(1,1,line) if line.startswith("Start"): parsing = True workbook.close() </code></pre> <p>However it returns only an empty workbook. What am I doing wrong?</p>
0
2016-09-03T12:37:47Z
39,307,443
<p>The data is being written to the cell, but one problem is that <code>worksheet.write()</code> will overwrite the contents of the cell, so only the last item written will be present.</p> <p>You can solve this by accumulating the lines between <code>Start</code> and <code>End</code> and then writing them with one <code>worksheet.write()</code>:</p> <pre><code>import xlsxwriter workbook = xlsxwriter.Workbook("Test1.xlsx") worksheet = workbook.add_worksheet() with open("TextTest.txt") as data: lines = [] for line in data: line = line.strip() if line == "Start": lines = [] elif line == "End": worksheet.write(0, 0, '\n'.join(lines)) workbook.close() </code></pre> <p>Here lines are accumulated into a list. When an end line is seen the contents of that list are joined with new lines (you could substitute this for another character, e.g. space) and written to the cell.</p>
1
2016-09-03T13:28:14Z
[ "python", "excel", "text" ]
Python Extract Text between two strings into Excel
39,306,972
<p>I have a text file like this</p> <pre><code>blablablabla blablablabla Start Hello World End blablabla </code></pre> <p>I want to extract the strings between Start and End and write them into an Excel cell. My code thus far looks like this:</p> <pre><code>import xlsxwriter workbook = xlsxwriter.Workbook("Test1.xlsx") worksheet = workbook.add_worksheet() flist = open("TextTest.txt").readlines() parsing = False for line in flist: if line.startswith("End"): parsing = False if parsing: worksheet.write(1,1,line) if line.startswith("Start"): parsing = True workbook.close() </code></pre> <p>However it returns only an empty workbook. What am I doing wrong?</p>
0
2016-09-03T12:37:47Z
39,307,609
<p>I don't have much of a experience with excel stuff in python but you can try openpyxl, I found it much easier to understand.</p> <p>Solution to your problem:</p> <pre><code>import openpyxl wb = openpyxl.Workbook() destination_filename = "my.xlsx" ws = wb.active ws.title = "sheet1" flist = open("text.txt").readlines() row = 1 column = 'A' parsing = False for i in flist: if i.startswith("End"): parsing = False if parsing: coord = column + str(row) ws[coord] = i row += 1 if i.startswith("Start"): parsing = True wb.save(filename = destination_filename) </code></pre> <p>Edit(Writing all lines in one cell):</p> <p>You have to create new variable to which you can add your lines, and at the end you will assign the string variable to cell in worksheet.</p> <pre><code>String="" for i in flist: if i.startswith("End"): parsing = False if parsing: i = i.strip("\n") String += str(i) + "," if i.startswith("Start"): parsing = True ws['A1'] = String wb.save(filename = destination_filename) </code></pre>
1
2016-09-03T13:46:29Z
[ "python", "excel", "text" ]
Display dictionary contents in a label in python tkinter
39,307,128
<p>Ive been trying for a while now but i cant seem to display the contents of a dictionary in a label. I want to hit the display button and when i do, i want all the contents in my dictionary to display, see the code below:</p> <pre><code> import sys from tkinter import * from tkinter import ttk import time from datetime import datetime now= datetime.now() x = [] d = dict() def quit(): print("Have a great day! Goodbye :)") sys.exit(0) def display(): for key in d.keys(): x.append(key) def add(*args): global stock global d stock = stock_Entry.get() Quantity = Quantity_Entry.get() if stock not in d: d[stock] = Quantity else: d[stock] += Quantity root = Tk() root.title("Homework 5 216020088") mainframe = ttk.Frame(root, padding="6 6 20 20") mainframe.grid(column=0, row=0, sticky=(N, W, E, S)) ttk.Label(mainframe, text="you are accesing this on day %s of month %s of %s" % (now.day,now.month,now.year)+" at exactly %s:%s:%s" % (now.hour,now.minute,now.second), foreground="yellow", background="Black").grid(column=0, row = 0) stock_Entry= ttk.Entry(mainframe, width = 60, textvariable="stock") stock_Entry.grid(column=0, row = 1, sticky=W) ttk.Label(mainframe, text="Please enter the stock name").grid(column=1, row = 1, sticky=(N, W, E, S)) Quantity_Entry= ttk.Entry(mainframe, width = 60, textvariable="Quantity") Quantity_Entry.grid(column=0, row = 2, sticky=W) ttk.Label(mainframe, text="Please enter the quantity").grid(column=1, row = 2, sticky=(N, W, E, S)) ttk.Button(mainframe, text="Add", command=add).grid(column=0, row=3, sticky=W) ttk.Button(mainframe, text="Display", command=display).grid(column=0, row=3, sticky=S) ttk.Button(mainframe, text="Exit", command=quit).grid(column=0, row=3, sticky=E) ttk.Label(mainframe, text= x).grid(column=0, row= 4, sticky=W) for child in mainframe.winfo_children(): child.grid_configure(padx=5, pady=5) root.mainloop() </code></pre>
0
2016-09-03T12:55:01Z
39,307,487
<p><code>Label(..., text= x)</code> will display only once - at the start.</p> <p>You have to use <code>StringVar</code> to do what you expect</p> <pre><code>x_var = StringVar() Label(..., texvariable=x_var) </code></pre> <p>Now you can set value in <code>x_var</code> to automatically set new text in <code>Label</code></p> <pre><code>x_var.set( x ) </code></pre> <hr> <p>BTW: instead of</p> <pre><code>for key in d.keys(): x.append(key) </code></pre> <p>probably you should do</p> <pre><code>x = list(d.keys()) </code></pre> <p>or maybe even</p> <pre><code>x = list(d) </code></pre> <hr> <p><strong>EDIT:</strong> display all keys (as in your code) when you press button "Display"</p> <pre><code>import sys from tkinter import * from tkinter import ttk import time from datetime import datetime # --- functions ---- def quit(): print("Have a great day! Goodbye :)") sys.exit(0) def display(): x_var.set( list(d) ) def add(*args): global stock global d stock = stock_Entry.get() Quantity = Quantity_Entry.get() if stock not in d: d[stock] = Quantity else: d[stock] += Quantity # --- main --- x = list() d = dict() now = datetime.now() root = Tk() root.title("Homework 5 216020088") x_var = StringVar() mainframe = ttk.Frame(root, padding="6 6 20 20") mainframe.grid(column=0, row=0, sticky=(N, W, E, S)) ttk.Label(mainframe, text="you are accesing this on day %s of month %s of %s" % (now.day,now.month,now.year)+" at exactly %s:%s:%s" % (now.hour,now.minute,now.second), foreground="yellow", background="Black").grid(column=0, row = 0) stock_Entry= ttk.Entry(mainframe, width = 60, textvariable="stock") stock_Entry.grid(column=0, row = 1, sticky=W) ttk.Label(mainframe, text="Please enter the stock name").grid(column=1, row = 1, sticky=(N, W, E, S)) Quantity_Entry= ttk.Entry(mainframe, width = 60, textvariable="Quantity") Quantity_Entry.grid(column=0, row = 2, sticky=W) ttk.Label(mainframe, text="Please enter the quantity").grid(column=1, row = 2, sticky=(N, W, E, S)) ttk.Button(mainframe, text="Add", command=add).grid(column=0, row=3, sticky=W) ttk.Button(mainframe, text="Display", command=display).grid(column=0, row=3, sticky=S) ttk.Button(mainframe, text="Exit", command=quit).grid(column=0, row=3, sticky=E) ttk.Label(mainframe, textvariable=x_var).grid(column=0, row= 4, sticky=W) for child in mainframe.winfo_children(): child.grid_configure(padx=5, pady=5) root.mainloop() </code></pre>
0
2016-09-03T13:33:03Z
[ "python", "user-interface", "dictionary", "tkinter" ]
Installing 64 bit PyCharm on Windows 10
39,307,152
<p>I have a Windows 10 Home 64-bit installed on a x64 laptop. I also have Python 3.4.3 Anaconda 2.3.0 (64-bit) (default, Mar 6 2015, 12:06:10) [MSC v.1600 64 bit (AMD64)] installed as well as 64-bit versions of Java, Firefox and Tortoise. </p> <p>For some reason when I run the PyCharm installer it only offers me the option of a 32 bit installation (rather irritatingly it doesn't even allow me to download a 64 bit installer from the website). Of course 32-bit PyCharm can't interact with 64-bit Tortoise.</p> <p>So, how can I force PyCharm to install the 64-bit version or do I have to downgrade Tortoise, Java, Firefox etc. to 32-bit? It really shouldn't be this difficult!</p>
1
2016-09-03T12:57:18Z
39,309,498
<p>See <a href="https://intellij-support.jetbrains.com/hc/en-us/articles/206544879-Selecting-the-JDK-version-the-IDE-will-run-under" rel="nofollow">help article</a>from Intellij. The Windows version has a 32bit java JRE download bundled with the installer. If you want to run a 64 bit version you have to install the 64bit JDK yourself as explained in the article.</p>
2
2016-09-03T17:22:46Z
[ "python", "64bit", "pycharm" ]
What function should I use to fix my code?
39,307,190
<p>I'm an amateur trying to code a simple troubleshooter in Python but I'm sure what function I need to use to stop this from happening... <a href="http://i.stack.imgur.com/XJsB1.png" rel="nofollow">enter image description here</a></p> <p>What should I do so the code doesnt continue running if the user inputs yes?</p> <pre><code> TxtFile =open('Answers.txt') lines=TxtFile.readlines() import random def askUser(question): answer = input(question + "? ").lower() Split = answer.split() if any(word in Split for word in KW1): return False elif any(word in Split for word in KW2): return True else: print("Please answer yes or no.") askUser(question) KW1=["didn't", "no",'nope','na'] #NO KW2=["did","yes","yeah","ya","oui","si"] #YES print (lines[0]) print("Nice to meet you, " + input("What is your name? ")) print("Welcome to my troubleshooter") #This is the menu to make the user experience better shooter=True while shooter: print('\n\n1.Enter troubleshooter\n2.Exit\n\n') shooter=input('Press enter to continue: ') if shooter==('2'): print('Ok bye') break words = ('tablet', 'phone', 's7 edge') while True: question = input('What type of device do you have?: ').lower() if any(word in question for word in words): print("Ok, we can help you") break else: print("Either we dont support your device or your answer is too vague") if askUser("Have you tried charging your phone"): print("It needs to personally examined by Apple") else: if askUser("Is it unresponsive"): print (lines[0]) else: print ("Ok") if askUser("Are you using IOS 5.1 or lower"): print (lines[1]) else: if askUser("Have you tried a hard reboot"): print (lines[2]) else: if askUser("Is your device jailbroken"): print (lines[3]) else: if askUser("Do you have a iPhone 5 or later"): print (lines[4]) else: print(lines[5]) print ('Here is your case number, we have stored this on our system') print (random.random()) </code></pre> <p>Here is my code for reference.</p> <p>Edit: Here is the problem <a href="http://i.stack.imgur.com/XJsB1.png" rel="nofollow">enter image description here</a></p> <p>It should just end the code there but it doesnt. I'm not sure how I can fix it</p>
-2
2016-09-03T13:00:52Z
39,307,411
<p>I would recommend moving the following:</p> <pre><code> if askUser("Are you using IOS 5.1 or lower"): print (lines[1]) else: if askUser("Have you tried a hard reboot"): print (lines[2]) else: if askUser("Is your device jailbroken"): print (lines[3]) else: if askUser("Do you have a iPhone 5 or later"): print (lines[4]) else: print(lines[5]) print ('Here is your case number, we have stored this on our system') print (random.random()) </code></pre> <p>into the else part of:</p> <pre><code>if askUser("Is it unresponsive"): </code></pre> <p>Hope this helps.</p>
-2
2016-09-03T13:25:19Z
[ "python" ]
ImportError: No module named pynotify, despite having the module installed
39,307,218
<pre><code>&gt;&gt;&gt; import pynotify Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ImportError: No module named pynotify &gt;&gt;&gt; </code></pre> <p>I have installed py-notify module. This is the error I'm getting when I import it and I'm losing my mind thinking about it.</p> <p>I just wonder if it's the problem with the path. When I print out <code>sys.path</code>, I get this output. Any suggestions?</p> <pre><code>&gt;&gt;&gt; import sys &gt;&gt;&gt; for x in sys.path: ... print x ... /usr/local/lib/python2.7/site-packages/distribute-0.6.14-py2.7.egg /usr/local/Cellar/python/2.7.12/Frameworks/Python.framework/Versions/2.7/li b/python27.zip /usr/local/Cellar/python/2.7.12/Frameworks/Python.framework/Versions/2.7/lib/python2.7 /usr/local/Cellar/python/2.7.12/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-darwin /usr/local/Cellar/python/2.7.12/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac /usr/local/Cellar/python/2.7.12/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac/lib-scriptpackages /usr/local/Cellar/python/2.7.12/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk /usr/local/Cellar/python/2.7.12/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-old /usr/local/Cellar/python/2.7.12/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload /usr/local/lib/python2.7/site-packages /usr/local/lib/python2.7/site-packages/gtk-2.0 /usr/local/lib/python2.7/site-packages/gtk-2.0 &gt;&gt;&gt; </code></pre>
1
2016-09-03T13:02:33Z
39,307,356
<p>By reading the <a href="http://home.gna.org/py-notify/tutorial.html" rel="nofollow">tutorial</a> on <code>py-notify</code> you will clearly see how you are <em>supposed</em> to import it. </p> <p>You are supposed to use:</p> <pre><code>import notify </code></pre> <p>Here is a full example of me pip installing py-notify in a new python 2 virtualenv, replicating your problem, and then importing properly, per what the tutorial stated: </p> <pre><code>▶ pip install py-notify Collecting py-notify Using cached py-notify-0.3.1.tar.gz Building wheels for collected packages: py-notify Running setup.py bdist_wheel for py-notify ... done Stored in directory: /Users/####/Library/Caches/pip/wheels/50/af/6b/dd4386701fdb578f06c4c52e1dea195ae43b8bf9a7d0320e16 Successfully built py-notify Installing collected packages: py-notify Successfully installed py-notify-0.3.1 (venv2) ~/dev/rough ▶ python Python 2.7.10 (default, Oct 23 2015, 19:19:21) [GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang-700.0.59.5)] on darwin Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import pynotify Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ImportError: No module named pynotify &gt;&gt;&gt; import notify &gt;&gt;&gt; dir(notify) ['__builtins__', '__doc__', '__docformat__', '__file__', '__name__', '__package__', '__path__', '__version__', 'version_tuple'] &gt;&gt;&gt; </code></pre>
1
2016-09-03T13:19:25Z
[ "python", "pynotify" ]
mocking a parent class
39,307,257
<p>I have a <code>Parent</code> class that is inherited by a lot of <code>ChildX</code> classes.</p> <pre><code>class Parent(object): # the class that should be mocked def __init__(self): assert False # should never happen, because we're supposed to use the mock instead class Child1(Parent): def method_1(self): return 3 class MockParent(object): # this one should replace Parent def __init__(self): assert True </code></pre> <p>I have a test suite to run with pytest, and I want to make sure that, during these tests, everytime a <code>ChildX</code> is instanciated, the instance would call <code>MockParent</code>'s methods instead of the <code>Parent</code>'s ones (I simplified a lot the example above, the <code>__init__</code> method is not the only one concerned).</p> <p>For the moment, all I've managed to do was to patch every <code>ChildX</code> class one by one:</p> <pre><code>class FixturePatcher(object): def __init__(self, klass): self.klass = klass self.patcher = None def __enter__(self): self.patcher = mock.patch.object(self.klass, '__bases__', (MockParent,)) return self.patcher.__enter__() def __exit__(self, *_, **__): self.patcher.is_local = True @pytest.fixture() def mock_parent_on_child1(): with FixturePatcher(Child1): return Child1() def test_mock_child1(mock_parent_on_child1): assert mock_parent_on_child1.method_1() == 3 </code></pre> <p>But I have many <code>ChildX</code> classes and sometimes <code>ChildY</code> is instanciated and used inside a method of <code>ChildZ</code>, so I can't patch them all.</p> <p>I've tried many things to replace <code>Parent</code> by <code>MockParent</code>, but none of them worked. Here are some of my failed attempts:</p> <pre><code>@mock.patch('src.parent.Parent', MockParent) def test_mock_parent(): assert Child1().method_1() == 3 # Parent's __init__ method is still called @mock.patch('src.parent.Parent.__getattribute__', lambda self, name: MockParent.__getattribute__(self, name)) def test_mock_parent(): assert Child1().method_1() == 3 # same results here def test_mock_parent(monkeypatch): monkeypatch.setattr('src.parent.Parent', MockParent) assert Child1().method_1() == 3 # and still the same here </code></pre> <p>Is this even possible? I'm using python2.7 and the up-to-date versions of <code>pytest</code> and <code>mock</code>.</p>
0
2016-09-03T13:06:54Z
39,307,310
<p>No, it's not possible. The definitions of Child1 and Parent - including the inheritance of one from the other - are executed as soon as the module they are in is imported. There is no opportunity to get in before that and change the inheritance hierarchy.</p> <p>The best you could do would be to move the definitions to some kind of factory function, which could dynamically define the parent of Child1 depending on what it was called with. </p>
1
2016-09-03T13:13:42Z
[ "python", "mocking", "py.test" ]
mocking a parent class
39,307,257
<p>I have a <code>Parent</code> class that is inherited by a lot of <code>ChildX</code> classes.</p> <pre><code>class Parent(object): # the class that should be mocked def __init__(self): assert False # should never happen, because we're supposed to use the mock instead class Child1(Parent): def method_1(self): return 3 class MockParent(object): # this one should replace Parent def __init__(self): assert True </code></pre> <p>I have a test suite to run with pytest, and I want to make sure that, during these tests, everytime a <code>ChildX</code> is instanciated, the instance would call <code>MockParent</code>'s methods instead of the <code>Parent</code>'s ones (I simplified a lot the example above, the <code>__init__</code> method is not the only one concerned).</p> <p>For the moment, all I've managed to do was to patch every <code>ChildX</code> class one by one:</p> <pre><code>class FixturePatcher(object): def __init__(self, klass): self.klass = klass self.patcher = None def __enter__(self): self.patcher = mock.patch.object(self.klass, '__bases__', (MockParent,)) return self.patcher.__enter__() def __exit__(self, *_, **__): self.patcher.is_local = True @pytest.fixture() def mock_parent_on_child1(): with FixturePatcher(Child1): return Child1() def test_mock_child1(mock_parent_on_child1): assert mock_parent_on_child1.method_1() == 3 </code></pre> <p>But I have many <code>ChildX</code> classes and sometimes <code>ChildY</code> is instanciated and used inside a method of <code>ChildZ</code>, so I can't patch them all.</p> <p>I've tried many things to replace <code>Parent</code> by <code>MockParent</code>, but none of them worked. Here are some of my failed attempts:</p> <pre><code>@mock.patch('src.parent.Parent', MockParent) def test_mock_parent(): assert Child1().method_1() == 3 # Parent's __init__ method is still called @mock.patch('src.parent.Parent.__getattribute__', lambda self, name: MockParent.__getattribute__(self, name)) def test_mock_parent(): assert Child1().method_1() == 3 # same results here def test_mock_parent(monkeypatch): monkeypatch.setattr('src.parent.Parent', MockParent) assert Child1().method_1() == 3 # and still the same here </code></pre> <p>Is this even possible? I'm using python2.7 and the up-to-date versions of <code>pytest</code> and <code>mock</code>.</p>
0
2016-09-03T13:06:54Z
39,311,813
<p>I can't think of a way to replace <code>Parent</code> with <code>MockParent</code> everywhere where it is used, but you could monkeypatch <code>Parent</code>'s methods instead, if that is what you are after:</p> <pre><code>class Parent(object): def my_method(self): print 'my method' class Child(Parent): def run(self): self.my_method() child = Child() child.run() # prints: my method ### Apply the monkeypatch: ### def my_method(self): print 'something else' Parent.my_method = my_method child.run() # prints: something else </code></pre> <p>You could also monkeypatch every method of <code>Parent</code> with a method from <code>MockParent</code>, in the same way. That would be almost the same as if you changed the parent class of everything inherited from <code>Parent</code>.</p> <p><strong>EDIT:</strong></p> <p>In fact, you could probably also do exactly what you asked for if you searched for all existing subclasses of <code>Parent</code>, patched them, and monkeypatched the definition if <code>Parent</code> in its module so that future classes are updated as well:</p> <pre><code>for child_class in Parent.__subclasses__(): mock.patch.object(child_klass, '__bases__', (MockParent,)) parents_module.Parent = MockParent </code></pre> <p>I think this would still miss some special situations, so monkeypatching each method is probably better.</p>
1
2016-09-03T22:18:09Z
[ "python", "mocking", "py.test" ]
Numpy np.where multiple condition
39,307,268
<p>I need to work with multiple condition using numpy.</p> <p>I'm trying this code that seem to work. </p> <p>My question is: There is another alternative that can do the same job? </p> <pre><code>Mur=np.array([200,246,372])*pq.kN*pq.m Mumax=np.array([1400,600,700])*pq.kN*pq.m Mu=np.array([100,500,2000])*pq.kN*pq.m Acreq=np.where(Mu&lt;Mur,0,"zero") Acreq=np.where(((Mur&lt;Mu)&amp;(Mu&lt;Mumax)),45,Acreq) Acreq=np.where(Mu&gt;Mumax,60,Acreq) Print(Acreq) ['0' '45' '60'] </code></pre>
1
2016-09-03T13:08:42Z
39,309,283
<p>you can use Pandas's <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.cut.html" rel="nofollow">pd.cut()</a> method:</p> <p>generate random series of integers:</p> <pre><code>In [162]: import pandas as pd In [163]: s = pd.Series(np.random.randint(-3,10, 10)) In [164]: s Out[164]: 0 6 1 -3 2 6 3 6 4 7 5 7 6 3 7 -2 8 9 9 1 dtype: int32 </code></pre> <p>categorize them:</p> <pre><code>In [165]: pd.cut(s, bins=[-np.inf, 2, 5, np.inf], labels=['0', '45', '60']) Out[165]: 0 60 1 0 2 60 3 60 4 60 5 60 6 45 7 0 8 60 9 0 dtype: category Categories (3, object): [0 &lt; 45 &lt; 60] </code></pre>
1
2016-09-03T16:55:35Z
[ "python", "numpy", "where" ]
Numpy np.where multiple condition
39,307,268
<p>I need to work with multiple condition using numpy.</p> <p>I'm trying this code that seem to work. </p> <p>My question is: There is another alternative that can do the same job? </p> <pre><code>Mur=np.array([200,246,372])*pq.kN*pq.m Mumax=np.array([1400,600,700])*pq.kN*pq.m Mu=np.array([100,500,2000])*pq.kN*pq.m Acreq=np.where(Mu&lt;Mur,0,"zero") Acreq=np.where(((Mur&lt;Mu)&amp;(Mu&lt;Mumax)),45,Acreq) Acreq=np.where(Mu&gt;Mumax,60,Acreq) Print(Acreq) ['0' '45' '60'] </code></pre>
1
2016-09-03T13:08:42Z
39,309,626
<p>Starting with this:</p> <pre><code>Mur = np.array([200,246,372])*3*5 Mumax = np.array([1400,600,700])*3*5 Mu = np.array([100,500,2000])*3*5 Acreq = np.where(Mu&lt;Mur,0,"zero") Acreq = np.where((Mur&lt;Mu)&amp;(Mu&lt;Mumax),45,Acreq) Acreq = np.where(Mu&gt;Mumax,60,Acreq) print(Acreq) ['0' '45' '60'] </code></pre> <p>Try this:</p> <pre><code>conditions = [Mu&lt;Mur, (Mur&lt;Mu)&amp;(Mu&lt;Mumax), Mu&gt;Mumax ] choices = [ 0, 45, 60 ] Acreq = np.select(conditions, choices, default='zero') print(Acreq) ['0' '45' '60'] </code></pre> <p>This also works: </p> <pre><code>np.where((Mur&lt;Mu)&amp;(Mu&lt;Mumax),45,np.where(Mu&gt;Mumax,60,np.where(Mu&lt;Mur,0,"zero"))) </code></pre>
1
2016-09-03T17:37:49Z
[ "python", "numpy", "where" ]
Use Python `set` keyword in Jinja
39,307,341
<p>I want to return unique items in Jinja template. Simplified:</p> <pre><code>{% set lst = [1, 2, 3, 3, 2] %} {% for t in set(lst) %} {{ t }} {% endfor %} </code></pre> <p>But this throws error:</p> <pre><code>UndefinedError: 'set' is undefined </code></pre> <p>And it seems hard to find answer on Google as <code>set</code> is also Jinja keyword. So can I use Python's <code>set</code> keyword in Jinja, or can I return unique items from list in Jinja?</p>
1
2016-09-03T13:17:44Z
39,307,477
<p>What set does is create a variable, so when you are using <code>set lst = 1</code>, you then access it with <code>lst</code>, not <code>set(lst)</code></p> <p>edit: misunderstood question, to access a python function from jinja, here's what I do in my flask app</p> <pre><code>@app.context_processor def inject_python(): return dict(set=set) </code></pre> <p>This way, jinja will have the function and you can use it as you did</p>
-3
2016-09-03T13:31:57Z
[ "python", "jinja2" ]
Django 1.10 default auth path to templates
39,307,382
<p>I'm trying to use the default django Auth system. It seems it can't find the template at registration/login.html even tho I have it created.</p> <p>I get this error when I try to login:</p> <pre><code>TemplateDoesNotExist at /accounts/login/ registration/login.html Request Method: GET Request URL: http://127.0.0.1:8000/accounts/login/ Django Version: 1.10 Exception Type: TemplateDoesNotExist Exception Value: registration/login.html </code></pre> <p>Here is how my project is organized</p> <p><a href="http://i.imgur.com/uymMTzd.png" rel="nofollow">http://i.imgur.com/uymMTzd.png</a></p> <p>This is my urls.py located in the same directory as my settings.py:</p> <pre><code>from django.contrib.auth import views as auth_views from django.conf.urls import url, include # include allows to import files from Apps from django.contrib import admin from .views import loggedin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^sharing/', include('sharing.urls')), #auth related URLS url(r'^accounts/login/$', auth_views.login, name='login'), </code></pre> <p>and finally, here is my settings file: """ Django settings for MyFamily project.</p> <pre><code>Generated by 'django-admin startproject' using Django 1.10. For more information on this file, see https://docs.djangoproject.com/en/1.10/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.10/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'ms62v8@=5p%*_$68th0zuw8!_xebp5s_m(7u-lq2wnvx+zyyrb' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'sharing.apps.SharingConfig', 'widget_tweaks', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'MyFamily.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'MyFamily.wsgi.application' # Database # https://docs.djangoproject.com/en/1.10/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'family', 'USER': 'root', 'PASSWORD': 'azerty', } } # Password validation # https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/1.10/topics/i18n/ LANGUAGE_CODE = 'fr_FR' TIME_ZONE = 'Europe/Paris' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.10/howto/static-files/ STATIC_URL = '/static/' </code></pre>
0
2016-09-03T13:21:49Z
39,307,608
<p>Add <code>templates</code> to <code>DIRS</code> array of <code>TEMPLATES</code> in your <code>settings.py</code></p> <pre><code>TEMPLATES = [{ 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['templates'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }] </code></pre>
0
2016-09-03T13:46:28Z
[ "python", "django", "authentication" ]
adding multiple directories as destination when copying files in python
39,307,400
<p>I want to copy an entire directory or just files from a directory to two or more directories at the same time. I'm struggling with the syntax to add more directories for the destination, so the copy is done at the same time (as I'll run a cron job). </p> <p>Everything works fine if I have one single directory, however I need to add two or more.</p> <p>The last line of code is:</p> <pre><code>shutil.copy(full_file_name, r'S:\\A') </code></pre> <p>I want to add more destination folders after S:\</p> <p>(this is for Win machines)</p> <p>Thanks for help!</p>
0
2016-09-03T13:23:55Z
39,307,929
<p>Why not just wrap in a loop:</p> <pre><code>destinations = [r'S:\\A', r'S:\\B', r'S:\\C'] for dest in destinations: shutil.copy(full_file_name, dest) </code></pre>
0
2016-09-03T14:19:04Z
[ "python" ]
adding multiple directories as destination when copying files in python
39,307,400
<p>I want to copy an entire directory or just files from a directory to two or more directories at the same time. I'm struggling with the syntax to add more directories for the destination, so the copy is done at the same time (as I'll run a cron job). </p> <p>Everything works fine if I have one single directory, however I need to add two or more.</p> <p>The last line of code is:</p> <pre><code>shutil.copy(full_file_name, r'S:\\A') </code></pre> <p>I want to add more destination folders after S:\</p> <p>(this is for Win machines)</p> <p>Thanks for help!</p>
0
2016-09-03T13:23:55Z
39,307,940
<p>In this example you define your file folder before, and an array of destination folders. Python then iterates through the destinations in a <code>for</code> loop. Note the use of <code>os.path.join</code>, which is a safe way of building file paths for cross-platform work.</p> <pre><code>import shutil import os full_file_path = os.path.join('home', 'orig') paths = [os.path.join('home', 'destA'), os.path.join('home', 'destB')] for path in paths: shutil.copy(full_file_path, path) </code></pre>
0
2016-09-03T14:20:22Z
[ "python" ]
adding multiple directories as destination when copying files in python
39,307,400
<p>I want to copy an entire directory or just files from a directory to two or more directories at the same time. I'm struggling with the syntax to add more directories for the destination, so the copy is done at the same time (as I'll run a cron job). </p> <p>Everything works fine if I have one single directory, however I need to add two or more.</p> <p>The last line of code is:</p> <pre><code>shutil.copy(full_file_name, r'S:\\A') </code></pre> <p>I want to add more destination folders after S:\</p> <p>(this is for Win machines)</p> <p>Thanks for help!</p>
0
2016-09-03T13:23:55Z
39,308,470
<p>If you want to copy the files at the same time, you should use <a href="https://docs.python.org/3/library/multiprocessing.html" rel="nofollow">multiprocessing</a>. In this sample, we have two files file1.txt and file2.txt and we will copy them to c:\temp\0 and c:\temp\1. </p> <pre><code>import multiprocessing import shutil def main(): orgs = ['c:\\temp\\file1.txt'] dests = ['c:\\temp\\0\\', 'c:\\temp\\1\\'] num_cores = multiprocessing.cpu_count() p = multiprocessing.Pool(num_cores) operations = [(x,y) for x in orgs for y in dests] p.starmap(shutil.copy, operations) p.close() p.join() if __name__ == "__main__": main() </code></pre>
0
2016-09-03T15:20:24Z
[ "python" ]
what would be the pandas equivalent of a complex SQL query (consisting of a subquery)
39,307,435
<p>Can anyone tell me the pandas equivalent of the following SQL query. Consider <code>sales_data</code> as tablename/pd.DataFrame</p> <pre><code>SELECT store_id, store_name, sales FROM sales_data WHERE sales = (SELECT max(sales) FROM sales_data WHERE store_location = 'Beijing') and store_location = 'Beijing' </code></pre> <p>I know, we can achieve this in 2 steps:</p> <pre><code>1) df = sales_data[sales_data['store_location'] == 'Beijing'][['store_id', 'store_name', 'sales']] 2) df[df['sales'] == df['sales'].max()] </code></pre> <p>But can we achieve it in a single step?? Is there a way.</p>
1
2016-09-03T13:27:32Z
39,308,276
<p>I wouldn't try to do it in one step in this case, because it might be slower:</p> <p>Demo:</p> <p><strong>Data:</strong></p> <pre><code>In [103]: df Out[103]: a b c x 0 2 1 1 b 1 2 3 2 a 2 4 1 3 c 3 3 2 3 b 4 2 1 4 c 5 1 3 1 c 6 2 3 0 a 7 2 3 2 b 8 4 2 4 a 9 4 1 1 b </code></pre> <p><strong>One-step solution:</strong></p> <pre><code>In [104]: df.ix[(df.x == 'a') &amp; (df.b == df.ix[df.x == 'a', 'b'].max())] Out[104]: a b c x 1 2 3 2 a 6 2 3 0 a </code></pre> <p><strong>Timing comparison against 1M rows DF:</strong></p> <pre><code>In [105]: big = pd.concat([df] * 10**5, ignore_index=True) In [106]: big.shape Out[106]: (1000000, 4) In [111]: %%timeit .....: x = big.ix[big.x == 'a'] .....: x.ix[x.b == x.b.max()] .....: 10 loops, best of 3: 189 ms per loop In [112]: %timeit big.ix[(big.x == 'a') &amp; (big.b == big.ix[big.x == 'a', 'b'].max())] 1 loop, best of 3: 321 ms per loop </code></pre> <p><strong>Conclusion:</strong> your 2-step method is almost 2 times faster</p> <p><strong>OLD <em>incorrect</em> answer:</strong></p> <pre><code>In [115]: df.ix[df.x == 'a'].nlargest(1, columns=['b']) Out[115]: a b c x 1 2 3 2 a </code></pre> <p>NOTE: this answer is incorrect because it will always return only one row, even if there will be multiple rows satisfying this condition: <code>column = max(column)</code></p> <p>Explanation:</p> <pre><code>In [114]: df.ix[df.x == 'a'] Out[114]: a b c x 1 2 3 2 a 6 2 3 0 a 8 4 2 4 a </code></pre> <p>correct answer:</p> <pre><code>In [116]: df.ix[(df.x == 'a') &amp; (df.b == df.ix[df.x == 'a', 'b'].max())] Out[116]: a b c x 1 2 3 2 a 6 2 3 0 a </code></pre>
1
2016-09-03T14:59:44Z
[ "python", "pandas", "subquery" ]
how to get the next page link in scrapy
39,307,468
<p>how to get the link "/zufang/dongcheng/pg2/" in "下一页"?</p> <pre><code>&lt;a href="/zufang/dongcheng/pg2/" data-page="2"&gt;下一页&lt;/a&gt; </code></pre> <p>I have tried this, but got nothing.</p> <p>the url is "<a href="http://bj.lianjia.com/zufang/dongcheng/" rel="nofollow">http://bj.lianjia.com/zufang/dongcheng/</a>"</p> <pre><code>start_urls = ( 'http://bj.lianjia.com/zufang/dongcheng/', ) rules = (Rule(LinkExtractor(allow=(), restrict_xpaths=('/html/body/div[4]/div[2]/div/div[2]/div[2]/a[5]',)), callback="parse", follow= True),) def parse(self, response): l = ItemLoader(item = ItjuziItem(),response=response) for i in range(0,len(response.xpath("//div[@class='info-panel']/h2/a/text()").extract())): info = response.xpath("//div[@class='info-panel']/h2/a/text()").extract()[i].encode('utf-8') local = response.xpath("//div[@class='info-panel']").xpath(".//span[@class='region']/text()").extract()[i].encode('utf-8') house_layout = response.xpath("//div[@class='info-panel']").xpath(".//span[@class='zone']//text()").extract()[i].encode('utf-8') house_square = response.xpath("//div[@class='info-panel']").xpath(".//span[@class='meters']/text()").extract()[i].encode('utf-8') house_orientation = response.xpath("//div[@class='info-panel']").xpath(".//div[@class='where']//span/text()").extract()[(i + 1) * 4 - 1].encode('utf-8') district = response.xpath("//div[@class='info-panel']").xpath(".//div[@class='con']/a/text()").extract()[i].encode('utf-8')[:-6] floor = response.xpath("//div[@class='info-panel']").xpath(".//div[@class='con']//text()").extract()[(i + 1) * 5 - 3].encode('utf-8') building_year = response.xpath("//div[@class='info-panel']").xpath(".//div[@class='con']//text()").extract()[(i + 1) * 5 - 1].encode('utf-8') price_month = response.xpath("//div[@class='info-panel']").xpath(".//span[@class='num']//text()").extract()[(i + 1) * 2 - 2].encode('utf-8') person_views = response.xpath("//div[@class='info-panel']").xpath(".//span[@class='num']//text()").extract()[(i + 1) * 2 - 1].encode('utf-8') tags = [] for j in range(0,len(response.xpath("//div[@class='view-label left']")[i].xpath(".//span//text()").extract())): tags.append(response.xpath("//div[@class='view-label left']")[i].xpath(".//span//text()").extract()[j].encode("utf-8")) l.add_value('info',info) l.add_value('local',local) l.add_value('house_layout',house_layout) l.add_value('house_square',house_square) l.add_value('house_orientation',house_orientation) l.add_value('district',district) l.add_value('floor',floor) l.add_value('building_year',building_year) l.add_value('price_month',price_month) l.add_value('person_views',person_views) l.add_value('tags',tags) print l return l.load_item() </code></pre>
-1
2016-09-03T13:30:15Z
39,307,836
<p>Why not just keep appending the incremented value of the page no in the url. Applicable to this link.</p> <pre><code>url = 'http://bj.lianjia.com/zufang/dongcheng/' counter = 1 while &lt;http error is null&gt;: url_to_crawl = url + "/pg" + counter counter = counter + 1 &lt;crawl the url&gt; </code></pre>
-1
2016-09-03T14:09:57Z
[ "python", "regex", "scrapy", "web-crawler" ]
how to get the next page link in scrapy
39,307,468
<p>how to get the link "/zufang/dongcheng/pg2/" in "下一页"?</p> <pre><code>&lt;a href="/zufang/dongcheng/pg2/" data-page="2"&gt;下一页&lt;/a&gt; </code></pre> <p>I have tried this, but got nothing.</p> <p>the url is "<a href="http://bj.lianjia.com/zufang/dongcheng/" rel="nofollow">http://bj.lianjia.com/zufang/dongcheng/</a>"</p> <pre><code>start_urls = ( 'http://bj.lianjia.com/zufang/dongcheng/', ) rules = (Rule(LinkExtractor(allow=(), restrict_xpaths=('/html/body/div[4]/div[2]/div/div[2]/div[2]/a[5]',)), callback="parse", follow= True),) def parse(self, response): l = ItemLoader(item = ItjuziItem(),response=response) for i in range(0,len(response.xpath("//div[@class='info-panel']/h2/a/text()").extract())): info = response.xpath("//div[@class='info-panel']/h2/a/text()").extract()[i].encode('utf-8') local = response.xpath("//div[@class='info-panel']").xpath(".//span[@class='region']/text()").extract()[i].encode('utf-8') house_layout = response.xpath("//div[@class='info-panel']").xpath(".//span[@class='zone']//text()").extract()[i].encode('utf-8') house_square = response.xpath("//div[@class='info-panel']").xpath(".//span[@class='meters']/text()").extract()[i].encode('utf-8') house_orientation = response.xpath("//div[@class='info-panel']").xpath(".//div[@class='where']//span/text()").extract()[(i + 1) * 4 - 1].encode('utf-8') district = response.xpath("//div[@class='info-panel']").xpath(".//div[@class='con']/a/text()").extract()[i].encode('utf-8')[:-6] floor = response.xpath("//div[@class='info-panel']").xpath(".//div[@class='con']//text()").extract()[(i + 1) * 5 - 3].encode('utf-8') building_year = response.xpath("//div[@class='info-panel']").xpath(".//div[@class='con']//text()").extract()[(i + 1) * 5 - 1].encode('utf-8') price_month = response.xpath("//div[@class='info-panel']").xpath(".//span[@class='num']//text()").extract()[(i + 1) * 2 - 2].encode('utf-8') person_views = response.xpath("//div[@class='info-panel']").xpath(".//span[@class='num']//text()").extract()[(i + 1) * 2 - 1].encode('utf-8') tags = [] for j in range(0,len(response.xpath("//div[@class='view-label left']")[i].xpath(".//span//text()").extract())): tags.append(response.xpath("//div[@class='view-label left']")[i].xpath(".//span//text()").extract()[j].encode("utf-8")) l.add_value('info',info) l.add_value('local',local) l.add_value('house_layout',house_layout) l.add_value('house_square',house_square) l.add_value('house_orientation',house_orientation) l.add_value('district',district) l.add_value('floor',floor) l.add_value('building_year',building_year) l.add_value('price_month',price_month) l.add_value('person_views',person_views) l.add_value('tags',tags) print l return l.load_item() </code></pre>
-1
2016-09-03T13:30:15Z
39,309,631
<p>Extract the link and attach it to the current url</p> <pre><code>from urlparse import urljoin yield scrapy.Request(urljoin(response.url,response.xpath("//a[@data-page]/@href").extract_first()), callback=self.parse) </code></pre> <p>or increment the page</p> <pre><code>for i in range(2,20): yield scrapy.Request("http://bj.lianjia.com/zufang/dongcheng/pg"+ str(i), callback=self.parse) </code></pre>
0
2016-09-03T17:38:18Z
[ "python", "regex", "scrapy", "web-crawler" ]
Access HTTP PUT data in python hug
39,307,491
<pre><code>import hug something = {'foo': 'bar'} @hug.put('/') def update_something(): something['foo'] = &lt;value_of_bar_from_http_put_request&gt; </code></pre> <p>How do I access the put data so that I can update <code>something</code>? I looked up <a href="https://github.com/timothycrosley/hug" rel="nofollow">this</a> and <a href="http://www.hug.rest/website/learn" rel="nofollow">this</a> but couldn't find anything.</p>
0
2016-09-03T13:33:11Z
39,476,129
<pre><code>import hug something = {'foo': 'bar'} @hug.put() def update_something(bar: hug.types.text): something['foo'] = bar return something # may be </code></pre> <p>And then you may use requests to test</p> <pre><code>import requests print(requests.put('http://localhost:8000/update_something', data={'bar': 'foobar'}).json()) </code></pre>
1
2016-09-13T17:48:17Z
[ "python", "api", "python-3.x", "hug" ]
How to install and build NS-3 using bake
39,307,561
<p>I am trying to download, build and test NS-3 using bake by typing the following commands on Cygwin on windows 7: </p> <pre><code>$ cd $ mkdir workspace $ cd workspace $ hg clone http://code.nsnam.org/bake </code></pre> <p>Then I changed the directory to bake directory and typed:</p> <pre><code>$ export BAKE_HOME=`pwd` $ export PATH=$PATH:$BAKE_HOME:$BAKE_HOME/build/bin $ export PYTHONPATH=$PYTHONPATH:$BAKE_HOME:$BAKE_HOME/build/lib </code></pre> <p>Then :</p> <pre><code>./bake.py configure -e ns-3.25 </code></pre> <p>I got nothing displayed on the screen and then typed:</p> <pre><code>./bake.py check </code></pre> <p>I got the following displayed on the screen:</p> <pre><code>&gt; Python - OK &gt; GNU C++ compiler - OK &gt; Mercurial - OK &gt; CVS - OK &gt; GIT - OK &gt; Bazaar - OK &gt; Tar tool - OK &gt; Unzip tool - OK &gt; Unrar tool - is missing &gt; 7z data compression utility - OK &gt; XZ data compression utility - OK &gt; Make - OK &gt; cMake - OK &gt; patch tool - OK &gt; autoreconf tool - OK &gt; Path searched for tools: /usr/local/bin /usr/bin /cygdrive/d/app/user/product/11.2.0/DB_HOME/bin /cygdrive/d/app/user/product/11.2.0/dbhome_1/bin /cygdrive/c/Windows/system32 /cygdrive/c/Windows /cygdrive/c/Windows/System32/Wbem /cygdrive/c/Windows/System32/WindowsPowerShell/v1.0 /cygdrive/c/Program Files (x86)/Microsoft SQL Server/100/Tools/Binn /cygdrive/c/Program Files (x86)/Microsoft SQL Server/100/DTS/Binn /cygdrive/c/Program Files (x86)/Skype/Phone /cygdrive/c/Users/user/AppData/Local/Programs/MiKTeX 2.9/miktex/bin/x64 /usr/lib/lapack /home/user-PC/ns-3-allinone-74b94ecd0120/ns-3-dev/bake/workspace/bake /home/user-PC/ns-3-allinone-74b94ecd0120/ns-3-dev/bake/workspace/bake/build/bin bin /home/user-PC/ns-3-allinone-74b94ecd0120/ns-3-dev/bake/workspace/bake /home/user-PC/ns-3-allinone-74b94ecd0120/ns-3-dev/bake/workspace/bake/build/lib </code></pre> <p>Then I typed on the command prompot: </p> <pre><code>$ ./bake.py download </code></pre> <p>I have to get the following in order to complete this process:</p> <pre><code>&gt;&gt; Downloading gccxml-ns3 (target directory:gccxml) - OK &gt;&gt; Searching for system dependency python-dev - OK &gt;&gt; Searching for system dependency pygraphviz - OK &gt;&gt; Searching for system dependency pygoocanvas - OK &gt;&gt; Searching for system dependency setuptools - OK &gt;&gt; Searching for system dependency g++ - OK &gt;&gt; Searching for system dependency qt4 - OK &gt;&gt; Downloading pygccxml - OK &gt;&gt; Downloading netanim-3.107 - OK &gt;&gt; Downloading pybindgen-0.17.0.post49+ng0e4e3bc (target directory:pybindgen) - OK &gt;&gt; Downloading ns-3.25 - OK </code></pre> <p>But I got the following problems and I do not have an idea how to get the needed dependencies:</p> <pre><code> $ ./bake.py download &gt;&gt; Searching for system dependency qt4 - OK &gt;&gt; Searching for system dependency g++ - OK &gt;&gt; Searching for system dependency setuptools - Problem &gt; Problem: Optional dependency, module "setuptools" not available This may reduce the functionality of the final build. However, bake will continue since "setuptools" is not an essential dependency. For more information call bake with -v or -vvv, for full verbose mode. &gt;&gt; Searching for system dependency pygoocanvas - Problem &gt; Problem: Optional dependency, module "pygoocanvas" not available This may reduce the functionality of the final build. However, bake will continue since "pygoocanvas" is not an essential dependency. For more information call bake with -v or -vvv, for full verbose mode. &gt;&gt; Searching for system dependency pygraphviz - Problem &gt; Problem: Optional dependency, module "pygraphviz" not available This may reduce the functionality of the final build. However, bake will continue since "pygraphviz" is not an essential dependency. For more information call bake with -v or -vvv, for full verbose mode. &gt;&gt; Searching for system dependency python-dev - OK &gt;&gt; Downloading gccxml-ns3 (target directory:gccxml) - Problem &gt; Problem: Optional dependency, module "gccxml-ns3" failed This may reduce the functionality of the final build. However, bake will continue since "gccxml-ns3" is not an essential dependency. For more information call bake with -v or -vvv, for full verbose mode. &gt;&gt; Downloading pygccxml - Problem &gt; Problem: Optional dependency, module "pygccxml" failed This may reduce the functionality of the final build. However, bake will continue since "pygccxml" is not an essential dependency. For more information call bake with -v or -vvv, for full verbose mode. &gt;&gt; Downloading netanim-3.107 - Problem &gt; Problem: Optional dependency, module "netanim-3.107" failed This may reduce the functionality of the final build. However, bake will continue since "netanim-3.107" is not an essential dependency. For more information call bake with -v or -vvv, for full verbose mode. &gt;&gt; Downloading pybindgen-0.17.0.post49+ng0e4e3bc (target directory:pybindgen) - Problem &gt; Problem: Optional dependency, module "pybindgen-0.17.0.post49+ng0e4e3bc" failed This may reduce the functionality of the final build. However, bake will continue since "pybindgen-0.17.0.post49+ng0e4e3bc" is not an essential dependency. For more information call bake with -v or -vvv, for full verbose mode. &gt;&gt; Downloading ns-3.25 - Problem &gt; Error: Critical dependency, module "ns-3.25" failed For more information call Bake with --debug and/or -v, -vvv, for full verbose mode (bake --help) </code></pre>
0
2016-09-03T13:40:38Z
40,112,059
<p>It seems you are missing "Unrar tool". I don't have cygwin to test here, but you migth try:</p> <pre><code>wget http://www.rarlab.com/rar/unrarsrc-5.1.7.tar.gz tar -xzvf unrarsrc-5.1.7.tar.gz cd unrar make </code></pre> <p>and then run bake download again.</p> <p>Source: <a href="https://wjianz.wordpress.com/2014/09/28/howto-extract-rar-files-on-cygwin/" rel="nofollow">https://wjianz.wordpress.com/2014/09/28/howto-extract-rar-files-on-cygwin/</a></p>
0
2016-10-18T15:18:42Z
[ "python", "c++", "g++", "cygwin", "cygpath" ]
os.path.join - how to cope with absolute path
39,307,631
<p><strong>Python 3.5.2</strong></p> <pre><code>BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATIC_URL = '/static/' </code></pre> <p>I want to join them:</p> <pre><code>STATIC_ROOT = os.path.join(PROJECT_PATH, STATIC_URL) </code></pre> <p>The result is '/static/'. </p> <p>This is the documentation: <a href="https://docs.python.org/3/library/os.path.html" rel="nofollow">https://docs.python.org/3/library/os.path.html</a></p> <p>We can read that "If a component is an absolute path, all previous components are thrown away and joining continues from the absolute path component."</p> <p>In my case BASE_DIR in the debugger is '/home/michael/PycharmProjects/photoarchive/photoarchive'.</p> <p>Well, this is an absolute path. Well, it eve was acquired via abspath function.</p> <p>So, there first component - BASE_DIR - is an absolute path. </p> <p><strong>Could you tell me why it is thrown away? And how to get '/home/michael/PycharmProjects/photoarchive/photoarchive/static'?</strong></p>
0
2016-09-03T13:48:48Z
39,307,659
<p>"If a component is an absolute path, all previous components are thrown away and joining continues from the absolute path component." applies here: <code>STATIC_URL</code> is an absolute path because it starts with <code>/</code>, so <code>BASE_DIR</code> is dropped.</p> <p>Drop the leading <code>/</code> else dirname thinks that <code>STATIC_URL</code> is absolute and keeps only that.</p> <pre><code>BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATIC_URL = 'static/' </code></pre>
3
2016-09-03T13:50:57Z
[ "python" ]
Google CodeJam Past Exercise - Decrease runtime
39,307,690
<p>I have been working on a past Google Codejam algorithm from 2010, but the time complexity is awful.</p> <p>Here is the question from Google Codejam: <a href="https://code.google.com/codejam/contest/619102/dashboard" rel="nofollow">https://code.google.com/codejam/contest/619102/dashboard</a></p> <p>TLDR - Imagine two towers that have a number line running up the sides, we draw a line from one buildings number line (say from 10) to another point on the other buildings number line (say from 1). If we do this n times, how many times will those lines intersect?</p> <p>I was wondering if anyone here is able to suggest a way in which I can speed up my algorithm? After 4 hours I really can't see one and I'm losing my miinnnnddd. </p> <p>Here is my code as of right now.</p> <p>An example input would be:</p> <p>2 - (Number of cases)</p> <p>3 - (Number of wires in case # 1)</p> <p>1 10</p> <p>5 5</p> <p>7 7</p> <p>Case #1: 2 - (2 intersections among lines 1,10 5,5 7,7)</p> <p>2 - (Number of wires in case #2)</p> <p>5 5</p> <p>2 2</p> <p>Case #2: 0 - (No lines intersect)</p> <pre><code>def solve(wire_ints, test_case): answer_integer = 0 for iterI in range(number_wires): for iterJ in range(iterI): holder = [wire_ints[iterI], wire_ints[iterJ]] holder.sort() if holder[0][1] &gt; holder[1][1]: answer_integer = answer_integer + 1 return("Case #" + str(test_case) + ":" + " " + str(answer_integer)) for test_case in range(1, int(input()) + 1): number_wires = int(input()) wire_ints = [] for count1 in range(number_wires): left_port,right_port = map(int, input().split()) wire_ints.append((left_port,right_port)) answer_string = solve(wire_ints, test_case) print(answer_string) </code></pre> <p>This algorithm does WORK for any input I give it, but as I said its very ugly and slow. </p> <p>Help would be appreciated!</p>
-4
2016-09-03T13:54:21Z
39,307,916
<p>Since <code>N</code> is 1000 an algorithm with <code>O(N^2)</code> would be acceptable. So what you have to do is sort the wires by one of their end points.</p> <pre><code>//sorted by first number 1 10 5 5 7 7 </code></pre> <p>Then you process each line from the beginning and check whether it has intersection with lines before it. If the second end point of a line before it is bigger than the second point of current line they have intersection. This requires two loops thus the <code>O(N^2)</code> complexity which suffice for <code>N=1000</code>. <br> Also you can interpret this as an inversion count. you have to count the number of inversions of the second end points where the list is sorted by first end point.</p> <pre><code>10 5 7 -&gt;‌ number of inversions is 2, because of (10,5) and (10,7) </code></pre> <p>Also there is <a href="http://stackoverflow.com/questions/337664/counting-inversions-in-an-array"><code>O(NlogN)</code> approach</a> to count the number of inversions which you don't need for this question.</p>
0
2016-09-03T14:17:58Z
[ "python", "algorithm" ]
Increase the significant digits in Numpy
39,307,766
<p>I want to know how can I increase the number of significant digits beyond the decimal. The original "rf" numpy array contains floating point numbers.</p> <pre><code>import numpy as np rf=daily_rets(df) [ 7.11441183 7.12383509 7.13325787 7.16152716 7.17094994 7.17094994 7.18979692 7.18979692 7.19921923 7.19921923 7.19921923 7.19921923 7.19921923 7.19921923 7.19921923 7.20864296 7.20864296 7.20864296 7.20864296 7.20864296] </code></pre> <p>But when I perform the operation I get an undesired output</p> <pre><code>rf[0:]=(1+rf[0:]/100)**(1/252) </code></pre> <p>I get the following output [ 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]</p> <p>np.around() also does not help giving me the same output as above</p> <pre><code>rf[0:]=np.around((1+rf[0:]/100)**(1/252), decimals=6) </code></pre> <p>I realize the above operation would make the numbers very small, still I want the numbers beyond decimals to appear</p>
0
2016-09-03T14:02:49Z
39,308,347
<p>In python 2.7 dividing a numpy float by an integer will return an integer, at least that is my experience. As the answers say:</p> <pre><code>In [1]: import numpy as np In [2]: rf = np.array([ 7.11441183, 7.12383509, 7.13325787, 7.16152716, 7.17 ...: 094994, 7.17094994, 7.18979692, 7.18979692, 7.19921923, 7.19921923, ...: 7.19921923, 7.19921923, 7.19921923, 7.19921923, 7.19921923, 7.208 ...: 64296, 7.20864296, 7.20864296, 7.20864296, 7.20864296]) In [3]: print (1+rf[0:]/100)**(1/252) [ 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1.] In [4]: print (1+rf[0:]/100.0)**(1/252.0) [ 1.00027276 1.00027311 1.00027346 1.00027451 1.00027486 1.00027486 1.00027556 1.00027556 1.00027591 1.00027591 1.00027591 1.00027591 1.00027591 1.00027591 1.00027591 1.00027626 1.00027626 1.00027626 1.00027626 1.00027626] </code></pre> <p>Dividing by a float solves this problem, i.e change both 100 and 252 to 100.0 and 252.0. Hope that helps.</p>
0
2016-09-03T15:06:49Z
[ "python", "numpy", "significant-digits" ]
Increase the significant digits in Numpy
39,307,766
<p>I want to know how can I increase the number of significant digits beyond the decimal. The original "rf" numpy array contains floating point numbers.</p> <pre><code>import numpy as np rf=daily_rets(df) [ 7.11441183 7.12383509 7.13325787 7.16152716 7.17094994 7.17094994 7.18979692 7.18979692 7.19921923 7.19921923 7.19921923 7.19921923 7.19921923 7.19921923 7.19921923 7.20864296 7.20864296 7.20864296 7.20864296 7.20864296] </code></pre> <p>But when I perform the operation I get an undesired output</p> <pre><code>rf[0:]=(1+rf[0:]/100)**(1/252) </code></pre> <p>I get the following output [ 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]</p> <p>np.around() also does not help giving me the same output as above</p> <pre><code>rf[0:]=np.around((1+rf[0:]/100)**(1/252), decimals=6) </code></pre> <p>I realize the above operation would make the numbers very small, still I want the numbers beyond decimals to appear</p>
0
2016-09-03T14:02:49Z
39,308,455
<p>You could just use <a href="http://docs.scipy.org/doc/numpy/reference/ufuncs.html#available-ufuncs" rel="nofollow">numpy ufuncs</a>:</p> <pre><code>from __future__ import division import numpy as np rf = np.array([7.11441183, 7.12383509, 7.13325787, 7.16152716]) np.divide(rf[0:], 100, rf[0:]) np.add(rf[0:], 1, rf[0:]) np.power(rf[0:], 1 / 252, rf[0:]) &gt;&gt;&gt; rf array([ 1.00027276, 1.00027311, 1.00027346, 1.00027451]) &gt;&gt;&gt; </code></pre> <p>Initially I thought numpy would handle the issue but as others have stated, it is the v2.7 integer division that is causing the problem. Hopefully the ufuncs above are not too much of a distractor.</p>
0
2016-09-03T15:19:30Z
[ "python", "numpy", "significant-digits" ]
Matching ctrl-M character in Python
39,307,806
<p>I am working on an interactive program where I take some actions based on the input. For the application I want to match <code>^M</code> characters in the input stream.</p> <p>To do this I found the ASCII equivalent of <code>^M</code> which is <code>0xd</code> and converted the input character to ascii using <code>hex(ord(char))</code> and compared the two.</p> <pre><code>if hex(ord(char)) == 0xd: take_action() </code></pre> <p>But this condition never evaluates to true. To see if I am using the correct ascii values I wrote the input I am sending to a file.</p> <pre><code> 0xd 0xd 0xd 0x65 0x78 0x69 0x74 0xd 0x65 0x78 0x69 0x74 0xd </code></pre> <p>Could anyone tell me how to compare <code>^M</code> character and why the above does not work ?</p>
0
2016-09-03T14:07:09Z
39,307,824
<p><code>0xd</code> is an <em>integer literal</em> (it produces the value 13), but <code>hex()</code> returns a string. <code>'0xd'</code> may <em>look</em> like <code>0xd</code>, but are not equal:</p> <pre><code>&gt;&gt;&gt; hex(13) '0xd' &gt;&gt;&gt; 0xd 13 &gt;&gt;&gt; hex(13) == 0xd False </code></pre> <p>Remove the <code>hex()</code> call:</p> <pre><code>if ord(char) == 0xd: </code></pre> <p>or just use a string literal:</p> <pre><code>if char == '\x0d': </code></pre> <p>or the equivalent:</p> <pre><code>if char == '\r': </code></pre> <p><code>'\r'</code> and <code>'\x0d'</code> produce the exact same character.</p>
3
2016-09-03T14:08:36Z
[ "python" ]
SqlAlchemy Join Query
39,307,825
<p>I have tables like this:</p> <p>Box</p> <p>|- issues[]</p> <p>Issue</p> <p>|- status_id</p> <p>|- status (related through status_id)</p> <p>Status</p> <p>|- id</p> <p>I want to get all the boxes where the “issues” field for each box will only contain issues that don’t have a status_id = 5. The following isn’t working</p> <p>db.session.query(Box).join(Issue).filter(Issue.status_id != 5).all()</p> <p>What is wrong with the above code?</p>
1
2016-09-03T14:08:39Z
39,308,097
<p>If I've understood your situation correctly, I think the following is what you're looking for:</p> <pre><code>db.session.query(Box).outerjoin(Box.issues).filter(or_(Issue.status_id.is_(None), Issue.status_id != 5)).options(contains_eager(Box.issues)).all() </code></pre>
1
2016-09-03T14:37:40Z
[ "python", "sqlalchemy", "flask-sqlalchemy" ]
Do we need to install library/package for cgi to run Python scripts (on WAMP)? Or is it available automatically (in WAMP server)?
39,307,889
<p>I'm running Python 3.5 and I have tried installing cgi using pip and it gave me the following message:</p> <pre><code>Could not find a version that satisfies the requirement cgi (from versions:) No matching distribution found for cgi </code></pre> <p>I want to run Python scripts (locally, using WAMP server) on my browser and through some research I learned that we need to use cgi for the same. I would like to know if it is necessary to install cgi package, or is it directly available (either when Python is installed or WAMP server is installed) so that we should just configure the httpd file in the (corresponding folder in) WAMP server by adding the following code:</p> <pre><code>AddHandler cgi-script .cgi .py Options Indexes FollowSymLinks ExecCGI </code></pre> <p>Also, can we just put the Python script files in cgi-bin folder (if available) so as to execute them?</p>
0
2016-09-03T14:14:45Z
39,308,098
<p>For CGI you dont actually need any libraries (although <a href="https://docs.python.org/3/library/cgi.html" rel="nofollow">cgi</a> from standard library is helpful) but I would strongly recommend to use WSGI as not only debugging is much easier with it. There is a <a href="https://docs.python.org/3/library/wsgiref.html#wsgiref.handlers.CGIHandler" rel="nofollow">WSGI as CGI adapter</a> in the standard library but you can also use <a href="https://code.google.com/archive/p/modwsgi/" rel="nofollow">mod_wsgi</a> for better performance.</p> <p>There are microframeworks like <a href="http://bottlepy.org/docs/dev/index.html" rel="nofollow">bottle</a> which make building sites much easier and they work with WSGI (and therefore CGI). </p>
0
2016-09-03T14:37:56Z
[ "python", "apache", "python-3.x", "cgi", "wamp" ]
How do I remove similar tuples in python as in (x,y) and (y,x)
39,307,906
<p>I have a list of tuples [(1,2),(2,1),(4,4)] I want to remove either of these tuples where (a,b) = (b,a). ie.. (1,2) or (2,1)</p>
-4
2016-09-03T14:17:05Z
39,308,018
<p>Assuming the order of the elements in tuple doesn't matter, one way is to do:</p> <pre><code>In [11]: l = [(1,2), (2,1), (4,4)] In [12]: list(set([(x[0], x[1]) if x [0] &lt; x[1] else (x[1], x[0]) for x in l])) Out[12]: [(1, 2), (4, 4)] </code></pre> <p>Edit (A simpler version):</p> <pre><code>In [15]: list(set(tuple(sorted(x)) for x in l)) Out[15]: [(1, 2), (4, 4)] </code></pre>
1
2016-09-03T14:29:38Z
[ "python" ]
Object is not callable the second time I call a class method
39,307,910
<p>I have a class Match:</p> <pre><code>class Match(object): def __init__(self,id): self.id = id def result(self): # somehow find the game result self.result = result return self.result </code></pre> <p>If I initialize a match object as</p> <pre><code>m = Match(1) </code></pre> <p>when I call the method result I get</p> <pre><code>m.result Out[18]: &lt;bound method Match.result of &lt;football_uk.Match object at 0x000000000B0081D0&gt;&gt; </code></pre> <p>When I call it with the parenthesis, I get</p> <pre><code>m.result() Out[19]: u'2-3' </code></pre> <p>That is the correct answer. However, when I try to call a second, third, fourth, etc. time the method, I get</p> <pre><code>m.result() Traceback (most recent call last): File "&lt;ipython-input-20-42f6486e36a5&gt;", line 1, in &lt;module&gt; m.result() TypeError: 'unicode' object is not callable </code></pre> <p>If instead now I call the method without the parenthesis, it works:</p> <pre><code>m.result Out[21]: u'2-3' </code></pre> <p>The same with other similar methods.</p>
2
2016-09-03T14:17:24Z
39,307,921
<p>You have given your instance an attribute named <code>result</code>:</p> <pre><code>self.result = result </code></pre> <p>This now masks the method. You can't use the same name as the method if you don't want it masked. Rename the attribute or the method.</p> <p>You could use the name <code>_result</code> for example:</p> <pre><code>def result(self): # somehow find the game result self._result = result return self._result </code></pre> <p><code>self</code> is just another reference to the same object that <code>m</code> references. Attributes set or found on <code>self</code> are the same ones that you can find on <code>m</code>, because they are the same object. There is no difference between <code>m.result</code> and <code>self.result</code> here.</p>
6
2016-09-03T14:18:26Z
[ "python" ]
Stratified Labeled K-Fold Cross-Validation In Scikit-Learn
39,307,945
<p>I'm trying to classify instances of a dataset as being in one of two classes, a or b. B is a minority class and only makes up 8% of the dataset. All instances are assigned an id indicating which subject generated the data. Because every subject generated multiple instances id's are repeated frequently in the dataset. </p> <p>The table below is just an example, the real table has about 100,000 instances. Each subject id has about 100 instances in the table. Every subject is tied to exactly one class as you can see with "larry" below. </p> <pre><code> * field * field * id * class ******************************************* 0 * _ * _ * bob * a 1 * _ * _ * susan * a 2 * _ * _ * susan * a 3 * _ * _ * bob * a 4 * _ * _ * larry * b 5 * _ * _ * greg * a 6 * _ * _ * larry * b 7 * _ * _ * bob * a 8 * _ * _ * susan * a 9 * _ * _ * susan * a 10 * _ * _ * bob * a 11 * _ * _ * greg * a ... ... ... ... ... </code></pre> <p>I would like to use cross-validation to tune the model and must stratify the dataset so that each fold contains a few examples of the minority class, b. The problem is that I have a second constraint, the same id must never appear in two different folds as this would leak information about the subject. </p> <p>I'm using python's scikit-learn library. I need a method which combines both LabelKFold, which makes sure labels (id's) are not split among folds, and StratifiedKFold, which makes sure every fold has a similar ratio of classes. How can I accomplish the above using scikit-learn? If it is not possible to split on two constraints in sklearn how can I effectively split the dataset by hand or with other python libraries?</p>
3
2016-09-03T14:20:38Z
39,308,376
<p>The following is a bit tricky with respect to indexing (it would help if you use something like Pandas for it), but conceptually simple.</p> <p>Suppose you make a dummy dataset where the independent variables are only <code>id</code> and <code>class</code>. Furthermore, in this dataset, remove duplicate <code>id</code> entries.</p> <p>For your cross validation, run stratified cross validation on the dummy dataset. At each iteration: </p> <ol> <li><p>Find out which <code>id</code>s were selected for the train and the test</p></li> <li><p>Go back to the original dataset, and insert all the instances belonging to <code>id</code> as necessary into train and test sets.</p></li> </ol> <p>This works because:</p> <ol> <li><p>As you stated, each <code>id</code> is associated with a single label.</p></li> <li><p>Since we run stratified CV, each class is represented proportionally.</p></li> <li><p>Since each <code>id</code> appears only in the train or test set (but not both), it is labeled too.</p></li> </ol>
2
2016-09-03T15:09:03Z
[ "python", "pandas", "machine-learning", "scikit-learn", "cross-validation" ]
Beautiful Soup - Python
39,308,028
<p>I was hoping to ask a pretty simple question. I have come across the below code and have not been able to find a decent explanation as to:</p> <ol> <li>What exactly does the <code>.attrs</code> function do in this case?</li> <li>What is the function of the <code>['href']</code> part at the end i.e. what exactly does that part of the code execute?</li> </ol> <p>Here is the code:</p> <pre><code>from urllib.request import urlopen from bs4 import BeautifulSoup html = urlopen("url") bsObj = BeautifulSoup(html) for link in bsObj.findAll("a"): if 'href' in link.attrs: print (link.attrs['href']) </code></pre>
-2
2016-09-03T14:30:28Z
39,308,104
<p>Let's go line by line after imports</p> <ul> <li>Load a url into variable called html</li> <li>Create BeautifulSoup object from html</li> <li>For every link in the object's "a" tags (it loops over html tags in the html, finds all <code>&lt;a&gt;</code> and loops over them)</li> <li>If the attribute of the tag has 'href' (<code>&lt;a href=""&gt;</code> - href is an attribute, thatt's stored in the link's .attrs property)</li> <li>print to stdout the attribute that has key 'href' (it's a dictionary with <code>'href':'http://something'</code>)</li> </ul> <p>The indentation is a bit wrong there, print should have be more indented than if</p>
1
2016-09-03T14:38:25Z
[ "python" ]
Beautiful Soup - Python
39,308,028
<p>I was hoping to ask a pretty simple question. I have come across the below code and have not been able to find a decent explanation as to:</p> <ol> <li>What exactly does the <code>.attrs</code> function do in this case?</li> <li>What is the function of the <code>['href']</code> part at the end i.e. what exactly does that part of the code execute?</li> </ol> <p>Here is the code:</p> <pre><code>from urllib.request import urlopen from bs4 import BeautifulSoup html = urlopen("url") bsObj = BeautifulSoup(html) for link in bsObj.findAll("a"): if 'href' in link.attrs: print (link.attrs['href']) </code></pre>
-2
2016-09-03T14:30:28Z
39,308,120
<p>Let's try to fetch this question it self and see:</p> <pre><code>from urllib.request import urlopen from bs4 import BeautifulSoup html = urlopen("http://stackoverflow.com/q/39308028/1005215") bsObj = BeautifulSoup(html) </code></pre> <blockquote> <p>i) what exactly does the .attrs function do in this code</p> </blockquote> <pre><code>In [6]: bsObj.findAll("a")[30] Out[6]: &lt;a class="question-hyperlink" href="/questions/39308028/beautifuelsoup-python"&gt;Beautifuelsoup - Python&lt;/a&gt; In [7]: bsObj.findAll("a")[30].attrs Out[7]: {'class': ['question-hyperlink'], 'href': '/questions/39308028/beautifuelsoup-python'} In [8]: type(bsObj.findAll("a")[30]) Out[8]: bs4.element.Tag </code></pre> <p>If you read the <a href="http://beautiful-soup-4.readthedocs.io/en/latest/index.html?highlight=attrs#attributes" rel="nofollow">documentation</a>, you will notice that a tag may have any number of attributes. In the element number 30, the tag has attributes 'class' and 'href'</p> <blockquote> <p>ii) what is the function of the ['href'] part at the end</p> </blockquote> <pre><code>In [9]: bsObj.findAll("a")[30]['href'] Out[9]: '/questions/39308028/beautifuelsoup-python' </code></pre> <p>If you look at the above output, you will see that the tag had an attribute 'href' and the above code fetched us the value for that attribute.</p>
1
2016-09-03T14:40:03Z
[ "python" ]
How do I increase the contrast of an image in Python OpenCV
39,308,030
<p>I am new to Python OpenCV. I have read some documents and answers <a href="http://stackoverflow.com/questions/19363293/whats-the-fastest-way-to-increase-color-image-contrast-with-opencv-in-python-c">here</a> but I am unable to figure out what the following code means:</p> <pre><code>if (self.array_alpha is None): self.array_alpha = np.array([1.25]) self.array_beta = np.array([-100.0]) # add a beta value to every pixel cv2.add(new_img, self.array_beta, new_img) # multiply every pixel value by alpha cv2.multiply(new_img, self.array_alpha, new_img) </code></pre> <p>I have come to know that <code>Basically, every pixel can be transformed as X = aY + b where a and b are scalars.</code>. Basically, I have understood this. However, I did not understand the code and how to increase contrast with this.</p> <p>Till now, I have managed to simply read the image using <code>img = cv2.imread('image.jpg',0)</code></p> <p>Thanks for your help</p>
0
2016-09-03T14:30:36Z
39,319,390
<p>Best explanation for <code>X = aY + b</code> (in fact it <code>f(x) = ax + b</code>)) is provided at <a href="http://math.stackexchange.com/a/906280/357701">http://math.stackexchange.com/a/906280/357701</a> </p> <p>A Simpler one by just adjusting lightness/luma/brightness for contrast as is below:</p> <pre><code>import cv2 img = cv2.imread('test.jpg') cv2.imshow('test', img) cv2.waitKey(1000) imghsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) imghsv[:,:,2] = [[max(pixel - 25, 0) if pixel &lt; 190 else min(pixel + 25, 255) for pixel in row] for row in imghsv[:,:,2]] cv2.imshow('contrast', cv2.cvtColor(imghsv, cv2.COLOR_HSV2BGR)) cv2.waitKey(1000) raw_input() </code></pre>
0
2016-09-04T17:01:16Z
[ "python", "opencv" ]
SQLITE3 database tables export in CSV
39,308,042
<p>I have a database including 10 tables: (date ,day ,month ,year ,pcp1 ,pcp2 ,pcp3 ,pcp4,pcp5 ,pcp6) and each column has 41 years dataset. day, month and year columns are "Null" as l will add them later after exporting tables in csv file and l did this part but format is not correct as each column must be respectively separate.</p> <p>here is my database example:</p> <pre><code>date day month year pcp1 pcp2 pcp3 pcp4 pcp5 pcp6 1.01.1979 0.431 2.167 9.375 9.375 0.431 9.375 2.01.1979 1.216 2.583 9.162 9.162 1.216 9.162 3.01.1979 4.041 9.373 23.169 23.169 4.041 23.169 4.01.1979 1.799 3.866 8.286 8.286 1.799 8.286 5.01.1979 0.003 0.051 0.342 0.342 0.003 0.342 6.01.1979 2.345 3.777 7.483 7.483 2.345 7.483 7.01.1979 0.017 0.031 0.173 0.173 0.017 0.173 </code></pre> <p>I would like to get all tables like above. However, I got the following output:</p> <pre><code>Column 1,Column 2,Ellipsis 1979-01-01,,,,0.431,2.167,9.375,9.375,0.431,9.375 1979-01-02,,,,1.216,2.583,9.162,9.162,1.216,9.162 1979-01-03,,,,4.041,9.373,23.169,23.169,4.041,23.169 1979-01-04,,,,1.799,3.866,8.286,8.286,1.799,8.286 1979-01-05,,,,0.003,0.051,0.342,0.342,0.003,0.342 </code></pre> <p>There are a few problems. Firstly the headers are absent, secondly jumping another row (1 to 3) instead of (1 to 2), and lastly all data come together under column1.</p> <p>my code is:</p> <pre><code>import csv import sqlite3 conn=sqlite3.connect("pcpnew6.db") c=conn.cursor() data = c.execute("SELECT * FROM pcp3") with open('output.csv', 'w') as f: writer = csv.writer(f) writer.writerow(['Column 1', 'Column 2', ...]) writer.writerows(data) </code></pre>
1
2016-09-03T14:32:10Z
39,308,066
<ol> <li>The query is not supposed to return the headers. Also I'm confident about both points below. This is untested, but the <code>description</code> attribute returns the last query table names, so it should work</li> <li>About the extra blank line every line: I suppose you're using windows. Opening the output as text file add an extra <code>\r</code> (carriage return char). It's handled differently between python 2 and python 3:</li> <li>It's actually OK, but you have the impression that it's not working because you're opening the csv with excel and excel requires a <code>;</code> by default for csvs => you have to specify semicolon delimiter or Excel opens it on one column.</li> </ol> <p>See my changes:</p> <p>In python 3 (it is not possible to open a text file as binary):</p> <pre><code> with open('output.csv', 'w', newline="") as f: writer = csv.writer(f,delimiter=';') </code></pre> <p>according to documentation writer.writerows(data)</p> <p>In python 2 (the newline option does not exist):</p> <pre><code> with open('output.csv', 'wb') as f: writer = csv.writer(f,delimiter=';') writer.writerows(data) </code></pre> <p>Edit: python 2/3 compatible snippet, with title line:</p> <pre><code>import sys if sys.version_info &lt; (3,): f = open('output.csv', 'wb') else: f = open('output.csv', 'w', newline="") writer = csv.writer(f,delimiter=';') first_item = next(data) # get first item to get keys writer.writerow(first_item.keys()) # keys=title you're looking for writer.writerow(first_item) # write the rest writer.writerows(data) f.close() </code></pre>
1
2016-09-03T14:34:31Z
[ "python", "sqlite", "csv" ]
SQLITE3 database tables export in CSV
39,308,042
<p>I have a database including 10 tables: (date ,day ,month ,year ,pcp1 ,pcp2 ,pcp3 ,pcp4,pcp5 ,pcp6) and each column has 41 years dataset. day, month and year columns are "Null" as l will add them later after exporting tables in csv file and l did this part but format is not correct as each column must be respectively separate.</p> <p>here is my database example:</p> <pre><code>date day month year pcp1 pcp2 pcp3 pcp4 pcp5 pcp6 1.01.1979 0.431 2.167 9.375 9.375 0.431 9.375 2.01.1979 1.216 2.583 9.162 9.162 1.216 9.162 3.01.1979 4.041 9.373 23.169 23.169 4.041 23.169 4.01.1979 1.799 3.866 8.286 8.286 1.799 8.286 5.01.1979 0.003 0.051 0.342 0.342 0.003 0.342 6.01.1979 2.345 3.777 7.483 7.483 2.345 7.483 7.01.1979 0.017 0.031 0.173 0.173 0.017 0.173 </code></pre> <p>I would like to get all tables like above. However, I got the following output:</p> <pre><code>Column 1,Column 2,Ellipsis 1979-01-01,,,,0.431,2.167,9.375,9.375,0.431,9.375 1979-01-02,,,,1.216,2.583,9.162,9.162,1.216,9.162 1979-01-03,,,,4.041,9.373,23.169,23.169,4.041,23.169 1979-01-04,,,,1.799,3.866,8.286,8.286,1.799,8.286 1979-01-05,,,,0.003,0.051,0.342,0.342,0.003,0.342 </code></pre> <p>There are a few problems. Firstly the headers are absent, secondly jumping another row (1 to 3) instead of (1 to 2), and lastly all data come together under column1.</p> <p>my code is:</p> <pre><code>import csv import sqlite3 conn=sqlite3.connect("pcpnew6.db") c=conn.cursor() data = c.execute("SELECT * FROM pcp3") with open('output.csv', 'w') as f: writer = csv.writer(f) writer.writerow(['Column 1', 'Column 2', ...]) writer.writerows(data) </code></pre>
1
2016-09-03T14:32:10Z
39,318,221
<p>Here is the answer of my question and it combined with the code posted by Jean-François Fabre ,thanks for his help.</p> <pre><code>import sys import sqlite3 import csv conn=sqlite3.connect("pcpnew6.db") c=conn.cursor() conn.row_factory=sqlite3.Row crsr=conn.execute("SELECT * From pcp3") row=crsr.fetchone() titles=row.keys() data = c.execute("SELECT * FROM pcp3") if sys.version_info &lt; (3,): f = open('output.csv', 'wb') else: f = open('output.csv', 'w', newline="") writer = csv.writer(f,delimiter=';') writer.writerow(titles) # keys=title you're looking for # write the rest writer.writerows(data) f.close() </code></pre> <p>here is output of code:</p> <pre><code>date day month year pcp1 pcp2 pcp3 pcp4 pcp5 pcp6 1.01.1979 0.431 2.167 9.375 9.375 2.167 0.431 2.01.1979 1.216 2.583 9.162 9.162 2.583 1.216 3.01.1979 4.041 9.373 23.169 23.169 9.373 4.041 4.01.1979 1.799 3.866 8.286 8.286 3.866 1.799 5.01.1979 0.003 0.051 0.342 0.342 0.051 0.003 6.01.1979 2.345 3.777 7.483 7.483 3.777 2.345 </code></pre>
1
2016-09-04T14:55:50Z
[ "python", "sqlite", "csv" ]
Regarding Keyerror while using Python json module
39,308,059
<p>would be helped if the mistake is pointed. Here Iam trying to create a code for displaying the name of the city state and country by taking Pincode as input, Thanks in advance</p> <pre><code> import urllib, json from urllib.request import urlopen from tkinter import * global pincode root=Tk() frame=Frame(root,width=250,height=250) frame.grid() class cal: def __init__(self): self.string=StringVar() entry=Entry(frame,textvariable=self.string) entry.grid(row=1,column=2,columnspan=6) but=Button(root,text="submit",command=self.pin) but.grid() def pin(self): pincode=self.string.get() url = "https://www.whizapi.com/api/v2/util/ui/in/indian-city-by-postal-code?pin="+pincode+"&amp;project-app-key=fnb1agfepp41y49jz6a39upx" response = urllib.request.urlopen(url) data = json.loads(response.read().decode('utf8')) fi=open("neme.txt","w") fi.write(str(data)) state=data['State'] city=data['City'] area=data['area'] name=Label(frame,text="State:"+state+"City:"+city+"area:"+area) name.grid(row=3,column=0) cal() mainloop() </code></pre> <p>error being </p> <pre><code>Traceback (most recent call last): File "/usr/lib/python3.4/tkinter/__init__.py", line 1541, in __call__ return self.func(*args) File "/home/yuvi/Documents/LiClipse Workspace/GUI/src/Pn_code.py", line 24, in pin state=data['State'] KeyError: 'State' </code></pre>
-1
2016-09-03T14:33:38Z
39,308,085
<p>Ok. Error tells you that you don't have key named "State" in you dict under <code>data</code> variable. So maybe there isn't also in incomming json.</p> <p>If in response you get:</p> <pre><code>{"ResponseCode":0,"ResponseMessage":"OK","ResponseDateTime":‌​"9/3/2016 2:41:25 PM GMT","Data":[{"Pincode":"560103","Address":"nagar","City":"B‌​analore","State":"na‌​taka","Country":"Ind‌​ia"}]} </code></pre> <p>then you cannot get "State" by using:</p> <pre><code>data["State"] </code></pre> <p>you have to do it using:</p> <pre><code>data["Data"][0]["State"] </code></pre> <p>and the rest:</p> <pre><code>data["Data"][0]["City"] data["Data"][0]["Country"] </code></pre> <p>Why in this way? Because you have to get nested keys, first key is <code>"Data"</code>, using <code>data["Data"]</code> you recieve a list, and because it's one element list, you have to get first item of the list: <code>data["Data"][0]</code>. And at the end under <code>data["Data"][0]</code> you get dict of keys where you can find State, City, Country.</p>
1
2016-09-03T14:36:25Z
[ "python", "json", "python-3.x" ]
How to display Chinese characters inside a pandas dataframe?
39,308,065
<p>I can read a csv file in which there is a column containing Chinese characters (other columns are English and numbers). However, Chinese characters don't display correctly. see photo below</p> <p><a href="http://i.stack.imgur.com/nG6oN.png" rel="nofollow"><img src="http://i.stack.imgur.com/nG6oN.png" alt="enter image description here"></a></p> <p>I loaded the csv file with <code>pd.read_csv()</code>. </p> <p>Either <code>display(data06_16)</code> or <code>data06_16.head()</code> won't display Chinese characters correctly. </p> <p>I tried to add the following lines into my <code>.bash_profile</code>:</p> <pre><code>export LC_ALL=zh_CN.UTF-8 export LANG=zh_CN.UTF-8 export LC_ALL=en_US.UTF-8 export LANG=en_US.UTF-8 </code></pre> <p>but it doesn't help. </p> <p>Also I have tried to add <code>encoding</code> arg to <code>pd.read_csv()</code>: </p> <pre><code>pd.read_csv('data.csv', encoding='utf_8') pd.read_csv('data.csv', encoding='utf_16') pd.read_csv('data.csv', encoding='utf_32') </code></pre> <p>These won't work at all. </p> <p>How can I display the Chinese characters properly? </p>
0
2016-09-03T14:34:28Z
39,310,336
<p>I see here three possible issues: </p> <p>1) You can try this:</p> <pre><code>import codecs x = codecs.open("testdata.csv", "r", "utf-8") </code></pre> <p>2) Another possibility can be theoretically this:</p> <pre><code>import pandas as pd df = pd.DataFrame(pd.read_csv('testdata.csv',encoding='utf-8')) </code></pre> <p>3) Maybe you should convert you csv file into utf-8 before importing with Python (for example in Notepad++)? It can be a solution for one-time-import, not for automatic process, of course.</p>
0
2016-09-03T18:55:42Z
[ "python", "csv", "pandas", "encoding", "chinese-locale" ]
How to display Chinese characters inside a pandas dataframe?
39,308,065
<p>I can read a csv file in which there is a column containing Chinese characters (other columns are English and numbers). However, Chinese characters don't display correctly. see photo below</p> <p><a href="http://i.stack.imgur.com/nG6oN.png" rel="nofollow"><img src="http://i.stack.imgur.com/nG6oN.png" alt="enter image description here"></a></p> <p>I loaded the csv file with <code>pd.read_csv()</code>. </p> <p>Either <code>display(data06_16)</code> or <code>data06_16.head()</code> won't display Chinese characters correctly. </p> <p>I tried to add the following lines into my <code>.bash_profile</code>:</p> <pre><code>export LC_ALL=zh_CN.UTF-8 export LANG=zh_CN.UTF-8 export LC_ALL=en_US.UTF-8 export LANG=en_US.UTF-8 </code></pre> <p>but it doesn't help. </p> <p>Also I have tried to add <code>encoding</code> arg to <code>pd.read_csv()</code>: </p> <pre><code>pd.read_csv('data.csv', encoding='utf_8') pd.read_csv('data.csv', encoding='utf_16') pd.read_csv('data.csv', encoding='utf_32') </code></pre> <p>These won't work at all. </p> <p>How can I display the Chinese characters properly? </p>
0
2016-09-03T14:34:28Z
39,312,264
<p>I just remembered that the source dataset was created using <code>encoding='GBK'</code>, so I tried again using </p> <pre><code>data06_16 = pd.read_csv("../data/stocks1542monthly.csv", encoding="GBK") </code></pre> <p>Now, I can see all the Chinese characters. </p> <p>Thanks guys!</p>
0
2016-09-03T23:37:30Z
[ "python", "csv", "pandas", "encoding", "chinese-locale" ]
Groupby/Sum in Python Pandas - zero counts not showing ...sometimes
39,308,093
<p><strong>The Background</strong></p> <p>I have a data set of a <em>simulated</em> population of people. They have the following attributes</p> <ol> <li>Age (0-120 years)</li> <li>Gender (male,female)</li> <li>Race (white, black, hispanic, asian, other)</li> </ol> <p>df.head()</p> <pre><code> Age Race Gender in_population 0 32 0 0 1 1 53 0 0 1 2 49 0 1 1 3 12 0 0 1 4 28 0 0 1 </code></pre> <p>There is another variable that identifies the individual as "In_Population"* which is a boolean variable. I am using groupby in pandas to group the population the possible combinations of the 3 attributes to calculate a table of counts by summing the "In_Population" variable in each possible category of person. </p> <p>There are 2 genders * 5 races * 121 ages = 1210 total possible groups that every individual in the population will fall under. </p> <p>If a particular group of people in a particular year has no members (e.g. 0 year old male 'other'), then I still want that group to show up in my group-by dataframe, but with a zero in the count. This happens correctly in the data sample below (Age = 0, Gender = {0,1}, and Race = 4). There were no 'other' zero year olds in this particular </p> <pre><code>grouped_obj = df.groupby( ['Age','Gender','Race'] ) groupedAGR = grouped_obj.sum() groupedAGR.head(10) in_population Age Gender Race 0 0 0 16 1 8 2 63 3 5 4 0 1 0 22 1 4 2 64 3 12 4 0 </code></pre> <p><strong>The issue</strong></p> <p>This only happens for some of the Age-Gender-Race combinations. Sometimes the zero sum groups get skipped entirely. The following is the data for age 45. I was expecting to see 0, indicating that there are no 45 year old male 'other' races in this data set. </p> <pre><code>&gt;&gt;&gt; groupedAGR.xs( 45, level = 'Age' ) in_population Gender Race 0 0 515 1 68 2 40 3 20 1 0 522 1 83 2 48 3 29 4 3 </code></pre> <p><strong>Notes</strong></p> <p>*"In_Population" Basically filters out "newborns" and "immigrants" who are not part of the relevant population when calculating "Mortality Rates"; the deaths in the population happen before immigration and births happen so I exclude them from the calculations. I had a suspicion that this had something to do with it - the zero year olds were showing zero counts but every other age group was not showing anything at all...but that's not the case.</p> <pre><code>&gt;&gt;&gt; groupedAGR.xs( 88, level = 'Age' ) in_population Gender Race 0 0 52 2 1 3 0 1 0 62 1 3 2 5 3 3 4 1 </code></pre> <p>There are no 88 year old Asian men in the population, so there's a zero in the category. There are no 88 year old 'other' men in the population either, but they don't show up at all. </p> <p>EDIT: I added in the code showing how I'm making the group by object in pandas and how I'm summing to find the counts in each group. </p>
2
2016-09-03T14:37:17Z
39,308,267
<p>Use <code>reindex</code> with a predefined index and <code>fill_value=0</code></p> <pre><code>ages = np.arange(21, 26) genders = ['male', 'female'] races = ['white', 'black', 'hispanic', 'asian', 'other'] sim_size = 10000 midx = pd.MultiIndex.from_product([ ages, genders, races ], names=['Age', 'Gender', 'Race']) sim_df = pd.DataFrame({ # I use [1:-1] to explicitly skip some age groups 'Age': np.random.choice(ages[1:-1], sim_size), 'Gender': np.random.choice(genders, sim_size), 'Race': np.random.choice(races, sim_size) }) </code></pre> <p><strong><em>These will have missing age groups</em></strong></p> <pre><code>counts = sim_df.groupby(sim_df.columns.tolist()).size() counts.unstack() </code></pre> <p><a href="http://i.stack.imgur.com/IyIBh.png" rel="nofollow"><img src="http://i.stack.imgur.com/IyIBh.png" alt="enter image description here"></a></p> <p><strong><em>This fills in missing age groups</em></strong></p> <pre><code>counts.reindex(midx, fill_value=0).unstack() </code></pre> <p><a href="http://i.stack.imgur.com/BEjGo.png" rel="nofollow"><img src="http://i.stack.imgur.com/BEjGo.png" alt="enter image description here"></a></p>
3
2016-09-03T14:58:19Z
[ "python", "pandas", "group-by", "aggregation" ]
Calculating percentile of bins from numpy digitize?
39,308,146
<p>I have a set of data, and a set of thresholds for creating bins:</p> <pre><code>data = np.array([0.01, 0.02, 1, 1, 1, 2, 2, 8, 8, 4.5, 6.6]) thresholds = np.array([0,5,10]) bins = np.digitize(data, thresholds, right=True) </code></pre> <p>For each of the elements in <code>bins</code>, I want to know the base percentile. For example, in <code>bins</code>, the smallest bin should start at the 0th percentile. Then the next bin, for example, the 20th percentile. So that if a value in <code>data</code> falls between the 0th and 20th percentile of <code>data</code>, it belongs in the first <code>bin</code>.</p> <p>I've looked into pandas <code>rank(pct=True)</code> but can't seem to get this done correctly.</p> <p>Suggestions?</p>
0
2016-09-03T14:42:50Z
39,316,086
<p>You can calculate the percentile for each element in your data array as described in a previous StackOverflow question (<a href="http://stackoverflow.com/questions/12414043/map-each-list-value-to-its-corresponding-percentile#answer-28577101">Map each list value to its corresponding percentile</a>).</p> <pre><code>import numpy as np from scipy import stats data = np.array([0.01, 0.02, 1, 1, 1, 2, 2, 8, 8, 4.5, 6.6]) </code></pre> <p>Method 1: Using <a href="http://docs.scipy.org/doc/scipy-0.15.1/reference/generated/scipy.stats.percentileofscore.html" rel="nofollow">scipy.stats.percentileofscore</a> :</p> <pre><code>data_percentile = np.array([stats.percentileofscore(data, a) for a in data]) data_percentile Out[1]: array([ 9.09090909, 18.18181818, 36.36363636, 36.36363636, 36.36363636, 59.09090909, 59.09090909, 95.45454545, 95.45454545, 72.72727273, 81.81818182]) </code></pre> <p>Method 2: Using <a href="http://docs.scipy.org/doc/scipy-0.16.0/reference/generated/scipy.stats.rankdata.html" rel="nofollow">scipy.stats.rankdata</a> and normalising to 100 (faster) :</p> <pre><code>ranked = stats.rankdata(data) data_percentile = ranked/len(data)*100 data_percentile Out[2]: array([ 9.09090909, 18.18181818, 36.36363636, 36.36363636, 36.36363636, 59.09090909, 59.09090909, 95.45454545, 95.45454545, 72.72727273, 81.81818182]) </code></pre> <p>Now that you have a list of percentiles, you can bin them as before using <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.digitize.html" rel="nofollow">numpy.digitize</a> :</p> <pre><code>bins_percentile = [0,20,40,60,80,100] data_binned_indices = np.digitize(data_percentile, bins_percentile, right=True) data_binned_indices Out[3]: array([1, 1, 2, 2, 2, 3, 3, 5, 5, 4, 5], dtype=int64) </code></pre> <p>This gives you the data binned according to the indices of your chosen list of percentiles. If desired, you could also return the actual (upper) percentiles using <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.take.html" rel="nofollow">numpy.take</a> : </p> <pre><code>data_binned_percentiles = np.take(bins_percentile, data_binned_indices) data_binned_percentiles Out[4]: array([ 20, 20, 40, 40, 40, 60, 60, 100, 100, 80, 100]) </code></pre>
2
2016-09-04T10:45:21Z
[ "python", "pandas", "numpy", "histogram", "percentage" ]
writing json-ish list to csv, line by line, in python for bitcoin addresses
39,308,153
<p>I'm querying the <a href="https://api.onename.com/#lookup_users" rel="nofollow">onename api</a> in an effort to get the bitcoin addresses of all the users. </p> <p>At the moment I'm getting all the user information as a json-esque list, and then piping the output to a file, it looks like this: </p> <pre><code>[{'0': {'owner_address': '1Q2Tv6f9vXbdoxRmGwNrHbjrrK4Hv6jCsz', 'zone_file': '{"avatar": {"url": "https://s3.amazonaws.com/kd4/111"}, "bitcoin": {"address": "1NmLvYVEZqPGeQNcgFS3DdghpoqaH4r5Xh"}, "cover": {"url": "https://s3.amazonaws.com/dx3/111"}, "facebook": {"proof": {"url": "https://facebook.com/jasondrake1978/posts/10152769170542776"}, "username": "jasondrake1978"}, "graph": {"url": "https://s3.amazonaws.com/grph/111"}, "location": {"formatted": "Mechanicsville, Va"}, "name": {"formatted": "Jason Drake"}, "twitter": {"username": "000001"}, "v": "0.2", "website": "http://1642.com"}', 'verifications': [{'proof_url': 'https://facebook.com/jasondrake1978/posts/10152769170542776', 'service': 'facebook', 'valid': False, 'identifier': 'jasondrake1978'}], 'profile': {'website': 'http://1642.com', 'cover': {'url': 'https://s3.amazonaws.com/dx3/111'}, 'facebook': {'proof': {'url': 'https://facebook.com/jasondrake1978/posts/10152769170542776'}, 'username': 'jasondrake1978'}, 'twitter': {'username': '000001'}, 'bitcoin': {'address': '1NmLvYVEZqPGeQNcgFS3DdghpoqaH4r5Xh'}, 'name': {'formatted': 'Jason Drake'}, 'graph': {'url': 'https://s3.amazonaws.com/grph/111'}, 'location': {'formatted': 'Mechanicsville, Va'}, 'avatar': {'url': 'https://s3.amazonaws.com/kd4/111'}, 'v': '0.2'}}}] </code></pre> <p>what I'm really interested in is the field <code>{"address": "1NmLvYVEZqPGeQNcgFS3DdghpoqaH4r5Xh"}</code>, the rest of the stuff I don't need, I just want the addresses of every user. </p> <p>Is there a way that I can just write only the addresses to a file using python? </p> <p>I'm trying to write it as something like: </p> <pre><code>1NmLvYVEZqPGeQNcgFS3DdghpoqaH4r5Xh, 1GA9RVZHuEE8zm4ooMTiqLicfnvymhzRVm, 1BJdMS9E5TUXxJcAvBriwvDoXmVeJfKiFV, 1NmLvYVEZqPGeQNcgFS3DdghpoqaH4r5Xh, ... </code></pre> <p>and so on. </p> <p>I've tried a number of different ways using <code>dump</code>, <code>dumps</code>, etc. but I haven't yet been able to pin it down. </p> <p>My code looks like this: </p> <pre><code>import os import json import requests #import py2neo import csv # set up authentication parameters #py2neo.authenticate("46.101.180.63:7474", "neo4j", "uni-bonn") # Connect to graph and add constraints. neo4jUrl = os.environ.get('NEO4J_URL',"http://46.101.180.63:7474/db/data/") #graph = py2neo.Graph(neo4jUrl) # Add uniqueness constraints. #graph.run("CREATE CONSTRAINT ON (q:Person) ASSERT q.id IS UNIQUE;") # Build URL. apiUrl = "https://api.onename.com/v1/users" # apiUrl = "https://raw.githubusercontent.com/s-matthew-english/26.04/master/test.json" # Send GET request. Allusersjson = requests.get(apiUrl, headers = {"accept":"application/json"}).json() #print(json)]) UsersDetails=[] for username in Allusersjson['usernames']: usernamex= username[:-3] apiUrl2="https://api.onename.com/v1/users/"+usernamex+"?app-id=demo-app-id&amp;app-secret=demo-app-secret" userinfo=requests.get(apiUrl2, headers = {"accept":"application/json"}).json() # try: # if('bitcoin' not in userinfo[usernamex]['profile']): # continue # else: # UsersDetails.append(userinfo) # except: # continue try: address = userinfo[usernamex]["profile"]["bitcoin"]["address"] UsersDetails.append(address) except KeyError: pass # no address out = "\n".join(UsersDetails) print(out) open("out.csv", "w").write(out) # f = csv.writer(open("test.csv", "wb+")) # Build query. query = """ RETURN {json} """ # Send Cypher query. # py2neo.CypherQuery(graph, query).run(json=json) # graph.run(query).run(json=json) #graph.run(query,json=json) </code></pre> <p>anyway, in such a situation, what's the best way to write out those addresses as csv :/</p> <hr> <p><strong>UPDATE</strong></p> <p>I ran it, and at first it worked, but then I got the following error: <a href="http://i.stack.imgur.com/E63RX.png" rel="nofollow"><img src="http://i.stack.imgur.com/E63RX.png" alt="enter image description here"></a></p>
2
2016-09-03T14:44:32Z
39,308,278
<p>Instead of adding all the information to the UsersDetails list</p> <pre><code>UsersDetails.append(userinfo) </code></pre> <p>you can add just the relevant part (address)</p> <pre><code>try: address = userinfo[usernamex]["profile"]["bitcoin"]["address"] UsersDetails.append(address) except KeyError: pass # no address except TypeError: pass # illformed data </code></pre> <p>To print the values to the screen:</p> <pre><code>out = "\n".join(UsersDetails) print(out) </code></pre> <p>(replace "\n" with "," for comma separated output, instead of one per line)</p> <p>To save to a file:</p> <pre><code>open("out.csv", "w").write(out) </code></pre>
1
2016-09-03T14:59:44Z
[ "python", "json", "csv", "bitcoin" ]
writing json-ish list to csv, line by line, in python for bitcoin addresses
39,308,153
<p>I'm querying the <a href="https://api.onename.com/#lookup_users" rel="nofollow">onename api</a> in an effort to get the bitcoin addresses of all the users. </p> <p>At the moment I'm getting all the user information as a json-esque list, and then piping the output to a file, it looks like this: </p> <pre><code>[{'0': {'owner_address': '1Q2Tv6f9vXbdoxRmGwNrHbjrrK4Hv6jCsz', 'zone_file': '{"avatar": {"url": "https://s3.amazonaws.com/kd4/111"}, "bitcoin": {"address": "1NmLvYVEZqPGeQNcgFS3DdghpoqaH4r5Xh"}, "cover": {"url": "https://s3.amazonaws.com/dx3/111"}, "facebook": {"proof": {"url": "https://facebook.com/jasondrake1978/posts/10152769170542776"}, "username": "jasondrake1978"}, "graph": {"url": "https://s3.amazonaws.com/grph/111"}, "location": {"formatted": "Mechanicsville, Va"}, "name": {"formatted": "Jason Drake"}, "twitter": {"username": "000001"}, "v": "0.2", "website": "http://1642.com"}', 'verifications': [{'proof_url': 'https://facebook.com/jasondrake1978/posts/10152769170542776', 'service': 'facebook', 'valid': False, 'identifier': 'jasondrake1978'}], 'profile': {'website': 'http://1642.com', 'cover': {'url': 'https://s3.amazonaws.com/dx3/111'}, 'facebook': {'proof': {'url': 'https://facebook.com/jasondrake1978/posts/10152769170542776'}, 'username': 'jasondrake1978'}, 'twitter': {'username': '000001'}, 'bitcoin': {'address': '1NmLvYVEZqPGeQNcgFS3DdghpoqaH4r5Xh'}, 'name': {'formatted': 'Jason Drake'}, 'graph': {'url': 'https://s3.amazonaws.com/grph/111'}, 'location': {'formatted': 'Mechanicsville, Va'}, 'avatar': {'url': 'https://s3.amazonaws.com/kd4/111'}, 'v': '0.2'}}}] </code></pre> <p>what I'm really interested in is the field <code>{"address": "1NmLvYVEZqPGeQNcgFS3DdghpoqaH4r5Xh"}</code>, the rest of the stuff I don't need, I just want the addresses of every user. </p> <p>Is there a way that I can just write only the addresses to a file using python? </p> <p>I'm trying to write it as something like: </p> <pre><code>1NmLvYVEZqPGeQNcgFS3DdghpoqaH4r5Xh, 1GA9RVZHuEE8zm4ooMTiqLicfnvymhzRVm, 1BJdMS9E5TUXxJcAvBriwvDoXmVeJfKiFV, 1NmLvYVEZqPGeQNcgFS3DdghpoqaH4r5Xh, ... </code></pre> <p>and so on. </p> <p>I've tried a number of different ways using <code>dump</code>, <code>dumps</code>, etc. but I haven't yet been able to pin it down. </p> <p>My code looks like this: </p> <pre><code>import os import json import requests #import py2neo import csv # set up authentication parameters #py2neo.authenticate("46.101.180.63:7474", "neo4j", "uni-bonn") # Connect to graph and add constraints. neo4jUrl = os.environ.get('NEO4J_URL',"http://46.101.180.63:7474/db/data/") #graph = py2neo.Graph(neo4jUrl) # Add uniqueness constraints. #graph.run("CREATE CONSTRAINT ON (q:Person) ASSERT q.id IS UNIQUE;") # Build URL. apiUrl = "https://api.onename.com/v1/users" # apiUrl = "https://raw.githubusercontent.com/s-matthew-english/26.04/master/test.json" # Send GET request. Allusersjson = requests.get(apiUrl, headers = {"accept":"application/json"}).json() #print(json)]) UsersDetails=[] for username in Allusersjson['usernames']: usernamex= username[:-3] apiUrl2="https://api.onename.com/v1/users/"+usernamex+"?app-id=demo-app-id&amp;app-secret=demo-app-secret" userinfo=requests.get(apiUrl2, headers = {"accept":"application/json"}).json() # try: # if('bitcoin' not in userinfo[usernamex]['profile']): # continue # else: # UsersDetails.append(userinfo) # except: # continue try: address = userinfo[usernamex]["profile"]["bitcoin"]["address"] UsersDetails.append(address) except KeyError: pass # no address out = "\n".join(UsersDetails) print(out) open("out.csv", "w").write(out) # f = csv.writer(open("test.csv", "wb+")) # Build query. query = """ RETURN {json} """ # Send Cypher query. # py2neo.CypherQuery(graph, query).run(json=json) # graph.run(query).run(json=json) #graph.run(query,json=json) </code></pre> <p>anyway, in such a situation, what's the best way to write out those addresses as csv :/</p> <hr> <p><strong>UPDATE</strong></p> <p>I ran it, and at first it worked, but then I got the following error: <a href="http://i.stack.imgur.com/E63RX.png" rel="nofollow"><img src="http://i.stack.imgur.com/E63RX.png" alt="enter image description here"></a></p>
2
2016-09-03T14:44:32Z
39,308,438
<p>You need to reformat the list, either through <code>map()</code> or a list comprehension, to get it down to just the information you want. For example, if the top-level key used in the response from the api.onename.com API is always <code>0</code>, you can do something like this </p> <pre><code>UsersAddresses = [user['0']['profile']['bitcoin']['address'] for user in UsersDetails] </code></pre>
1
2016-09-03T15:17:10Z
[ "python", "json", "csv", "bitcoin" ]
Strange error in python3 when doing big int calculation
39,308,302
<p>I was trying to do this in Python 3.5.2:</p> <pre><code>int(204221389795918291262976/10000) </code></pre> <p>but got the unexpected result: <code>20422138979591827456</code></p> <p>It's working fine in Python 2.7.12, result is: <code>20422138979591829126L</code></p> <p>Any idea why Python 3 gave me the wrong result?</p>
3
2016-09-03T15:01:54Z
39,308,310
<p>In python 3 you have to use integer division <code>//</code> explicitly or else float division will apply even between 2 integers.</p> <p>That's one of the major changes between python 2 and python 3</p> <p>In your example: (will work both in python 2 and python 3 so it's backwards compatible!)</p> <pre><code>int(204221389795918291262976//10000) 20422138979591829126 </code></pre> <p>BTW if you want to make this bug work with python 2 it is also possible :)</p> <pre><code>from __future__ import division </code></pre>
5
2016-09-03T15:03:16Z
[ "python", "python-3.x" ]
How can I extract these list and tuples into strings?
39,308,333
<p>I have these lists and tuples and can't figure out how to extract the numbers out of them.</p> <pre><code>[('40', '50')] [('35', '45', '49')] [('02', '11')] </code></pre> <p>They are stored in three different variables, how can I extract them? I've tried the following:</p> <pre><code>chain.from_iterable(list_one) </code></pre> <p>but it gives me this:</p> <pre><code>&lt;itertools.chain object at 0x1101415f8&gt; </code></pre> <p>Expected output for <code>[('40', '50')]</code> is <code>40 50</code></p> <p>Expected output for <code>[('35', '45', '49')]</code> is <code>35 45 49</code></p> <p>Expected output for <code>[('02', '11')]</code> is <code>02 11</code></p>
0
2016-09-03T15:05:40Z
39,308,405
<p>To get each seperately as string:</p> <pre><code> output = "" a = [('02', '11')] for i in a: for x in i: output = output + " " + x </code></pre>
0
2016-09-03T15:12:27Z
[ "python", "python-3.x" ]
How can I extract these list and tuples into strings?
39,308,333
<p>I have these lists and tuples and can't figure out how to extract the numbers out of them.</p> <pre><code>[('40', '50')] [('35', '45', '49')] [('02', '11')] </code></pre> <p>They are stored in three different variables, how can I extract them? I've tried the following:</p> <pre><code>chain.from_iterable(list_one) </code></pre> <p>but it gives me this:</p> <pre><code>&lt;itertools.chain object at 0x1101415f8&gt; </code></pre> <p>Expected output for <code>[('40', '50')]</code> is <code>40 50</code></p> <p>Expected output for <code>[('35', '45', '49')]</code> is <code>35 45 49</code></p> <p>Expected output for <code>[('02', '11')]</code> is <code>02 11</code></p>
0
2016-09-03T15:05:40Z
39,308,411
<p>Use <strong><a href="https://docs.python.org/3/library/itertools.html#itertools.chain" rel="nofollow"><code>chain</code></a></strong> to chain your lists together and then iterate through them. Then you can unpack in the <code>print</code> call to get every sub-element element printed out.</p> <p>So, if for example your lists are named <code>l1</code>, <code>l2</code> and <code>l3</code> as so:</p> <pre><code>l1, l2, l3 = [('40', '50')], [('35', '45', '49')], [('02', '11')] </code></pre> <p>You're able to access each individual and print it with:</p> <pre><code>for sub in chain(l1, l2, l3): print(*sub) </code></pre> <p>Yields:</p> <pre><code>40 50 35 45 49 02 11 </code></pre> <p>Now, the output from your original attempt, namely:</p> <pre><code>&lt;itertools.chain object at 0x1101415f8&gt; </code></pre> <p>is due to the fact that <code>chain</code> returns an <em>iterator</em> object and that is its representation in the Python REPL. Remember, iterators are meant to be iterated over.</p>
2
2016-09-03T15:13:24Z
[ "python", "python-3.x" ]
Grouping up elements from a list in Python 2.7
39,308,400
<p>Ok, I got a huge text. I extract matches with regex (omitted here because it doesn't matter and I'm bad at this so you don't see how ugly my regex is :) ) and count them. Then, for readability, I split the elements and print them in the fashion I need:</p> <pre><code>import re f = re.findall(r"(...)", PF) a = [[y,f.count(y)] for y in set(f)] (' '.join(map(str, j)) for j in w) for element in w: print element </code></pre> <p>result is something like</p> <pre><code>['202', 1] ['213', 2] ['210', 2] ['211', 2] ['208', 2] ['304', 1] ['107', 2] ['133', 1] ['132', 1] ['131', 2] </code></pre> <p>What I need is to group up the elements, so that I get an output like</p> <pre><code>A ['133', 1] ['132', 1] ['131', 2] B ['202', 1] ['213', 2] C ['304', 1] ['107', 2] ['210', 2] ['211', 2] ['208', 2] </code></pre> <p>Note that: </p> <ul> <li>in the final result I will need 5 groups (A, B, C, D, E)</li> <li>the elements can vary, for example tomorrow 131 might not be present but I might have 232 that goes in group A and the number of elements is different every day</li> <li>it would be perfect, but not mandatory, if the elements in each group would be sorted numerically.</li> <li>Might sound obvious but I'll make it clear anyway, I know exactly which elements need to go in which group. If it is of any help, group <em>A can contain (102, 103), B(104,105,106,201,202,203), C(204,205,206,301,302,303,304), D(107,108,109,110,208,209,210,211,213,305,306,307), E(131,132,133,231,232)</em>.</li> </ul> <p>The script needs to take the results that are present that day, compare them to the list above, and sort into the relative groups.</p> <p>Thanks in advance!</p>
1
2016-09-03T15:11:44Z
39,308,600
<p>You can set up a hash that maps elements to groups. You can then transform each array item from [element,count] to (group,element,count) <em>(using a tuple to make it more easily sortable and such)</em>. Sort that array, then use a loop or <code>reduce</code> to transform that into your final output.</p> <pre><code>mapElementsToGroups = {'131': 'A', '202': 'B', '304': 'C', …} elementsFoundByGroup = {} for (group, element, count) in sorted( [(mapElementsToGroups[item[0]], item[1], item[2]) for item in a] ): elementsFoundByGroup[group] = elementsFoundByGroup.get(group, []) + [(element, count)] </code></pre> <p>You now have a dictionary mapping each group name found to the list of elements and counts found within that group. The quick print is:</p> <pre><code>print [ group + " " + elements.join("\n " + " "*len(group)) for (group,elements) in sorted(elementsFoundByGroup.items()) ].join("\n") </code></pre>
0
2016-09-03T15:36:20Z
[ "python", "arrays", "list", "python-2.7", "count" ]
Grouping up elements from a list in Python 2.7
39,308,400
<p>Ok, I got a huge text. I extract matches with regex (omitted here because it doesn't matter and I'm bad at this so you don't see how ugly my regex is :) ) and count them. Then, for readability, I split the elements and print them in the fashion I need:</p> <pre><code>import re f = re.findall(r"(...)", PF) a = [[y,f.count(y)] for y in set(f)] (' '.join(map(str, j)) for j in w) for element in w: print element </code></pre> <p>result is something like</p> <pre><code>['202', 1] ['213', 2] ['210', 2] ['211', 2] ['208', 2] ['304', 1] ['107', 2] ['133', 1] ['132', 1] ['131', 2] </code></pre> <p>What I need is to group up the elements, so that I get an output like</p> <pre><code>A ['133', 1] ['132', 1] ['131', 2] B ['202', 1] ['213', 2] C ['304', 1] ['107', 2] ['210', 2] ['211', 2] ['208', 2] </code></pre> <p>Note that: </p> <ul> <li>in the final result I will need 5 groups (A, B, C, D, E)</li> <li>the elements can vary, for example tomorrow 131 might not be present but I might have 232 that goes in group A and the number of elements is different every day</li> <li>it would be perfect, but not mandatory, if the elements in each group would be sorted numerically.</li> <li>Might sound obvious but I'll make it clear anyway, I know exactly which elements need to go in which group. If it is of any help, group <em>A can contain (102, 103), B(104,105,106,201,202,203), C(204,205,206,301,302,303,304), D(107,108,109,110,208,209,210,211,213,305,306,307), E(131,132,133,231,232)</em>.</li> </ul> <p>The script needs to take the results that are present that day, compare them to the list above, and sort into the relative groups.</p> <p>Thanks in advance!</p>
1
2016-09-03T15:11:44Z
39,308,612
<p>One (probably not most elegant) solution would be to define a dictionary with the mappings and then lookup the name of the group to which the element belongs to. </p> <pre><code>elements = { "133": "A", "132": "A", "202": "B", ... } </code></pre> <p>The elements can then be added to a new dictionary with group names as keys:</p> <pre><code>groups = {"A":[], "B": [], ...} for element, count in a: group = elements[element] groups[group].append( (element, count) ) for group in groups: groups[group].sort() # sort by element for element, count in groups[group]: print "%s %s %s" % (group, element, count) </code></pre>
0
2016-09-03T15:38:08Z
[ "python", "arrays", "list", "python-2.7", "count" ]
Mimicking HTML5 Video support on PhantomJS used through Selenium in Python
39,308,447
<p>I am trying to extract the source link of an HTML5 video found in the video tag . Using Firefox webdrive , I am able to get the desired result ie - </p> <pre><code>[&lt;video class="video-stream html5-main-video" src='myvideoURL..'&lt;/video&gt;] </code></pre> <p>but if I use PhantomJS -</p> <pre><code> &lt;video class="video-stream html5-main-video" style="width: 854px; height: 480px; left: 0px; top: 0px; -webkit-transform: none;" tabindex="-1"&gt;&lt;/video&gt; </code></pre> <p>I suspect this is because of PhantomJS' lack of HTML5 Video support . Is there anyway I can trick the webpage into thinking that HTML5 Video is supported so that it generates the URL ? Or can I do something else ?</p> <p>tried this</p> <pre><code>try: WebDriverWait(browser,10).until(EC.presence_of_element_located((By.XPATH, "//video"))) finally: k = browser.page_source browser.quit() soup = BeautifulSoup(k,'html.parser') print (soup.find_all('video')) </code></pre>
2
2016-09-03T15:18:34Z
39,315,815
<p>The way Firefox and phantomjs webdrivers communicate with Selenium are quite different.</p> <p>When using Firefox, it signals back that the page has finished loading after it loaded some of the javascript</p> <p>Differently in phantomjs, it signals Selenium that the page has finished loading as soon as it is able to get the page source meaning it wouldn't have loaded any javascript.</p> <p>What you need to do is <a href="http://www.seleniumhq.org/docs/04_webdriver_advanced.jsp" rel="nofollow">Wait</a> for the element to be present before extracting it, in this case it would be:</p> <pre><code>video = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, "//video"))) </code></pre> <p>EDIT:</p> <p>Youtube first checks if the browser supports the video content before deciding whether to provide the source, theres a workaround though described <a href="http://stackoverflow.com/questions/30146353/phantomjs-not-mimicking-browser-behavior-when-looking-at-youtube-videos">here</a></p>
1
2016-09-04T10:11:57Z
[ "python", "selenium", "phantomjs" ]
Does filter,map, and reduce in Python create a new copy of list?
39,308,479
<p>Using <code>Python 2.7</code>. Let us say we have <code>list_of_nums = [1,2,2,3,4,5]</code> and we want to remove all occurrences of 2. We can achieve it by <code>list_of_nums[:] = filter(lambda x: x! = 2, list_of_nums)</code> or <code>list_of_nums = filter(lambda x: x! = 2, list_of_nums)</code>.</p> <p>Is this an "in-place" substitution? Also, are we creating a copy of list when we use filter?</p>
3
2016-09-03T15:21:39Z
39,308,693
<pre><code>list_of_nums[:] = filter(lambda x: x != 2, list_of_nums) </code></pre> <p>and</p> <pre><code>list_of_nums = filter(lambda x: x != 2, list_of_nums) </code></pre> <p>are two different operations that end up with <em>mostly</em> the same result.</p> <p>In both cases,</p> <pre><code>filter(lambda x: x != 2, list_of_nums) </code></pre> <p>returns either a new list containing items that match the filter (in Python 2), or an iterable over <code>list_of_nums</code> that returns the same items (in Python 3).</p> <p>The first case,</p> <pre><code>list_of_nums[:] = filter(lambda x: x != 2, list_of_nums) </code></pre> <p>then deletes all items from <code>list_of_nums</code> and replaces them with the items from the new list or iterable.</p> <p>The second case,</p> <pre><code>list_of_nums = filter(lambda x: x != 2, list_of_nums) </code></pre> <p>assigns the new list to the variable <code>list_of_nums</code>.</p> <p>The time when this makes a difference is this:</p> <pre><code>def processItemsNotTwo_case1(list_of_nums): list_of_nums[:] = filter(lambda x: x != 2, list_of_nums) # do stuff here # return something def processItemsNotTwo_case2(list_of_nums): list_of_nums = filter(lambda x: x != 2, list_of_nums) # do stuff here # return something list1 = [1,2,2,3,4,5] processItemsNotTwo_case1(list1) list2 = [1,2,2,3,4,5] processItemsNotTwo_case2(list2) </code></pre> <p>With this code, <code>list1</code> ends up with the new contents <code>[1,3,4,5]</code>, whereas <code>list2</code> ends up with the original contents <code>[1,2,2,3,4,5]</code>.</p>
4
2016-09-03T15:48:04Z
[ "python", "python-2.7", "lambda", "higher-order-functions" ]
Python3.4 int object is not iterable - MySQLdb
39,308,534
<p>I'm running python3.4 and i'm trying to run a query with the MySQLdb library.</p> <p>I've done one successful query but now I am stuck when it comes to integers in a query. Here's the code:</p> <pre><code> location = player_info[6] query2 = ("SELECT name FROM locations WHERE id=%d"); execute = cursor.execute(query2, (location)); </code></pre> <p>Value of the variable location is 2. I just keep getting the error:</p> <blockquote> <p>File "login.py", line 75, in tryLogin execute = cursor.execute(query2, (location));</p> <p>File "/usr/lib/python3/dist-packages/MySQLdb/cursors.py", line 195, in execute args = tuple(map(db.literal, args)) TypeError: 'int' object is not iterable</p> </blockquote> <p>I tried to change the %d to %s because someone said it should all be in string format but I still get the same error.</p> <p>I have also tried changing "location" variable to simply:</p> <p>location = 2</p> <p>Any ideas?</p>
0
2016-09-03T15:28:57Z
39,308,731
<pre><code> execute = cursor.execute(query2, (location)); </code></pre> <p>In python, <code>(location)</code> is a parenthesized expression, not a tuple. In order to force that to be a tuple, you need to add a comma: <code>(location,)</code></p> <pre><code> execute = cursor.execute(query2, (location,)); </code></pre>
1
2016-09-03T15:51:49Z
[ "python", "mysql-python" ]
Java generate random int from timestamp
39,308,625
<p>I am trying to generate a random int from timestamp, but below java code gives output in following format.</p> <pre><code>java.util.Date date= new java.util.Date(); System.out.println(new Timestamp(date.getTime())); </code></pre> <p>Output : </p> <blockquote> <p>2010-03-08 14:59:30.252</p> </blockquote> <p>Any java equivalent for python <code>print time.time()</code> which gives output like <code>1472916832.39</code></p>
-1
2016-09-03T15:40:20Z
39,308,751
<p>To print the number of milliseconds from epoch to the Date object use <code>System.out.println(Long.toString(new Date().getTime()));</code>.</p> <p>Otherwise if you just want the current count of milliseconds or nanoseconds since epoch, you have a couple options:</p> <ul> <li><code>System.currentTimeMillis()</code></li> <li><code>System.nanoTime()</code></li> </ul> <p>both of which return a long.</p>
2
2016-09-03T15:53:48Z
[ "java", "python", "timestamp" ]
Java generate random int from timestamp
39,308,625
<p>I am trying to generate a random int from timestamp, but below java code gives output in following format.</p> <pre><code>java.util.Date date= new java.util.Date(); System.out.println(new Timestamp(date.getTime())); </code></pre> <p>Output : </p> <blockquote> <p>2010-03-08 14:59:30.252</p> </blockquote> <p>Any java equivalent for python <code>print time.time()</code> which gives output like <code>1472916832.39</code></p>
-1
2016-09-03T15:40:20Z
39,308,766
<p>You can use System. currentTimeMillis() or System.nanoTime()</p>
0
2016-09-03T15:55:58Z
[ "java", "python", "timestamp" ]
Cassandra error 'NoneType' object has no attribute 'datacenter' while importing csv
39,308,666
<p>I have set up a cassandra cluster with 3 nodes.</p> <p>I am trying to do a simple export/ import using copy command, but it fails with the following error:</p> <pre><code>cqlsh:walmart&gt; select * from test; store | date | isholiday | dept -------+------------+-----------+------ 1 | 22/04/1993 | False | 1 cqlsh&gt; use walmart; cqlsh:walmart&gt; copy test to 'test.csv'; 'NoneType' object has no attribute 'datacenter' </code></pre> <p>I researched the error and every related link seems to point out to python problems.</p> <p>I also installed python driver pip cassandra-driver. Inserting data manually works, but not through export/ import.</p> <pre><code>cassandra@cassandra-srv01:~$ python -c 'import cassandra; print cassandra.__version__' 3.6.0 </code></pre> <p>Ubuntu 16.04 64bit.</p> <p>how can I fix this error?</p> <p>the logs inside <code>$CASSANDRA_HOME/logs</code> don't have any entries regarding the error.</p> <p>Traceback:</p> <pre><code>Traceback (most recent call last): File "/usr/local/Cellar/cassandra/3.7/libexec/bin/cqlsh.py", line 1152, in onecmd self.handle_statement(st, statementtext) File "/usr/local/Cellar/cassandra/3.7/libexec/bin/cqlsh.py", line 1189, in handle_statement return custom_handler(parsed) File "/usr/local/Cellar/cassandra/3.7/libexec/bin/cqlsh.py", line 1907, in do_copy task = ImportTask(self, ks, table, columns, fname, opts, DEFAULT_PROTOCOL_VERSION, CONFIG_FILE) File "/usr/local/Cellar/cassandra/3.7/libexec/bin/../pylib/cqlshlib/copyutil.py", line 1061, in __init__ CopyTask.__init__(self, shell, ks, table, columns, fname, opts, protocol_version, config_file, 'from') File "/usr/local/Cellar/cassandra/3.7/libexec/bin/../pylib/cqlshlib/copyutil.py", line 207, in __init__ self.local_dc = shell.conn.metadata.get_host(shell.hostname).datacenter AttributeError: 'NoneType' object has no attribute 'datacenter </code></pre>
1
2016-09-03T15:44:27Z
39,358,147
<p>The issue is with the build of cqlsh that you are using, In that build copyutil is not using correct host to connect. It has been <a href="http://mail-archives.apache.org/mod_mbox/cassandra-commits/201607.mbox/%3Cfe01c229440a4ac6a05f776a666548ad@git.apache.org%3E" rel="nofollow">fixed</a> in the new releases. Just clone the <a href="https://github.com/apache/cassandra" rel="nofollow">repo</a> and run <code>bin/cqlsh</code> and try the same commands.</p>
1
2016-09-06T21:30:05Z
[ "python", "csv", "cassandra", "copy", "nonetype" ]
Cassandra error 'NoneType' object has no attribute 'datacenter' while importing csv
39,308,666
<p>I have set up a cassandra cluster with 3 nodes.</p> <p>I am trying to do a simple export/ import using copy command, but it fails with the following error:</p> <pre><code>cqlsh:walmart&gt; select * from test; store | date | isholiday | dept -------+------------+-----------+------ 1 | 22/04/1993 | False | 1 cqlsh&gt; use walmart; cqlsh:walmart&gt; copy test to 'test.csv'; 'NoneType' object has no attribute 'datacenter' </code></pre> <p>I researched the error and every related link seems to point out to python problems.</p> <p>I also installed python driver pip cassandra-driver. Inserting data manually works, but not through export/ import.</p> <pre><code>cassandra@cassandra-srv01:~$ python -c 'import cassandra; print cassandra.__version__' 3.6.0 </code></pre> <p>Ubuntu 16.04 64bit.</p> <p>how can I fix this error?</p> <p>the logs inside <code>$CASSANDRA_HOME/logs</code> don't have any entries regarding the error.</p> <p>Traceback:</p> <pre><code>Traceback (most recent call last): File "/usr/local/Cellar/cassandra/3.7/libexec/bin/cqlsh.py", line 1152, in onecmd self.handle_statement(st, statementtext) File "/usr/local/Cellar/cassandra/3.7/libexec/bin/cqlsh.py", line 1189, in handle_statement return custom_handler(parsed) File "/usr/local/Cellar/cassandra/3.7/libexec/bin/cqlsh.py", line 1907, in do_copy task = ImportTask(self, ks, table, columns, fname, opts, DEFAULT_PROTOCOL_VERSION, CONFIG_FILE) File "/usr/local/Cellar/cassandra/3.7/libexec/bin/../pylib/cqlshlib/copyutil.py", line 1061, in __init__ CopyTask.__init__(self, shell, ks, table, columns, fname, opts, protocol_version, config_file, 'from') File "/usr/local/Cellar/cassandra/3.7/libexec/bin/../pylib/cqlshlib/copyutil.py", line 207, in __init__ self.local_dc = shell.conn.metadata.get_host(shell.hostname).datacenter AttributeError: 'NoneType' object has no attribute 'datacenter </code></pre>
1
2016-09-03T15:44:27Z
39,381,054
<p>it is not so good, but i will try to contribute to the problem. i'm new in cassandra and had exactly the same problem while trying to import data into a cassandra table via the copy function. i connect to the server on which cassandra is installed through cqlsh installed on a virtual machine. so i have to specify the server ip address and the port while running the cqlsh command: # cqlsh ip_address port i connected with the servername like that: # cqlsh myserver.example.com 9040 and i was connected and the copy fonction didn't work.</p> <p>But connecting with the numerical ip address of the server (for example:</p> <h1>cqlsh 127.0.0.1 9040) it has worked.</h1> <p>it was by pure chance, i have simply tested and it has worked for me.</p> <p>when someone here can explain this fact it would be great!</p>
1
2016-09-08T00:58:50Z
[ "python", "csv", "cassandra", "copy", "nonetype" ]
Django-registration custom urls
39,308,702
<p>I've used django-registration (<a href="https://django-registration.readthedocs.io/en/latest/index.html" rel="nofollow">the app</a>, HMAC) for user registration and login. Everything works fine, but I would like to have the login form at <a href="http://localhost:8000/" rel="nofollow">http://localhost:8000/</a>, instead of /accounts/login/. What would be the cleanest way to accomplish this?</p> <p>When just copying the form from login.html to my index.html file, which provides the view of the main page, it (obviously (?)) doesn't work. I'm using django 1.9.6 and django-registration 2.1. Please note that I haven't got 'registration' in INSTALLED_APPS in the setting.py file, since that wasn't needed according to the docs.</p> <p>This is my login.html file:</p> <pre><code>{% extends "mysite/base.html" %} {% load i18n %} {% block content %} &lt;form method="post" action="."&gt; {% csrf_token %} {{ form.as_p }} &lt;input type="submit" value="{% trans 'Log in' %}" /&gt; &lt;input type="hidden" name="next" value="{{next}}" /&gt; &lt;/form&gt; &lt;p&gt;{% trans "Forgot password" %}? &lt;a href="{% url 'auth_password_reset' %}"&gt;{% trans "Reset it" %}&lt;/a&gt;!&lt;/p&gt; &lt;p&gt;{% trans "Not member" %}? &lt;a href="{% url 'registration_register' %}"&gt;{% trans "Register" %}&lt;/a&gt;!&lt;/p&gt; {% endblock %} </code></pre> <p>And my urls.py file:</p> <pre><code>from django.conf.urls import include, url from django.contrib import admin from . import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', views.index, name='index'), url(r'^accounts/', include('registration.backends.hmac.urls')), url(r'^groups/', include('groups.urls')), #my own app ] </code></pre>
0
2016-09-03T15:48:45Z
39,309,933
<p>Theres a few ways to do it, and it really depends on whether you care about redirects and how you like to organize your URL structure.</p> <p>I would do something like this:</p> <p>from django.conf.urls import include, url from django.contrib import admin from . import views form registration.backends.hmac.views import login</p> <pre><code>urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', views.index, name='index'), url(r'^accounts/login$', RedirectView.as_view(url='/login'), name='got-to-lgoin') # You have several options for this, see below url(r'^accounts/', include('registration.backends.hmac.urls')), url(r'^login/$, login, name='login'), url(r'^groups/', include('groups.urls')), #my own app ] </code></pre> <p>Now as per the second login url, you could remove it from the hmac.urls, change it to redirect to /login, make a new custom urls file and include that, or do what I did and just add a redirect view.</p> <p>Like I said its personal preference. If youre going to do it for more urls other than just /login and /logout, I would just make a separate urls.py file and include that. It's cleaner.</p> <p>Hope this helps!</p>
0
2016-09-03T18:07:09Z
[ "python", "django", "django-registration" ]
python3-pip installed, but returns "command not found"?
39,308,772
<p>There are a few other posts I've found that address my question but none of them solve my problem so I'm creating this post.</p> <p>I'm trying to install rpi.gpio for my Raspberry Pi B+. I installed python3-pip, but every time I try to call it from the command line with pip3 I get "command not found". I uninstalled it with:</p> <pre><code>sudo apt-get remove python3-pip </code></pre> <p>then reinstalled</p> <pre><code>sudo apt-get install python3-pip </code></pre> <p>and got the following:</p> <pre><code>Reading package lists... Done Building dependency tree Reading state information... Done The following NEW packages will be installed: python3-pip 0 upgraded, 1 newly installed, 0 to remove and 183 not upgraded. Need to get 0 B/79.7 kB of archives. After this operation, 361 kB of additional disk space will be used. Selecting previously unselected package python3-pip. (Reading database ... 70831 files and directories currently installed.) Unpacking python3-pip (from .../python3-pip_1.1-3_all.deb) ... Processing triggers for man-db ... Setting up python3-pip (1.1-3) ... </code></pre> <p>But when I try to do:</p> <pre><code>sudo pip3 install rpi.gpio </code></pre> <p>I get:</p> <pre><code>sudo: pip3: command not found </code></pre> <p>I've tried suggestions from this site and others to see if pip is installed and where to locate it, but I always get "command not found":</p> <pre><code>pi@raspberrypi ~ $ locate pip3 bash: locate: command not found pi@raspberrypi ~ $ pip --version bash: pip: command not found pi@raspberrypi ~ $ python3-pip --version bash: python3-pip: command not found pi@raspberrypi ~ $ python3.2-pip --version bash: python3.2-pip: command not found </code></pre> <p>How can I get pip to install??? This is driving me nuts....</p>
0
2016-09-03T15:56:45Z
39,308,917
<p>You can always use <code>python3 -m pip</code> (possibly with <code>sudo</code>) if the library is available - like installed to the right place. This does not depend on pip being installed as a normal command which is just a shortcut for this.</p>
0
2016-09-03T16:14:57Z
[ "python", "pip", "raspberry-pi2" ]
python3-pip installed, but returns "command not found"?
39,308,772
<p>There are a few other posts I've found that address my question but none of them solve my problem so I'm creating this post.</p> <p>I'm trying to install rpi.gpio for my Raspberry Pi B+. I installed python3-pip, but every time I try to call it from the command line with pip3 I get "command not found". I uninstalled it with:</p> <pre><code>sudo apt-get remove python3-pip </code></pre> <p>then reinstalled</p> <pre><code>sudo apt-get install python3-pip </code></pre> <p>and got the following:</p> <pre><code>Reading package lists... Done Building dependency tree Reading state information... Done The following NEW packages will be installed: python3-pip 0 upgraded, 1 newly installed, 0 to remove and 183 not upgraded. Need to get 0 B/79.7 kB of archives. After this operation, 361 kB of additional disk space will be used. Selecting previously unselected package python3-pip. (Reading database ... 70831 files and directories currently installed.) Unpacking python3-pip (from .../python3-pip_1.1-3_all.deb) ... Processing triggers for man-db ... Setting up python3-pip (1.1-3) ... </code></pre> <p>But when I try to do:</p> <pre><code>sudo pip3 install rpi.gpio </code></pre> <p>I get:</p> <pre><code>sudo: pip3: command not found </code></pre> <p>I've tried suggestions from this site and others to see if pip is installed and where to locate it, but I always get "command not found":</p> <pre><code>pi@raspberrypi ~ $ locate pip3 bash: locate: command not found pi@raspberrypi ~ $ pip --version bash: pip: command not found pi@raspberrypi ~ $ python3-pip --version bash: python3-pip: command not found pi@raspberrypi ~ $ python3.2-pip --version bash: python3.2-pip: command not found </code></pre> <p>How can I get pip to install??? This is driving me nuts....</p>
0
2016-09-03T15:56:45Z
39,308,923
<p>Try to use:</p> <pre><code>sudo python3 -m pip </code></pre> <p>or</p> <pre><code>sudo python -m pip </code></pre>
0
2016-09-03T16:15:47Z
[ "python", "pip", "raspberry-pi2" ]
python3-pip installed, but returns "command not found"?
39,308,772
<p>There are a few other posts I've found that address my question but none of them solve my problem so I'm creating this post.</p> <p>I'm trying to install rpi.gpio for my Raspberry Pi B+. I installed python3-pip, but every time I try to call it from the command line with pip3 I get "command not found". I uninstalled it with:</p> <pre><code>sudo apt-get remove python3-pip </code></pre> <p>then reinstalled</p> <pre><code>sudo apt-get install python3-pip </code></pre> <p>and got the following:</p> <pre><code>Reading package lists... Done Building dependency tree Reading state information... Done The following NEW packages will be installed: python3-pip 0 upgraded, 1 newly installed, 0 to remove and 183 not upgraded. Need to get 0 B/79.7 kB of archives. After this operation, 361 kB of additional disk space will be used. Selecting previously unselected package python3-pip. (Reading database ... 70831 files and directories currently installed.) Unpacking python3-pip (from .../python3-pip_1.1-3_all.deb) ... Processing triggers for man-db ... Setting up python3-pip (1.1-3) ... </code></pre> <p>But when I try to do:</p> <pre><code>sudo pip3 install rpi.gpio </code></pre> <p>I get:</p> <pre><code>sudo: pip3: command not found </code></pre> <p>I've tried suggestions from this site and others to see if pip is installed and where to locate it, but I always get "command not found":</p> <pre><code>pi@raspberrypi ~ $ locate pip3 bash: locate: command not found pi@raspberrypi ~ $ pip --version bash: pip: command not found pi@raspberrypi ~ $ python3-pip --version bash: python3-pip: command not found pi@raspberrypi ~ $ python3.2-pip --version bash: python3.2-pip: command not found </code></pre> <p>How can I get pip to install??? This is driving me nuts....</p>
0
2016-09-03T15:56:45Z
39,309,012
<p>To install <code>locate</code> run</p> <pre><code>sudo apt-get install mlocate </code></pre> <p>Then update the locatedb with</p> <pre><code>sudo updatedb </code></pre> <p>This could take sometime depending on the number of files you have on your machine</p> <p>locate should work now and show you where all the pip's are</p> <p>Back to the root problem. In Raspian wheezy, pip is managed with <code>pip-3.2</code>, you can easily create a <code>pip3</code> alias or a symlink to it to avoid typing <code>pip-3.2</code> every time.</p> <pre><code>pip-3.2 install rpi.gpio </code></pre> <p>For more info you can read the <a href="https://www.raspberrypi.org/documentation/linux/software/python.md" rel="nofollow">docs</a> on python packages and raspberry pi</p>
2
2016-09-03T16:25:49Z
[ "python", "pip", "raspberry-pi2" ]
Tkinter Update intvar in label
39,308,786
<p>I am trying to have an integer to constantly change inside a label using Tkinter.</p> <pre><code>import tkinter root = tkinter.Tk() var = tkinter.IntVar() label = tkinter.Label(root, textvariable=var) button = tkinter.Button(root, command=lambda: var.set(var.get() + 1), text='+1') label.pack() button.pack() root.mainloop() </code></pre> <p>The closest I have come to what I need after searching is to the example above. However you need to click a button for the integer to change, What I need is without anything for the user to do, for the integer to change.</p> <p>I have an array which is constantly getting bigger while the program is running which I need to print its length each time there is one new element appended to it.</p> <p>Update: Working answer:</p> <pre><code>import tkinter import time root = tkinter.Tk() var = tkinter.IntVar() label = tkinter.Label(root, textvariable=var) label.pack() def update_Value(): for i in range(5): time.sleep(1) var.set(i) root.update() root.after(0, update_Value) root.mainloop() </code></pre>
-1
2016-09-03T15:57:57Z
39,308,869
<p>You can use <code>root.after(time_in_milisecond, function_name)</code> to call function which change value in label without user interaction.</p> <p>Example: <a href="https://github.com/furas/my-python-codes/blob/master/tkinter/timer-using-after/clock-function.py" rel="nofollow">showing current time using after</a></p> <hr> <p>Here's an example of the code from the question, using <code>after</code> to automatically call the function after <code>mainloop</code> starts:</p> <pre><code>import tkinter import time root = tkinter.Tk() var = tkinter.IntVar() label = tkinter.Label(root, textvariable=var) label.pack() def function(): for i in range(5): var.set(i) root.update() time.sleep(1) # to slow down root.after(1, function) root.mainloop() </code></pre>
1
2016-09-03T16:08:28Z
[ "python", "tkinter" ]
How do I apply function to third-dimension array effectively with numpy?
39,308,835
<p>I want to apply arbitrary function to 3d-ndarray as element, which use (3rd-dimensional) array for its arguments and return scalar.As a result, we should get 2d-Matrix.</p> <p>e.g) pseudo code </p> <pre><code>A = [[[1,2,3],[4,5,6]], [[7,8,9],[10,11,12]]] A.apply_3d_array(sum) ## or apply_3d_array(A,sum) is Okey. &gt;&gt; [[6,15],[24,33]] </code></pre> <p>I understand it's possible with loop using ndarray.shape function,but direct index access is inefficient as official document says. Is there more effective way than using loop? </p> <pre><code>def chromaticity(pixel): geo_mean = math.pow(sum(pixel),1/3) return map(lambda x: math.log(x/geo_mean),pixel ) </code></pre>
1
2016-09-03T16:03:42Z
39,308,953
<p><code>apply_along_axis</code> is designed to make this task easy:</p> <pre><code>In [683]: A=np.arange(1,13).reshape(2,2,3) In [684]: A Out[684]: array([[[ 1, 2, 3], [ 4, 5, 6]], [[ 7, 8, 9], [10, 11, 12]]]) In [685]: np.apply_along_axis(np.sum, 2, A) Out[685]: array([[ 6, 15], [24, 33]]) </code></pre> <p>It, in effect, does</p> <pre><code>for all i,j: out[i,j] = func( A[i,j,:]) </code></pre> <p>taking care of the details. It's not faster than doing that iteration yourself, but it makes it easier.</p> <p>Another trick is to reshape your input to 2d, perform the simpler 1d iteration, and the reshape the result</p> <pre><code> A1 = A.reshape(-1, A.shape[-1]) for i in range(A1.shape[0]): out[i] = func(A1[i,:]) out.reshape(A.shape[:2]) </code></pre> <p>To do things faster, you need to dig into the guts of the function, and figure out how to use compile numpy operations on more than one dimension. In the simple case of <code>sum</code>, that function already can work on selected axes.</p>
1
2016-09-03T16:18:42Z
[ "python", "arrays", "numpy", "multidimensional-array", "vectorization" ]
How do I apply function to third-dimension array effectively with numpy?
39,308,835
<p>I want to apply arbitrary function to 3d-ndarray as element, which use (3rd-dimensional) array for its arguments and return scalar.As a result, we should get 2d-Matrix.</p> <p>e.g) pseudo code </p> <pre><code>A = [[[1,2,3],[4,5,6]], [[7,8,9],[10,11,12]]] A.apply_3d_array(sum) ## or apply_3d_array(A,sum) is Okey. &gt;&gt; [[6,15],[24,33]] </code></pre> <p>I understand it's possible with loop using ndarray.shape function,but direct index access is inefficient as official document says. Is there more effective way than using loop? </p> <pre><code>def chromaticity(pixel): geo_mean = math.pow(sum(pixel),1/3) return map(lambda x: math.log(x/geo_mean),pixel ) </code></pre>
1
2016-09-03T16:03:42Z
39,309,371
<p>Given the function implementation, we could vectorize it using <a href="http://docs.scipy.org/doc/numpy/reference/ufuncs.html" rel="nofollow"><code>NumPy ufuncs</code></a> that would operate on the entire input array <code>A</code> in one go and thus avoid the <code>math</code> library functions that doesn't support vectorization on arrays. In this process, we would also bring in the very efficient vectorizing tool : <a href="http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html" rel="nofollow"><code>NumPy broadcasting</code></a>. So, we would have an implementation like so -</p> <pre><code>np.log(A/np.power(np.sum(A,2,keepdims=True),1/3)) </code></pre> <p><strong>Sample run and verification</strong></p> <p>The function implementation without the <code>lamdba</code> construct and introducing NumPy functions instead of <code>math</code> library functions, would look something like this -</p> <pre><code>def chromaticity(pixel): geo_mean = np.power(np.sum(pixel),1/3) return np.log(pixel/geo_mean) </code></pre> <p>Sample run with the iterative implementation -</p> <pre><code>In [67]: chromaticity(A[0,0,:]) Out[67]: array([-0.59725316, 0.09589402, 0.50135913]) In [68]: chromaticity(A[0,1,:]) Out[68]: array([ 0.48361096, 0.70675451, 0.88907607]) In [69]: chromaticity(A[1,0,:]) Out[69]: array([ 0.88655887, 1.02009026, 1.1378733 ]) In [70]: chromaticity(A[1,1,:]) Out[70]: array([ 1.13708257, 1.23239275, 1.31940413]) </code></pre> <p>Sample run with the proposed vectorized implementation -</p> <pre><code>In [72]: np.log(A/np.power(np.sum(A,2,keepdims=True),1/3)) Out[72]: array([[[-0.59725316, 0.09589402, 0.50135913], [ 0.48361096, 0.70675451, 0.88907607]], [[ 0.88655887, 1.02009026, 1.1378733 ], [ 1.13708257, 1.23239275, 1.31940413]]]) </code></pre> <p><strong>Runtime test</strong></p> <pre><code>In [131]: A = np.random.randint(0,255,(512,512,3)) # 512x512 colored image In [132]: def org_app(A): ...: out = np.zeros(A.shape) ...: for i in range(A.shape[0]): ...: for j in range(A.shape[1]): ...: out[i,j] = chromaticity(A[i,j]) ...: return out ...: In [133]: %timeit org_app(A) 1 loop, best of 3: 5.99 s per loop In [134]: %timeit np.apply_along_axis(chromaticity, 2, A) #@hpaulj's soln 1 loop, best of 3: 9.68 s per loop In [135]: %timeit np.log(A/np.power(np.sum(A,2,keepdims=True),1/3)) 10 loops, best of 3: 90.8 ms per loop </code></pre> <p>That's why always try to push in <code>NumPy funcs</code> when vectorizing things with arrays and work on as many elements in one-go as possible!</p>
3
2016-09-03T17:06:28Z
[ "python", "arrays", "numpy", "multidimensional-array", "vectorization" ]
django:column books_book.publication_date does not exist
39,308,840
<p>I'm reading chapter 6 of django book: <a href="http://www.djangobook.com/en/2.0/chapter06.html" rel="nofollow">http://www.djangobook.com/en/2.0/chapter06.html</a> And I've done whatever chapter 5 and 6 of this book told me and I checked my work and searched the error many times but I'm still having problem when I go to <a href="http://127.0.0.1:8000/admin/books/book/" rel="nofollow">http://127.0.0.1:8000/admin/books/book/</a> to add some book and save it, I get this error:</p> <blockquote> <p>ProgrammingError at /admin/books/book/</p> <p>column books_book.publication_date does not exist LINE 1: ...books_book"."title", "books_book"."publisher_id", "books_boo...</p> </blockquote> <p>And this is my models on models.py:</p> <pre><code>from django.db import models class Publisher(models.Model): name = models.CharField(max_length=30) address = models.CharField(max_length=50) city = models.CharField(max_length=60) state_province = models.CharField(max_length=30) country = models.CharField(max_length=50) website = models.URLField() def __unicode__(self): return self.name class Meta: ordering = ['name'] class Author(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=40) email = models.EmailField() def __unicode__(self): return u'%s %s' % (self.first_name, self.last_name) class Book(models.Model): title = models.CharField(max_length=100) authors = models.ManyToManyField(Author) publisher = models.ForeignKey(Publisher) publication_date = models.DateField() def __unicode__(self): return self.title </code></pre> <p>And this is on setting.py:</p> <pre><code>INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.messages', 'django.contrib.sessions', 'django.contrib.staticfiles', 'books', ] MIDDLEWARE_CLASSES = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', ] </code></pre> <p>And this is on admin.py:</p> <pre><code>from django.contrib import admin # Register your models here. from django.contrib import admin from books.models import Publisher, Author, Book admin.site.register(Publisher) admin.site.register(Author) admin.site.register(Book) </code></pre> <p>Thanks in advance...</p>
1
2016-09-03T16:04:38Z
39,309,384
<pre><code>Please correct your code like that: from django.contrib import admin # Register your models here. from django.contrib import admin from myproject.books.models import Publisher, Author, Book admin.site.register(Publisher) admin.site.register(Author) admin.site.register(Book) </code></pre>
-1
2016-09-03T17:07:52Z
[ "python", "django" ]
Cannot fetch choices for multiple select from in django
39,308,850
<p>I've got a problems with fetching choices for multiple select form. I'm trying to get choices from couchdb. It's successfully printed out into console it:<br> [[u'c6570a56173b637d66ba2a2e390271fe', u'Rambler'], [u'c6570a56173b637d66ba2a2e3902ad1f', u'BBC']]<br> , but it doesn't appear in template. <br> Here's my <strong>forms.py</strong> </p> <pre><code>sel = [] # FiltersForm is print out title, two select elements and an one required textinput's field class FiltersForm(forms.Form): title = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'A title'}), label='Title') item = forms.ChoiceField(widget=forms.Select(attrs={'class': 'selectpicker'}), required=False, label='If', choices=items) action = forms.ChoiceField(widget=forms.Select(attrs={'class': 'selectpicker'}), required=False, label='is', choices=actions) word = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'a word'})) link = forms.URLField(max_length=255, widget=forms.URLInput(attrs={'value': 'http://'})) source = forms.MultipleChoiceField(widget=forms.SelectMultiple(attrs={'class': 'selectpicker'}), choices=sel) def __init__(self, *args, **kwargs): request = kwargs.pop('request', None) response = request.db.view('subscriptions/source', key=str(request.user)).rows for item in response: sel.append([item.id, item.value['title']]) print sel super(FiltersForm, self).__init__(*args, **kwargs) </code></pre> <p><strong>Instance of form in views.py</strong> <br></p> <pre><code># Retrieving a FiltersForm form = FiltersForm(request.POST or None, request=request) </code></pre> <p>What's wrong with my form? </p>
0
2016-09-03T16:06:05Z
39,309,366
<p>You've defined a local variable called <code>sel</code> inside your <code>__init__</code> method, but that doesn't have anything to do with the variable with the same name at global level that you used to populate the form. You'd actually have to replace the choices with your new values inside that method:</p> <pre><code>self.fields['source'].choices = sel </code></pre>
0
2016-09-03T17:05:44Z
[ "python", "django", "couchdb" ]
How to move a python application to another folder in server without damaging it?
39,308,993
<p>I am running the celery flower application (<a href="https://github.com/mher/flower" rel="nofollow">https://github.com/mher/flower</a>) in my server. I installed this application in my Python LAMP server using the following command:</p> <pre><code>pip install flower </code></pre> <p>Now I want to do some modifications in the application such as functionality and layout. I want to do it by placing a copy of the application files in my <code>/var/www/html</code> public folder where all of my other applications are placed so as not to disturb the original application and not having to go into the system files like <code>../lib/......./dist/flower</code>. I have been developing applications in django previously and and in django, we can just put a copy of application files in our root applications folder and do modifications in it and the system reads the new copy of the files instead of original installation (pretty clean and clear method). I was hoping to have something like this for this application also? Any suggestions?</p>
0
2016-09-03T16:23:57Z
39,309,068
<p>Firstly, none of your application files should be in /var/www/html. That's for documents served directly by the webserver, not for code.</p> <p>To answer your question though, if you want to modify a project you should fork it on github, make your changes there, and install from the forked repo in pip.</p>
1
2016-09-03T16:31:32Z
[ "python", "linux", "django", "celery" ]
Need help fixing a game I made in Python
39,308,998
<p>I have been set a task to make a fruit machine game in python, however I am facing a small problem, it involves a variable. it is saying that I have referenced the variable before it's assignment, even though I have assigned it. It seems to be reading it as a local variable instead of a global variable. How do i fix this.</p> <p>This is the part causing the most trouble </p> <pre><code>Credit = 1 def main(): #the main program Credit = Credit - 0.20 print("Credit remaining = " + Credit) #tells the player the amount of credit remaining print("\n *** The Wheel Spins... *** \n") #Spinning the wheel print(input("\n (press enter to continue) \n")) </code></pre> <h1>error message</h1> <pre><code>line 19, in main Credit = Credit - 0.20 UnboundLocalError: local variable 'Credit' referenced before assignment </code></pre>
1
2016-09-03T16:24:44Z
39,309,050
<p>Anytime you want to write to a global variable in another function in python, you should let python know you want to use the global variable. Before the first line of main insert:</p> <pre><code>global Credit </code></pre>
0
2016-09-03T16:30:02Z
[ "python", "pygame", "global-variables", "local-variables" ]
Need help fixing a game I made in Python
39,308,998
<p>I have been set a task to make a fruit machine game in python, however I am facing a small problem, it involves a variable. it is saying that I have referenced the variable before it's assignment, even though I have assigned it. It seems to be reading it as a local variable instead of a global variable. How do i fix this.</p> <p>This is the part causing the most trouble </p> <pre><code>Credit = 1 def main(): #the main program Credit = Credit - 0.20 print("Credit remaining = " + Credit) #tells the player the amount of credit remaining print("\n *** The Wheel Spins... *** \n") #Spinning the wheel print(input("\n (press enter to continue) \n")) </code></pre> <h1>error message</h1> <pre><code>line 19, in main Credit = Credit - 0.20 UnboundLocalError: local variable 'Credit' referenced before assignment </code></pre>
1
2016-09-03T16:24:44Z
39,309,091
<p>The answer to <a href="http://stackoverflow.com/questions/10588317/python-function-global-variables">this question</a> might help you (copy-pasted below).</p> <blockquote> <p>If you want to simply access a global variable you just use its name. However to change its value you need to use the global keyword.</p> <p>E.g.</p> </blockquote> <pre><code>global someVar someVar = 55 </code></pre> <blockquote> <p>This would change the value of the global variable to 55. Otherwise it would just assign 55 to a local variable.</p> <p>The order of function definition listings doesn't matter (assuming they don't refer to each other in some way), the order they are called does.</p> </blockquote> <p>You both read <strong>and</strong> change the value of <code>Credit</code> you need to rewrite your code into something along the lines of:</p> <pre><code>def main(): #the main program(edited) global Credit Credit = Credit - 0.20 </code></pre>
2
2016-09-03T16:33:43Z
[ "python", "pygame", "global-variables", "local-variables" ]
Need help fixing a game I made in Python
39,308,998
<p>I have been set a task to make a fruit machine game in python, however I am facing a small problem, it involves a variable. it is saying that I have referenced the variable before it's assignment, even though I have assigned it. It seems to be reading it as a local variable instead of a global variable. How do i fix this.</p> <p>This is the part causing the most trouble </p> <pre><code>Credit = 1 def main(): #the main program Credit = Credit - 0.20 print("Credit remaining = " + Credit) #tells the player the amount of credit remaining print("\n *** The Wheel Spins... *** \n") #Spinning the wheel print(input("\n (press enter to continue) \n")) </code></pre> <h1>error message</h1> <pre><code>line 19, in main Credit = Credit - 0.20 UnboundLocalError: local variable 'Credit' referenced before assignment </code></pre>
1
2016-09-03T16:24:44Z
39,309,288
<p>You don't declared your variable . A variable that declared outside the function don't work into function . To use that variable you have to make the credit in this case as global variable. And then everything may become fine . All the best .</p> <pre><code>x = something #declearing a local variable def something(): global x # setting local x variable as global variable, so x can be use into as well as outside of the function print x #or do something u like . </code></pre>
0
2016-09-03T16:56:05Z
[ "python", "pygame", "global-variables", "local-variables" ]