title
stringlengths
12
150
question_id
int64
469
40.1M
question_score
int64
2
5.52k
question_date
stringdate
2008-08-02 15:11:16
2016-10-18 06:16:31
answer_id
int64
536
40.1M
answer_score
int64
7
8.38k
answer_date
stringdate
2008-08-02 18:49:07
2016-10-18 06:19:33
tags
listlengths
1
5
question_body_md
stringlengths
15
30.2k
answer_body_md
stringlengths
11
27.8k
Python: Every possible letter combination
31,914,097
3
2015-08-10T07:42:04Z
31,914,167
9
2015-08-10T07:45:47Z
[ "python" ]
What's the most efficient way at producing every possible letter combination of the alphabet? E.g. a,b,c,d,e...z,aa,ab,ac,ad,ae... ect I've written a code that successfully produces this result but I feel like it's too inefficient at producing the desired result. Any ideas? I've also tried to explain what i've done ``` #import module time import time #set starting variable "gen", make gen list. gen ='' gen = list(gen) #expermintal alphabet, not actually used alpha ='abcdefghijklmnopqrstuvwxyz' alpha = list(alpha) #Approx. on time taken to complete x letters useless_value = raw_input("Press Enter to continue...") print "How many letters would you like to start at?" useless_value = input("> ") gen = gen*useless_value #start time for function start_time= time.time() try: gen[-1] except IndexError: print "INVALID LETTER RANGE" print "DEFAULT LETTERS USED (1)" gen = 'a' gen = list(gen) #function loop (will never break) x=1 while True: #print raw string of gen print "".join(gen) #since infinite loop within same function, variables have to be reset #thus oh = 0 is reseting for later use oh = 0 #change a to b, b to c... ect. Will only make one change if gen[-1] =='a': gen[-1] ='b' elif gen[-1] =='b': gen[-1] ='c' elif gen[-1] =='c': gen[-1] ='d' elif gen[-1] =='d': gen[-1] ='e' elif gen[-1] =='e': gen[-1] ='f' elif gen[-1] =='f': gen[-1] ='g' elif gen[-1] =='g': gen[-1] ='h' elif gen[-1] =='h': gen[-1] ='i' elif gen[-1] =='i': gen[-1] ='j' elif gen[-1] =='j': gen[-1] ='k' elif gen[-1] =='k': gen[-1] ='l' elif gen[-1] =='l': gen[-1] ='m' elif gen[-1] =='m': gen[-1] ='n' elif gen[-1] =='n': gen[-1] ='o' elif gen[-1] =='o': gen[-1] ='p' elif gen[-1] =='p': gen[-1] ='q' elif gen[-1] =='q': gen[-1] ='r' elif gen[-1] =='r': gen[-1] ='s' elif gen[-1] =='s': gen[-1] ='t' elif gen[-1] =='t': gen[-1] ='u' elif gen[-1] =='u': gen[-1] ='v' elif gen[-1] =='v': gen[-1] ='w' elif gen[-1] =='w': gen[-1] ='x' elif gen[-1] =='x': gen[-1] ='y' #if 'y' changes to 'z'. variable 'oh' is set to '1'. # This is so it doesn't enter unwanted equations elif gen[-1] =='y': gen[-1] ='z' oh = 1 #if last string = 'z' #Checks max length of gen through [-1,-2].. ect if gen[-1] =='z': #reset s s = 0 x=1 while True: try: s except NameError: s = -1 s = s-1 try: gen[s] except IndexError: s = s+1 break #s = the amount that gen cannot be #Therefore s+1 == max #resets values because of loop d= 0 q= 0 #this infinite loop checks the string to see if all string values = 'z' #if it does it will change all values to 'a' then add 'a' x=1 while True: #useless piece of code #1 try: d except NameError: d = 0 #useful d = d-1 try: gen[d] except IndexError: break #if d value == 'z' it will continue, otherwise break from loop if gen[d] =='z': #if the max == the d value that means all values have been checked #and = 'z'. Otherwise it would've already broken the loop if s == d: x=1 while True: #if oh == 1 which was set from y changing to z # it will not continue #this is so that if 'zy' changes to 'zz' in the first #loop it will not change to 'aaa' while still in the loop # this is so it prints 'zz' and doesn't skip this #This is important to assure all possible combinations are printed if oh == 1: break else: pass #useless q already set to 0 try: q except NameError: q = 0 #sets individually all values of 'z' to 'a' q= q-1 try: gen[q] ='a' #then when q cannot exist, adds an 'a' except IndexError: gen = gen + ['a'] #sets oh = 1, just in case. most likely useless again oh = 1 #prints time taken to complete amount of letters print "Completed", ((len(gen))-1), "letters in", ((time.time() - start_time) /60), "minutes." break else: continue else: break #if the last value = 'z' it will find the next non 'z' value and make all #values after it = 'a'. e.g. you have abczezzz # it will check find the 'e' and change that 'e' to a 'f' # then it will change all the z's after it to a's # so final would be - abczfaaa m = -1 if gen[-1] =='z': x=1 while True: if oh == 1: break else: pass m = m -1 if gen[m] =='a': gen[m] ='b' gen[(m+1):] = ('a')*(-(m+1)) break elif gen[m] =='b': gen[m] ='c' gen[(m+1):] = ('a')*(-(m+1)) break elif gen[m] =='c': gen[m] ='d' gen[(m+1):] = ('a')*(-(m+1)) break elif gen[m] =='d': gen[m] ='e' gen[(m+1):] = ('a')*(-(m+1)) break elif gen[m] =='e': gen[m] ='f' gen[(m+1):] = ('a')*(-(m+1)) break elif gen[m] =='f': gen[m] ='g' gen[(m+1):] = ('a')*(-(m+1)) break elif gen[m] =='g': gen[m] ='h' gen[(m+1):] = ('a')*(-(m+1)) break elif gen[m] =='h': gen[m] ='i' gen[(m+1):] = ('a')*(-(m+1)) break elif gen[m] =='i': gen[m] ='j' gen[(m+1):] = ('a')*(-(m+1)) break elif gen[m] =='j': gen[m] ='k' gen[(m+1):] = ('a')*(-(m+1)) break elif gen[m] =='k': gen[m] ='l' gen[(m+1):] = ('a')*(-(m+1)) break elif gen[m] =='l': gen[m] ='m' gen[(m+1):] = ('a')*(-(m+1)) break elif gen[m] =='m': gen[m] ='n' gen[(m+1):] = ('a')*(-(m+1)) break elif gen[m] =='n': gen[m] ='o' gen[(m+1):] = ('a')*(-(m+1)) break elif gen[m] =='o': gen[m] ='p' gen[(m+1):] = ('a')*(-(m+1)) break elif gen[m] =='p': gen[m] ='q' gen[(m+1):] = ('a')*(-(m+1)) break elif gen[m] =='q': gen[m] ='r' gen[(m+1):] = ('a')*(-(m+1)) break elif gen[m] =='r': gen[m] ='s' gen[(m+1):] = ('a')*(-(m+1)) break elif gen[m] =='s': gen[m] ='t' gen[(m+1):] = ('a')*(-(m+1)) break elif gen[m] =='t': gen[m] ='u' gen[(m+1):] = ('a')*(-(m+1)) break elif gen[m] =='u': gen[m] ='v' gen[(m+1):] = ('a')*(-(m+1)) break elif gen[m] =='v': gen[m] ='w' gen[(m+1):] = ('a')*(-(m+1)) break elif gen[m] =='w': gen[m] ='x' gen[(m+1):] = ('a')*(-(m+1)) break elif gen[m] =='x': gen[m] ='y' gen[(m+1):] = ('a')*(-(m+1)) break elif gen[m] =='y': gen[m] ='z' gen[(m+1):] = ('a')*(-(m+1)) break elif gen[m] =='z': continue ```
Use [`itertools.product()`](https://docs.python.org/2/library/itertools.html#itertools.product) to create combinations of letters: ``` from string import ascii_lowercase from itertools import product for length in range(minimum_length, maximum_length + 1): for combo in product(ascii_lowercase, repeat=length): print ''.join(combo) ``` Take into account that the number of combinations produced grows exponentially with the `length` parameter. Demo: ``` >>> minimum_length, maximum_length = 1, 2 >>> for length in range(minimum_length, maximum_length + 1): ... for combo in product(ascii_lowercase, repeat=length): ... print ''.join(combo) ... a b c d e f g h i j k l m n o p q r s t u v w x y z aa ab ac ad ae af ag ah ai aj ak al am an ao ap aq ar as at au av aw ax ay az ba bb bc bd be bf bg bh bi bj bk bl bm bn bo bp bq br bs bt bu bv bw bx by bz ca cb cc cd ce cf cg ch ci cj ck cl cm cn co cp cq cr cs ct cu cv cw cx cy cz da db dc dd de df dg dh di dj dk dl dm dn do dp dq dr ds dt du dv dw dx dy dz ea eb ec ed ee ef eg eh ei ej ek el em en eo ep eq er es et eu ev ew ex ey ez fa fb fc fd fe ff fg fh fi fj fk fl fm fn fo fp fq fr fs ft fu fv fw fx fy fz ga gb gc gd ge gf gg gh gi gj gk gl gm gn go gp gq gr gs gt gu gv gw gx gy gz ha hb hc hd he hf hg hh hi hj hk hl hm hn ho hp hq hr hs ht hu hv hw hx hy hz ia ib ic id ie if ig ih ii ij ik il im in io ip iq ir is it iu iv iw ix iy iz ja jb jc jd je jf jg jh ji jj jk jl jm jn jo jp jq jr js jt ju jv jw jx jy jz ka kb kc kd ke kf kg kh ki kj kk kl km kn ko kp kq kr ks kt ku kv kw kx ky kz la lb lc ld le lf lg lh li lj lk ll lm ln lo lp lq lr ls lt lu lv lw lx ly lz ma mb mc md me mf mg mh mi mj mk ml mm mn mo mp mq mr ms mt mu mv mw mx my mz na nb nc nd ne nf ng nh ni nj nk nl nm nn no np nq nr ns nt nu nv nw nx ny nz oa ob oc od oe of og oh oi oj ok ol om on oo op oq or os ot ou ov ow ox oy oz pa pb pc pd pe pf pg ph pi pj pk pl pm pn po pp pq pr ps pt pu pv pw px py pz qa qb qc qd qe qf qg qh qi qj qk ql qm qn qo qp qq qr qs qt qu qv qw qx qy qz ra rb rc rd re rf rg rh ri rj rk rl rm rn ro rp rq rr rs rt ru rv rw rx ry rz sa sb sc sd se sf sg sh si sj sk sl sm sn so sp sq sr ss st su sv sw sx sy sz ta tb tc td te tf tg th ti tj tk tl tm tn to tp tq tr ts tt tu tv tw tx ty tz ua ub uc ud ue uf ug uh ui uj uk ul um un uo up uq ur us ut uu uv uw ux uy uz va vb vc vd ve vf vg vh vi vj vk vl vm vn vo vp vq vr vs vt vu vv vw vx vy vz wa wb wc wd we wf wg wh wi wj wk wl wm wn wo wp wq wr ws wt wu wv ww wx wy wz xa xb xc xd xe xf xg xh xi xj xk xl xm xn xo xp xq xr xs xt xu xv xw xx xy xz ya yb yc yd ye yf yg yh yi yj yk yl ym yn yo yp yq yr ys yt yu yv yw yx yy yz za zb zc zd ze zf zg zh zi zj zk zl zm zn zo zp zq zr zs zt zu zv zw zx zy zz ```
Practical use of tuple as a singleton
31,915,428
4
2015-08-10T08:58:43Z
31,915,562
7
2015-08-10T09:05:05Z
[ "python", "tuples" ]
In the documentation on [data models](https://docs.python.org/2/reference/datamodel.html#the-standard-type-hierarchy) it mentions the possibility to use a single item tuple as a singleton, due to it's immutability. > **Tuples** > > A tuple of one item (a ‘singleton’) can be formed by affixing a comma > to an expression... As far as I understand it in Python, a singleton functions similarly to a constant. It is a fixed value that maintains the same memory address so that you can test either equality or identity. For instance, `None`, `True` and `False` are all builtin singletons. However using a tuple defined this way seems impractical for awkward syntax, considering this kind of usage: ``` HELLO_WORLD = ("Hello world",) print HELLO_WORLD > ('Hello world',) print HELLO_WORLD[0] > Hello world ``` Not to mention, it only functions as a singleton if you remember to index it. ``` HELLO_WORLD[0] = "Goodbye world" Traceback (most recent call last): File "<pyshell#3>", line 1, in <module> HELLO_WORLD[0] = "Goodbye world" TypeError: 'str' object does not support item assignment ``` Meaning that you could easily do this: ``` HELLO_WORLD = "Goodbye world" print HELLO_WORLD > Goodbye world ``` Given these limitations, is there any point to this singleton implementation? The only advantage I see is that it's simple to create. Other approaches I've seen have been more complicated approaches (using classes etc.) but is there some other use for this I'm not thinking of?
I don't think this is useful for implementing singletons at all, it doesn't add anything: the tuple can still be overwritten by a new single-element tuple. Anyway, in your example your value is a string, which is already immutable itself. But I think the line of documentation you refer to ("A tuple of one item (a ‘singleton’)"), doesn't refer to the *singleton pattern* at all, but rather to the mathematical usage of the word, see [Wikipedia on Singleton (mathematics)](https://en.wikipedia.org/wiki/Singleton_%28mathematics%29) > The term is also used for a 1-tuple (a sequence with one element).
Concatenate two lists side by side
31,915,812
3
2015-08-10T09:17:06Z
31,915,845
8
2015-08-10T09:18:44Z
[ "python", "list" ]
I am looking for the shortest way of doing the following (one line solution) ``` a = ["a", "b", "c"] b = ["w", "e", "r"] ``` I want the following output: ``` q = ["a w", "b e", "c r"] ``` Of course this can be achieved by applying a for loop. But I am wondering if there is a smart solution to this?
You can use `str.join()` and [`zip()`](https://docs.python.org/2/library/functions.html#zip) , Example - ``` q = [' '.join(x) for x in zip(a,b)] ``` Example/Demo - ``` >>> a = ["a", "b", "c"] >>> b = ["w", "e", "r"] >>> q = [' '.join(x) for x in zip(a,b)] >>> q ['a w', 'b e', 'c r'] ```
Can someone explain how the source code of staticmethod works in python
31,916,048
9
2015-08-10T09:28:36Z
31,916,107
9
2015-08-10T09:31:37Z
[ "python", "decorator", "static-methods", "python-internals" ]
First of all, I understand how, in general, a decorator work. And I know `@staticmethod` strips off the instance argument in the signature, making ``` class C(object): @staticmethod def foo(): print 'foo' C.foo //<function foo at 0x10efd4050> C().foo //<function foo at 0x10efd4050> ``` valid. However, I don't understand how the sourcec code of `staticmethod` make this happen. It seems to me that when wrapping method `foo` in `staticmethod`, an instance of `staticmethod` is instantiated, then *some magic* happens, making `C.foo()` legit. So.. what happen in those *magic*? what did `staticmethod` do? I'm aware the enormous topics on SO regarding `staticmethods` but none of them addresses my doubts. But maybe I didn't hit the magic keyword. If so, please kindly let me know. For whoever looking for `staticmethod` source code, please refer to <https://hg.python.org/cpython/file/c6880edaf6f3/Objects/funcobject.c>
A `staticmethod` object is a [*descriptor*](https://docs.python.org/2/howto/descriptor.html). The magic you are missing is that Python calls the `__get__` method when accessing the object as an attribute on a class or instance. So accessing the object as `C.foo` results in Python translating that to `C.__dict__['foo'].__get__(None, C)`, while `instance_of_C.foo` becomes `type(instace_of_C).__dict__['foo'].__get__(instance_of_C, type(instance_of_C))`. The `staticmethod` object is [defined in C code](https://hg.python.org/cpython/file/2.7/Objects/funcobject.c#l748), but an equivalent in Python would be: ``` class staticmethod(object): def __init__(self, callable): self.f = callable def __get__(self, obj, type=None): return self.f @property def __func__(self): return self.f ``` where `self.f` is the original wrapped function. All this is needed because functions are themselves descriptors too; it is the descriptor protocol that gives you method objects (see [python bound and unbound method object](http://stackoverflow.com/questions/13348031/python-bound-and-unbound-method-object) for more details). Since they too have a `__get__` method, without a `staticmethod` object wrapping the function, a `functionobj.__get__` call produces a method object instead, passing in a `self` argument. There is also a `classmethod`, which uses the second argument to `descriptor.__get__` to bind a function to the class, and then there are `property` objects, which translate binding into a function call directly. See [How does the @property decorator work?](http://stackoverflow.com/questions/17330160/how-does-the-property-decorator-work).
How do you translate strings to padded binary in python?
31,917,211
4
2015-08-10T10:28:34Z
31,917,271
12
2015-08-10T10:31:26Z
[ "python" ]
I have made a program that translates a text into binary code but its really messy. This is my code: ``` def converter(): print("message:") inputMsg = input() msg = '' for letter in inputMsg: if letter == 'a': msg = msg + '01100001' elif letter == 'b': msg = msg + '01100010' elif letter == 'c': msg = msg + '01100011' elif letter == 'd': msg = msg + '01100100' elif letter == 'e': msg = msg + '01100101' elif letter == 'f': msg = msg + '01100110' elif letter == 'g': msg = msg + '011000111' elif letter == 'h': msg = msg + '01101000' elif letter == 'i': msg = msg + '01101001' elif letter == 'j': msg = msg + '01101010' elif letter == 'k': msg = msg + '01101011' elif letter == 'l': msg = msg + '01101100' elif letter == 'm': msg = msg + '01101101' elif letter == 'n': msg = msg + '01101110' elif letter == 'o': msg = msg + '01101111' elif letter == 'p': msg = msg + '01110000' elif letter == 'q': msg = msg + '01110001' elif letter == 'r': msg = msg + '01100010' elif letter == 's': msg = msg + '01110011' elif letter == 't': msg = msg + '01110100' elif letter == 'u': msg = msg + '01110101' elif letter == 'v': msg = msg + '01110110' elif letter == 'w': msg = msg + '01110111' elif letter == 'x': msg = msg + '01111000' elif letter == 'y': msg = msg + '01111001' elif letter == 'z': msg = msg + '01111010' elif letter == 'A': msg = msg + '01000001' elif letter == 'B': msg = msg + '01000010' elif letter == 'C': msg = msg + '01000011' elif letter == 'D': msg = msg + '01000100' elif letter == 'E': msg = msg + '01000101' elif letter == 'F': msg = msg + '01000110' elif letter == 'G': msg = msg + '01000111' elif letter == 'H': msg = msg + '01001000' elif letter == 'I': msg = msg + '01001001' elif letter == 'J': msg = msg + '01001010' elif letter == 'K': msg = msg + '01001011' elif letter == 'L': msg = msg + '01001100' elif letter == 'M': msg = msg + '01001101' elif letter == 'N': msg = msg + '01001110' elif letter == 'O': msg = msg + '01001111' elif letter == 'P': msg = msg + '01010000' elif letter == 'Q': msg = msg + '01010001' elif letter == 'R': msg = msg + '01000010' elif letter == 'S': msg = msg + '01010011' elif letter == 'T': msg = msg + '01010100' elif letter == 'U': msg = msg + '01010101' elif letter == 'V': msg = msg + '01010110' elif letter == 'W': msg = msg + '01010111' elif letter == 'X': msg = msg + '01011000' elif letter == 'Y': msg = msg + '01011001' elif letter == 'Z': msg = msg + '01011010' elif letter == ' ': msg = msg + '00100000' print('\n',msg,'\n') print('do again? (y/n)') yn() def yn(): yn = input() if yn == 'y': converter() elif yn == 'n': pass else: yn() converter() ``` My output is OK but you see i have an if/else for every letter. Is there an other way to do it clean and a bit more efficient?
``` >>> st = "hello" >>> ' '.join(format(ord(x), '08b') for x in st) '01101000 01100101 01101100 01101100 01101111 ``` What happens here is that we loop over every character, `x`, in string `st`. On each of those items we run [`ord()`](https://docs.python.org/2/library/functions.html#ord), which converts the character `x` into a integer representing the Unicode code point, e.g. `'T' == 84`. This number we then [`.format`](https://docs.python.org/2/library/string.html#format-string-syntax) into (padded) binary. `08` here means that the number is to be formatted to be 8 digits long, padded by `0` from the left. `b` then indicates that it is to be in binary, or base 2. The number has to be padded or there would be no leading zeroes.
Why is string's startswith slower than in?
31,917,372
48
2015-08-10T10:35:51Z
31,917,646
35
2015-08-10T10:52:10Z
[ "python", "python-2.7", "cpython", "python-internals", "startswith" ]
Surprisingly, I find `startswith` is slower than `in`: ``` In [10]: s="ABCD"*10 In [11]: %timeit s.startswith("XYZ") 1000000 loops, best of 3: 307 ns per loop In [12]: %timeit "XYZ" in s 10000000 loops, best of 3: 81.7 ns per loop ``` As we all know, the `in` operation needs to search the whole string and `startswith` just needs to check the first few characters, so `startswith` should be more efficient. When `s` is big enough, `startswith` is faster: ``` In [13]: s="ABCD"*200 In [14]: %timeit s.startswith("XYZ") 1000000 loops, best of 3: 306 ns per loop In [15]: %timeit "XYZ" in s 1000000 loops, best of 3: 666 ns per loop ``` So it seems that calling `startswith` has some overhead which makes it slower when the string is small. And than I tried to figure out what's the overhead of the `startswith` call. First, I used an `f` variable to reduce the cost of the dot operation - as mentioned in this [answer](http://stackoverflow.com/a/13271125/552942) - here we can see `startswith` is still slower: ``` In [16]: f=s.startswith In [17]: %timeit f("XYZ") 1000000 loops, best of 3: 270 ns per loop ``` Further, I tested the cost of an empty function call: ``` In [18]: def func(a): pass In [19]: %timeit func("XYZ") 10000000 loops, best of 3: 106 ns per loop ``` Regardless of the cost of the dot operation and function call, the time of `startswith` is about (270-106)=164ns, but the `in` operation takes only 81.7ns. It seems there are still some overheads for `startswith`, what's that? Add the test result between `startswith` and `__contains__` as suggested by poke and lvc: ``` In [28]: %timeit s.startswith("XYZ") 1000000 loops, best of 3: 314 ns per loop In [29]: %timeit s.__contains__("XYZ") 1000000 loops, best of 3: 192 ns per loop ```
As already mentioned in the comments, if you use `s.__contains__("XYZ")` you get a result that is more similar to `s.startswith("XYZ")` because it needs to take the same route: Member lookup on the string object, followed by a function call. This is usually somewhat expensive (not enough that you should worry about of course). On the other hand, when you do `"XYZ" in s`, the parser interprets the operator and can short-cut the member access to the `__contains__` (or rather the implementation behind it, because `__contains__` itself is just one way to access the implementation). You can get an idea about this by looking at the bytecode: ``` >>> dis.dis('"XYZ" in s') 1 0 LOAD_CONST 0 ('XYZ') 3 LOAD_NAME 0 (s) 6 COMPARE_OP 6 (in) 9 RETURN_VALUE >>> dis.dis('s.__contains__("XYZ")') 1 0 LOAD_NAME 0 (s) 3 LOAD_ATTR 1 (__contains__) 6 LOAD_CONST 0 ('XYZ') 9 CALL_FUNCTION 1 (1 positional, 0 keyword pair) 12 RETURN_VALUE ``` So comparing `s.__contains__("XYZ")` with `s.startswith("XYZ")` will produce a more similar result, however for your example string `s`, the `startswith` will still be slower. To get to that, you could check the implementation of both. Interesting to see for the [contains implementation](https://hg.python.org/cpython/file/e39c4373b83f/Objects/unicodeobject.c#l10889) is that it is statically typed, and just assumes that the argument is a unicode object itself. So this is quite efficient. The [`startswith` implementation](https://hg.python.org/cpython/file/e39c4373b83f/Objects/unicodeobject.c#l13124) however is a “dynamic” Python method which requires the implementation to actually parse the arguments. `startswith` also supports a tuple as an argument, which makes the whole start-up of the method a bit slower: (shortened by me, with my comments): ``` static PyObject * unicode_startswith(PyObject *self, PyObject *args) { // argument parsing PyObject *subobj; PyObject *substring; Py_ssize_t start = 0; Py_ssize_t end = PY_SSIZE_T_MAX; int result; if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end)) return NULL; // tuple handling if (PyTuple_Check(subobj)) {} // unicode conversion substring = PyUnicode_FromObject(subobj); if (substring == NULL) {} // actual implementation result = tailmatch(self, substring, start, end, -1); Py_DECREF(substring); if (result == -1) return NULL; return PyBool_FromLong(result); } ``` This is likely a big reason why `startswith` is slower for strings for which a `contains` is fast because of its simplicity.
Boto3 to download all files from a S3 Bucket
31,918,960
12
2015-08-10T11:58:16Z
31,929,277
14
2015-08-10T21:13:18Z
[ "python", "amazon-s3", "boto3" ]
I'm using boto3 to get files from s3 bucket. I need a similar functionality like `aws s3 sync` My current code is ``` #!/usr/bin/python import boto3 s3=boto3.client('s3') list=s3.list_objects(Bucket='my_bucket_name')['Contents'] for key in list: s3.download_file('my_bucket_name', key['Key'], key['Key']) ``` This is working fine, as long as the bucket has only files. If a folder is present inside the bucket, its throwing an error ``` Traceback (most recent call last): File "./test", line 6, in <module> s3.download_file('my_bucket_name', key['Key'], key['Key']) File "/usr/local/lib/python2.7/dist-packages/boto3/s3/inject.py", line 58, in download_file extra_args=ExtraArgs, callback=Callback) File "/usr/local/lib/python2.7/dist-packages/boto3/s3/transfer.py", line 651, in download_file extra_args, callback) File "/usr/local/lib/python2.7/dist-packages/boto3/s3/transfer.py", line 666, in _download_file self._get_object(bucket, key, filename, extra_args, callback) File "/usr/local/lib/python2.7/dist-packages/boto3/s3/transfer.py", line 690, in _get_object extra_args, callback) File "/usr/local/lib/python2.7/dist-packages/boto3/s3/transfer.py", line 707, in _do_get_object with self._osutil.open(filename, 'wb') as f: File "/usr/local/lib/python2.7/dist-packages/boto3/s3/transfer.py", line 323, in open return open(filename, mode) IOError: [Errno 2] No such file or directory: 'my_folder/.8Df54234' ``` Is this a proper way to download a complete s3 bucket using boto3. How to download folders.
Amazon S3 does not have folders/directories. It is a **flat file structure**. To maintain the appearance of directories, **path names are stored as part of the object Key** (filename). For example: * `images/foo.jpg` In this case, they whole Key is `images/foo.jpg`, rather than just `foo.jpg`. I suspect that your problem is that `boto` is returning a file called `my_folder/.8Df54234` and is attempting to save it to the local filesystem. However, your local filesystem interprets the `my_folder/` portion as a directory name, and **that directory does not exist on your local filesystem**. You could either **truncate** the filename to only save the `.8Df54234` portion, or you would have to **create the necessary directories** before writing files. Note that it could be multi-level nested directories. An easier way would be to use the [**AWS Command-Line Interface (CLI)**](http://aws.amazon.com/cli/), which will do all this work for you, eg: ``` aws s3 cp --recursive s3://my_bucket_name local_folder ``` There's also a `sync` option that will only copy new and modified files.
Boto3 to download all files from a S3 Bucket
31,918,960
12
2015-08-10T11:58:16Z
33,350,380
18
2015-10-26T16:06:54Z
[ "python", "amazon-s3", "boto3" ]
I'm using boto3 to get files from s3 bucket. I need a similar functionality like `aws s3 sync` My current code is ``` #!/usr/bin/python import boto3 s3=boto3.client('s3') list=s3.list_objects(Bucket='my_bucket_name')['Contents'] for key in list: s3.download_file('my_bucket_name', key['Key'], key['Key']) ``` This is working fine, as long as the bucket has only files. If a folder is present inside the bucket, its throwing an error ``` Traceback (most recent call last): File "./test", line 6, in <module> s3.download_file('my_bucket_name', key['Key'], key['Key']) File "/usr/local/lib/python2.7/dist-packages/boto3/s3/inject.py", line 58, in download_file extra_args=ExtraArgs, callback=Callback) File "/usr/local/lib/python2.7/dist-packages/boto3/s3/transfer.py", line 651, in download_file extra_args, callback) File "/usr/local/lib/python2.7/dist-packages/boto3/s3/transfer.py", line 666, in _download_file self._get_object(bucket, key, filename, extra_args, callback) File "/usr/local/lib/python2.7/dist-packages/boto3/s3/transfer.py", line 690, in _get_object extra_args, callback) File "/usr/local/lib/python2.7/dist-packages/boto3/s3/transfer.py", line 707, in _do_get_object with self._osutil.open(filename, 'wb') as f: File "/usr/local/lib/python2.7/dist-packages/boto3/s3/transfer.py", line 323, in open return open(filename, mode) IOError: [Errno 2] No such file or directory: 'my_folder/.8Df54234' ``` Is this a proper way to download a complete s3 bucket using boto3. How to download folders.
I got the same needs and create the following function that download recursively the files. The directories are created locally only if they contain files. ``` import boto3 import os def download_dir(client, resource, dist, local='/tmp', bucket='your_bucket'): paginator = client.get_paginator('list_objects') for result in paginator.paginate(Bucket=bucket, Delimiter='/', Prefix=dist): if result.get('CommonPrefixes') is not None: for subdir in result.get('CommonPrefixes'): download_dir(client, resource, subdir.get('Prefix'), local) if result.get('Contents') is not None: for file in result.get('Contents'): if not os.path.exists(os.path.dirname(local + os.sep + file.get('Key'))): os.makedirs(os.path.dirname(local + os.sep + file.get('Key'))) resource.meta.client.download_file(bucket, file.get('Key'), local + os.sep + file.get('Key')) ``` The function is called that way: ``` def _start(): client = boto3.client('s3') resource = boto3.resource('s3') download_dir(client, resource, 'clientconf/', '/tmp') ```
Sum up over np.array or np.float
31,921,290
5
2015-08-10T13:47:15Z
31,921,406
9
2015-08-10T13:52:23Z
[ "python", "arrays", "numpy", "types" ]
We have a numpy-based algorithm that is supposed to handle data of different type. ``` def my_fancy_algo(a): b = np.sum(a, axis=1) # Do something b return b ``` If we pass `a=np.array[1.0, 2.0, 3.0]` then `b` evaluates to `[6.0]`. If we pass `a=6.0` then we get ``` *** ValueError: 'axis' entry is out of bounds ``` The desired behavior would be that we get same return value `6.0` not (`[6.0]`) for both inputs. What is the correct pythonic and safe way to handle this? `type`? `shape`?
Your example array actually gives the same problem as a scalar: ``` >>> a = np.array([1.0,2.0,3.0]) >>> np.sum(a, axis=1) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python3.4/site-packages/numpy/core/fromnumeric.py", line 1724, in sum out=out, keepdims=keepdims) File "/usr/lib/python3.4/site-packages/numpy/core/_methods.py", line 32, in _sum return umr_sum(a, axis, dtype, out, keepdims) ValueError: 'axis' entry is out of bounds ``` The good news is that there's a numpy function exactly for ensuring making numpy calls with `axis=1` will work - it's called [`np.atleast_2d`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.atleast_2d.html): ``` >>> np.sum(np.atleast_2d(a), axis=1) array([ 6.]) >>> np.sum(np.atleast_2d(6.0), axis=1) array([ 6.]) ``` But since you apparently want a scalar answer, you could instead just drop the `axis` argument entirely: ``` >>> np.sum(a) 6.0 >>> np.sum(6.0) 6.0 ```
Creating a live plot of CSV data with Matplotlib
31,922,016
2
2015-08-10T14:18:38Z
31,943,177
7
2015-08-11T13:29:22Z
[ "python", "csv", "python-3.x", "matplotlib" ]
I am trying to use Matplotlib to visualize some measurements. The measurements typically last about 24hrs and will include ~30k lines of data in the csv. I've been struggling mostly with getting my plots to actually animate. I can execute the code and it will display a snapshot up to the current point in time but nothing else. When I try to autoscale it, nothing plots and it just defaults to a view of -.6 to +.6 on both axes. Am I supposed to call plt.draw() for this to work? This is what I have so far: ``` import numpy as np import datetime as dt import matplotlib import matplotlib.pyplot as plt from matplotlib import animation FMT = '%Y-%m-%d %H:%M:%S.%f' data = np.genfromtxt('sampleData.csv', delimiter=',', skip_header=5, names=['x', 'y', 'z', 'w'], dtype=['object', 'int8', 'int8', 'float']) mytime = [dt.datetime.strptime(i.decode('ascii'), FMT) for i in data['x']] thickness = data['w'] fig = plt.figure() axes = fig.add_subplot(111) line, = axes.plot([], [], '.') plt.show(block=False) def init(): line.set_data([],[]) return line, fig.canvas.draw() def animate(i): xdata = mytime[:i] ydata = thickness[:i] line.set_data(xdata, ydata) plt.draw() axes.relim() axes.autoscale(True,'both',True) axes.autoscale_view(True,True,True) return line, anim = animation.FuncAnimation(fig, animate, init_func=init, interval=0, blit=True) plt.show() ``` This is a sample line of data from the CSV: ``` 2013-09-25 14:51:15.329091,1,0,439.80,,,,0,0, ```
You have two issues. One is because you're effectively drawing things twice, the second is purely human psychology (the plot appears to slow over time because you're adding one point to 10000 vs adding one point to 10 or 100). --- Let's discuss the double-draw first: The `FuncAnimation` will draw things for you, but by telling it to use blitting, it's only updating the inside of the axes and not the ticks, etc. Therefore, you need to manually call `draw`, but the animation will be calling `draw_artist`, as well. You should be able to get at least a 2x speedup by removing `blit=True` and `plt.draw()` Furthermore, by setting `interval=0`, you're forcing it to draw constantly, which will effectively force things to lock up. Set the interval to something more reasonable, e.g. `25` (the interval is in milliseconds. "25" is 40 fps.). For example, this is very smooth for me: ``` import numpy as np import matplotlib.pyplot as plt from matplotlib import animation y = np.random.normal(0, 1, 10000).cumsum(axis=0) x = np.arange(y.size) fig, ax = plt.subplots() line, = ax.plot([], [], '.') ax.margins(0.05) def init(): line.set_data(x[:2],y[:2]) return line, def animate(i): i = min(i, x.size) xdata = x[:i] ydata = y[:i] line.set_data(xdata, ydata) ax.relim() ax.autoscale() return line, anim = animation.FuncAnimation(fig, animate, init_func=init, interval=25) plt.show() ``` I've also added `ax.margins(0.05)` to avoid the axes limits snapping to the next nearest "even" number and giving a "jerky" appearance. --- However, because you're progressively plotting more and more data, the rate of change will *appear to slow*, simply because less of the data appears to be changing over time. Adding one point at the end of 10000 is hardly noticeable, but adding one point at the end of 10 is *very* noticable. Therefore, the plot looks *much* more "exciting" at the beginning than at the end even though it's updating at the same rate. This has nothing whatsoever to do with matplotlib, and is a consequence of the way you're choosing to animate your data. To get around that, you might consider moving a "sliding window" through your data and plotting a constant number of points at a time. As an example: ``` import numpy as np import matplotlib.pyplot as plt from matplotlib import animation y = np.random.normal(0, 1, 1000000).cumsum(axis=0) x = np.arange(y.size) + 1 fig, ax = plt.subplots() line, = ax.plot([], [], 'k-') ax.margins(0.05) def init(): line.set_data(x[:2],y[:2]) return line, def animate(i): win = 300 imin = min(max(0, i - win), x.size - win) xdata = x[imin:i] ydata = y[imin:i] line.set_data(xdata, ydata) ax.relim() ax.autoscale() return line, anim = animation.FuncAnimation(fig, animate, init_func=init, interval=25) plt.show() ```
How to convert dictionary values to int in Python?
31,923,552
12
2015-08-10T15:30:34Z
31,923,593
19
2015-08-10T15:32:24Z
[ "python", "sorting", "dictionary" ]
I have a program that returns a set of domains with ranks like so: ``` ranks = [ {'url': 'example.com', 'rank': '11,279'}, {'url': 'facebook.com', 'rank': '2'}, {'url': 'google.com', 'rank': '1'} ] ``` I'm trying to sort them by ascending rank with `sorted`: ``` results = sorted(ranks,key=itemgetter("rank")) ``` However, since the values of "rank" are strings, then it sorts them alphanumerically instead of by ascending value: ``` 1. google.com: 1 2. example.com: 11,279 3. facebook.com: 2 ``` I need to convert the values of only the "rank" key to integers so that they'll sort correctly. Any ideas?
You are almost there. You need to convert the picked values to integers after replacing `,`, like this ``` results = sorted(ranks, key=lambda x: int(x["rank"].replace(",", ""))) ``` For example, ``` >>> ranks = [ ... {'url': 'example.com', 'rank': '11,279'}, ... {'url': 'facebook.com', 'rank': '2'}, ... {'url': 'google.com', 'rank': '1'} ... ] >>> from pprint import pprint >>> pprint(sorted(ranks, key=lambda x: int(x["rank"].replace(",", "")))) [{'rank': '1', 'url': 'google.com'}, {'rank': '2', 'url': 'facebook.com'}, {'rank': '11,279', 'url': 'example.com'}] ``` **Note:** I just used `pprint` function to pretty print the result. Here, `x` will be the current object for which the `key` value being determined. We get the value of `rank` attribute from it, replace `,` with empty string and then converted that to a number with `int`. --- If you don't want to replace `,` and handle it properly, then you can use [`locale` module's `atoi` function](https://docs.python.org/3/library/locale.html#locale.atoi), like this ``` >>> import locale >>> pprint(sorted(ranks, key=lambda x: int(locale.atoi(x["rank"])))) [{'rank': '1', 'url': 'google.com'}, {'rank': '2', 'url': 'facebook.com'}, {'rank': '11,279', 'url': 'example.com'}] ```
Importance of apps orders in INSTALLED_APPS
31,925,458
7
2015-08-10T17:16:52Z
31,925,587
8
2015-08-10T17:24:08Z
[ "python", "django" ]
Is the order of apps in `INSTALLED_APPS` is important? I ask it because I have `settings` folder with two `settings` files: `base.py` and `production.py` and I put all my settings in `base.py` and then in `production.py` write ``` `from base import *` ``` and overwrite some settings. Also in my `base.py` I make `INSTALLED_APPS` to be a list, not a tuple. Because I want to remove some apps for `production` settings. In `production.py` I want to write: ``` NOT_USED_APPS = ['debut_toolbar', 'other_odd_app',] INSTALLED_APPS = list(set(INSTALLED_APPS) - set(NOT_USED_APPS)) ``` In this case, the order of apps in `INSTALLED_APPS` is not like in `base.py`
**Yes, the order is quite important.** From Django official docs on [`INSTALLED_APPS` settings](https://docs.djangoproject.com/en/1.8/ref/settings/#installed-apps): > When several applications provide different versions of the same > resource (template, static file, management command, translation), the > application listed first in `INSTALLED_APPS` has precedence. **Example-1 Templates:** **[`django.template.loaders.app_directories.Loader`](https://docs.djangoproject.com/en/1.8/ref/templates/api/#django.template.loaders.app_directories.Loader)** If this template loader is enabled in your `DjangoTemplates` backend in the `TEMPLATES` setting or if you have passed it as a loaders argument to Engine, then it loads templates from Django apps on the filesystem. For each app in `INSTALLED_APPS`, the loader looks for a templates subdirectory. If the directory exists, Django will look for templates in there. Lets say in my project, i have defined `INSTALLED_APPS` as: ``` INSTALLED_APPS = ('myproject.app1', 'myproject.app2') ``` Now, i want to get the template `some_template.html`. Then `get_template('some_template.html')` will look for `some_template.html` in these directories, **in this order:** ``` /path/to/myproject/app1/templates/ # checks here first /path/to/myproject/app2/templates/ # Then checks here ``` **It will then use the one which it finds first.** Quoting from that [section](https://docs.djangoproject.com/en/1.8/ref/templates/api/#django.template.loaders.app_directories.Loader): > The order of `INSTALLED_APPS` is significant! **Example-2: Translations** Django applies the following algorithm for discovering translations: 1. The directories listed in `LOCALE_PATHS` have the highest precedence, with the ones appearing first having higher precedence than the ones appearing later. 2. Then, it looks for and uses if it exists a `locale` directory in each of the installed apps listed in `INSTALLED_APPS`. **The ones appearing first have higher precedence than the ones appearing later.** 3. Finally, the Django-provided base translation in `django/conf/locale` is used as a fallback. We can see that order is important here also. **Example-3 Management Commands:** From Django 1.7 release notes on [management commands and order of `INSTALLED_APPS`](https://docs.djangoproject.com/en/1.8/releases/1.7/#management-commands-and-order-of-installed-apps): > When several applications provide management commands with the same > name, Django loads the command from the application that comes first > in `INSTALLED_APPS`. Previous versions loaded the command from the > application that came last. > > This brings discovery of management commands in line with other parts > of Django that rely on the order of `INSTALLED_APPS`, such as static > files, templates, and translations.
Python Check if String split succeeded
31,925,964
5
2015-08-10T17:49:19Z
31,926,007
7
2015-08-10T17:51:39Z
[ "python", "string" ]
I am splitting a string `"name:john"` and want to check whether the split happened or not. What is the right way doing that check? **A quick solution:** (but maybe overkill) ``` name = "name:john" splitted = name.split(":") if len(splitted) > 1: print "split" ``` Is there a more elaborate way of doing the check?
You can also choose the [EAFP](https://docs.python.org/2/glossary.html#term-eafp) approach: split, unpack and handle `ValueError`: ``` try: key, value = name.split(":") except ValueError: print "Failure" else: print "Success" ```
next_is_valid() doesn't exist in flask-login?
31,927,227
10
2015-08-10T19:06:32Z
31,967,035
8
2015-08-12T13:44:07Z
[ "python", "flask", "flask-login" ]
[Flask-login doc](https://flask-login.readthedocs.org/en/latest/) says we should validate next using `next_is_valid()`, but I can't find any such method: > Warning: You MUST validate the value of the next parameter. If you do not, your application will be vulnerable to open redirects. ``` @app.route('/login', methods=['GET', 'POST']) def login(): # Here we use a class of some kind to represent and validate our # client-side form data. For example, WTForms is a library that will # handle this for us. form = LoginForm() if form.validate_on_submit(): # Login and validate the user. login_user(user) flask.flash('Logged in successfully.') next = flask.request.args.get('next') if not next_is_valid(next): return flask.abort(400) return flask.redirect(next or flask.url_for('index')) return flask.render_template('login.html', form=form) ``` Running this I get the error: ``` NameError: global name 'next_is_valid' is not defined ``` And if I do: ``` from flask.ext.login import next_is_valid >> ImportError: cannot import name next_is_valid ``` Where is the `next_is_valid()` function, and if it doesn't exist, how do I validate the `next` parameter?
It doesn't say you must validate `next` with `next_is_valid`, only that > You MUST validate the value of the next parameter. **`next_is_valid` is just an example function.** You must determine if `next` is valid based on your own criteria. `next` is the url to redirect to on a successful login. If you have any permissions to apply or restrictions on your site this is where you would want to make sure they are enforced. For example, a user could attempt to login with the request url `http://example.com/login?next=admin/delete/all/users`. If the login attempt was successful and the admin permission was not checked within your login function or on the endpoint itself, well, bad things could happen. It all depends on how you structure your application and control access to individual endpoints.
How to get a list of all indexes in python-elasticsearch
31,928,506
3
2015-08-10T20:26:17Z
31,928,663
8
2015-08-10T20:36:04Z
[ "python", "elasticsearch" ]
How would I get a list of the names of an index in Python? Here is what I have so far: ``` >>> es=e.es >>> es <Elasticsearch([{'host': '14555f777d8097.us-east-1.aws.found.io', 'port': 9200}])> >>> es.indices <elasticsearch.client.indices.IndicesClient object at 0x10de86790> # how to get a list of all indexes in this cluster? ```
Here is one way to do it with the [`get_aliases()`](https://elasticsearch-py.readthedocs.org/en/master/api.html?highlight=indicesclient#elasticsearch.client.IndicesClient.get_alias) method: ``` >>> indices=es.indices.get_aliases().keys() >>> sorted(indices) [u'avails', u'hey', u'kibana-int'] ```
How to install Rodeo IDE in Anaconda python distribution?
31,935,714
6
2015-08-11T07:28:59Z
37,713,789
7
2016-06-08T22:09:12Z
[ "python", "python-3.x", "ipython", "anaconda", "rodeo" ]
I have a 64bit anaconda python distribution version 2.3 with python 3.4.3 installed on windows 7 machine. I searched about installing rodeo on top of this but seems like "conda install rodeo" wont work, so i did "pip install rodeo". ``` "pip install rodeo" gave me the following message "Successfully installed rodeo". ``` But when i type rodeo in cmd to start rodeo it is giving an error saying ``` "failed to create process." ``` & i am not able to start rodeo. Please advise. Thanks
# Updated Answer (as of 2016-6-8) Rodeo has been undergoing a significant re-write since the latest major release, **v1.3** which is the [currently downloadable version](https://www.yhat.com/products/rodeo) on yhat's website. I recommend checking out the latest release, **v2.0**, downloadable from the [Rodeo project page on github](https://github.com/yhat/rodeo). --- Here's how I set up Anaconda and Rodeo 1. Install the latest version of [Anaconda](https://www.continuum.io/downloads) 2. [Create a fresh virtual environment](http://conda.pydata.org/docs/using/envs.html#create-an-environment) which includes jupyter. `conda create --name datasci jupyter` 3. Install the [latest version of Rodeo](https://github.com/yhat/rodeo) 4. Open Rodeo and set the Python Path to your fresh anaconda virtual environment. (In my case //anaconda/envs/datasci/bin/python) [![enter image description here](http://i.stack.imgur.com/mkff5.png)](http://i.stack.imgur.com/mkff5.png) If you're not sure what path to set, 1. Open Terminal 2. Activate your virtual environment `source activate datasci` 3. Run `which python` More details in the [Rodeo docs](http://rodeo.yhat.com/docs/). And keep checking github for version updates as they're coming almost daily at this point.
Plot a (polar) color wheel based on a colormap using Python/Matplotlib
31,940,285
11
2015-08-11T11:14:45Z
31,942,626
11
2015-08-11T13:04:55Z
[ "python", "matplotlib", "plot", "colors", "scipy" ]
I am trying to create a color wheel in Python, preferably using Matplotlib. The following works OK: ``` import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt xval = np.arange(0, 2*pi, 0.01) yval = np.ones_like(xval) colormap = plt.get_cmap('hsv') norm = mpl.colors.Normalize(0.0, 2*np.pi) ax = plt.subplot(1, 1, 1, polar=True) ax.scatter(xval, yval, c=xval, s=300, cmap=colormap, norm=norm, linewidths=0) ax.set_yticks([]) ``` [![Own attempt at creating a color wheel](http://i.stack.imgur.com/QQIch.png)](http://i.stack.imgur.com/QQIch.png) However, this attempt has two serious drawbacks. First, when saving the resulting figure as a vector ([figure\_1.svg](https://dl.dropboxusercontent.com/u/4023322/figure_1.svg)), the color wheel consists (as expected) of 621 different shapes, corresponding to the different (x,y) values being plotted. Although the result looks like a circle, it isn't really. I would greatly prefer to use an actual circle, defined by a few path points and Bezier curves between them, as in e.g. [`matplotlib.patches.Circle`](http://matplotlib.org/api/patches_api.html#matplotlib.patches.Circle). This seems to me the 'proper' way of doing it, and the result would look nicer (no banding, better gradient, better anti-aliasing). Second (relatedly), the final plotted markers (the last few before `2*pi`) overlap the first few. It's very hard to see in the pixel rendering, but if you zoom in on the vector-based rendering you can clearly see the last disc overlap the first few. I tried using different markers (`.` or `|`), but none of them go around the second issue. Bottom line: can I draw a circle in Python/Matplotlib which is defined in the proper vector/Bezier curve way, and which has an edge color defined according to a colormap (or, failing that, an arbitrary color gradient)?
One way I have found is to produce a colormap and then project it onto a polar axis. Here is a working example - it includes a nasty hack, though (clearly commented). I'm sure there's a way to either adjust limits or (harder) write your own `Transform` to get around it, but I haven't quite managed that yet. I thought the bounds on the call to `Normalize` would do that, but apparently not. ``` import matplotlib.pyplot as plt import numpy as np from matplotlib import cm import matplotlib as mpl fig = plt.figure() display_axes = fig.add_axes([0.1,0.1,0.8,0.8], projection='polar') display_axes._direction = 2*np.pi ## This is a nasty hack - using the hidden field to ## multiply the values such that 1 become 2*pi ## this field is supposed to take values 1 or -1 only!! norm = mpl.colors.Normalize(0.0, 2*np.pi) # Plot the colorbar onto the polar axis # note - use orientation horizontal so that the gradient goes around # the wheel rather than centre out quant_steps = 2056 cb = mpl.colorbar.ColorbarBase(display_axes, cmap=cm.get_cmap('hsv',quant_steps), norm=norm, orientation='horizontal') # aesthetics - get rid of border and axis labels cb.outline.set_visible(False) display_axes.set_axis_off() plt.show() # Replace with plt.savefig if you want to save a file ``` This produces [![colorwheel direct from matplotlib](http://i.stack.imgur.com/ZzAii.png)](http://i.stack.imgur.com/ZzAii.png) If you want a ring rather than a wheel, use this before `plt.show()` or `plt.savefig` ``` display_axes.set_rlim([-1,1]) ``` This gives [![color ring](http://i.stack.imgur.com/6ME6s.png)](http://i.stack.imgur.com/6ME6s.png) --- As per [@EelkeSpaak](http://stackoverflow.com/users/1692028/eelkespaak) in comments - if you save the graphic as an SVG as per the OP, here is a tip for working with the resulting graphic: The little elements of the resulting SVG image are touching and non-overlapping. This leads to faint grey lines in some renderers (Inkscape, Adobe Reader, probably not in print). A simple solution to this is to apply a small (e.g. 120%) scaling to each of the individual gradient elements, using e.g. Inkscape or Illustrator. Note you'll have to apply the transform to each element separately (the mentioned software provides functionality to do this automatically), rather than to the whole drawing, otherwise it has no effect.
Python: why the code for swapping the largest and the smallest numbers isn't working?
31,943,047
2
2015-08-11T13:24:52Z
31,943,643
7
2015-08-11T13:50:03Z
[ "python", "list" ]
Imagine we have a list of numbers `a` where all numbers are different, and we want to swap the largest one and the smallest one. The question is, why this code in Python: ``` a[a.index(min(a))], a[a.index(max(a))] = a[a.index(max(a))], a[a.index(min(a))] ``` isn't working?
Why does it fail? Let's take `a = [1, 2, 3, 4]` as example. First, the right side is evaluated: ``` a[a.index(max(a))], a[a.index(min(a))] => 4, 1 ``` That's btw of course the same as ``` max(a), min(a) => 4, 1 ``` Next, the assignments happen, [from left to right](https://docs.python.org/3.5/reference/simple_stmts.html#assignment-statements): First, setting `a[a.index(min(a))]` to 4 makes the list `[4, 2, 3, 4]`, as the minimum is at the front. Then, setting `a[a.index(max(a))]` to 1 makes the list `[1, 2, 3, 4]` again, as the maximum has been written at the front, so that's where it is found now and where the 1 gets written.
Localhost Endpoint to DynamoDB Local with Boto3
31,948,742
12
2015-08-11T17:56:46Z
32,260,680
13
2015-08-27T22:53:32Z
[ "python", "amazon-dynamodb", "dynamo-local" ]
Although Amazon provides documentation regarding how to connect to [dynamoDB local](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Tools.DynamoDBLocal.html) with Java, PHP and .Net, there is no description of how to connect to localhost:8000 using Python. Existing documentation on the web points to the use of the [DynamoDBConnection method](https://boto.readthedocs.org/en/latest/dynamodb2_tut.html) inside boto.dynamodb2.layer1, but this creates an incompatibility between live and test environments that use the boto3 protocol to manage dynamoDB. In boto3, you can make a request to dynamo using the following constructor and variables set into the environment: ``` client = boto3.client('dynamodb') table = client.list_tables() ``` Whereas the boto.dynamodb2.layer1 package requires you to construct the following: ``` client = DynamoDBConnection( host='localhost', port=8000, aws_access_key_id='anything', aws_secret_access_key='anything', is_secure=False) table = client.list_tables() ``` Although it is possible to create logic which determines the proper constructor based upon the local environment, I am wary of building a set of methods which treat each constructor as the same. Instead, I would prefer to use boto3 for everything and to be able to set the endpoint for dynamoDB in the environmental variables. Unfortunately, [that option](http://docs.pythonboto.org/en/latest/boto_config_tut.html#dynamodb) does not appear to be currently be available. Is there any way to use boto3 to define a dynamoDB local endpoint (like the other languages)? Or any chance that Amazon will plan to support this feature?
It does support DynamoDB Local. You just need to set the appropriate endpoint such as you can do with other [language SDKs](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Tools.DynamoDBLocal.html#Tools.DynamoDBLocal.Using) Here is a code snippet of how you can use boto3's client and resource interface via DynamoDB Local: ``` import boto3 # For a Boto3 client. ddb = boto3.client('dynamodb', endpoint_url='http://localhost:8000') response = ddb.list_tables() print(response) # For a Boto3 service resource ddb = boto3.resource('dynamodb', endpoint_url='http://localhost:8000') print(list(ddb.tables.all())) ```
Localhost Endpoint to DynamoDB Local with Boto3
31,948,742
12
2015-08-11T17:56:46Z
34,530,320
7
2015-12-30T13:16:44Z
[ "python", "amazon-dynamodb", "dynamo-local" ]
Although Amazon provides documentation regarding how to connect to [dynamoDB local](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Tools.DynamoDBLocal.html) with Java, PHP and .Net, there is no description of how to connect to localhost:8000 using Python. Existing documentation on the web points to the use of the [DynamoDBConnection method](https://boto.readthedocs.org/en/latest/dynamodb2_tut.html) inside boto.dynamodb2.layer1, but this creates an incompatibility between live and test environments that use the boto3 protocol to manage dynamoDB. In boto3, you can make a request to dynamo using the following constructor and variables set into the environment: ``` client = boto3.client('dynamodb') table = client.list_tables() ``` Whereas the boto.dynamodb2.layer1 package requires you to construct the following: ``` client = DynamoDBConnection( host='localhost', port=8000, aws_access_key_id='anything', aws_secret_access_key='anything', is_secure=False) table = client.list_tables() ``` Although it is possible to create logic which determines the proper constructor based upon the local environment, I am wary of building a set of methods which treat each constructor as the same. Instead, I would prefer to use boto3 for everything and to be able to set the endpoint for dynamoDB in the environmental variables. Unfortunately, [that option](http://docs.pythonboto.org/en/latest/boto_config_tut.html#dynamodb) does not appear to be currently be available. Is there any way to use boto3 to define a dynamoDB local endpoint (like the other languages)? Or any chance that Amazon will plan to support this feature?
Note: You will want to extend the above response to include region. I have appended to Kyle's code above. If your initial attempt is greeted with a region error, this will return the appropriate '[]' response. ``` import boto3 ## For a Boto3 client ('client' is for low-level access to Dynamo service API) ddb1 = boto3.client('dynamodb', endpoint_url='http://localhost:8000', region_name='us-west-2') response = ddb1.list_tables() print(response) # For a Boto3 service resource ('resource' is for higher-level, abstracted access to Dynamo) ddb2 = boto3.resource('dynamodb', endpoint_url='http://localhost:8000', region_name='us-west-2') print(list(ddb2.tables.all())) ```
How to limit python traceback to specific files
31,949,760
26
2015-08-11T18:52:37Z
32,999,522
12
2015-10-07T18:13:05Z
[ "python", "debugging", "traceback" ]
I write a lot of Python code that uses external libraries. Frequently I will write a bug, and when I run the code I get a big long traceback in the Python console. 99.999999% of the time it's due to a coding error in my code, not because of a bug in the package. But the traceback goes all the way to the line of error in the package code, and either it takes a lot of scrolling through the traceback to find the code I wrote, or the traceback is so deep into the package that my own code doesn't even appear in the traceback. Is there a way to "black-box" the package code, or somehow only show traceback lines from my code? I'd like the ability to specify to the system which directories or files I want to see traceback from.
In order to print your own stacktrace, you would need to handle all unhandled exceptions yourself; this is how the [`sys.excepthook`](https://docs.python.org/2/library/sys.html#sys.excepthook) becomes handy. The signature for this function is `sys.excepthook(type, value, traceback)` and its job is: > This function prints out a given traceback and exception to `sys.stderr`. So as long as you can play with the traceback and only extract the portion you care about you should be fine. Testing frameworks do that very frequently; they have custom `assert` functions which usually does not appear in the traceback, in other words they skip the frames that belong to the test framework. Also, in those cases, the tests usually are started by the test framework as well. You end up with a traceback that looks like this: `[ custom assert code ]` + `... [ code under test ] ...` + `[ test runner code ]` ## How to identify your code. You can add a global to your code: ``` __mycode = True ``` Then to identify the frames: ``` def is_mycode(tb): globals = tb.tb_frame.f_globals return globals.has_key('__mycode') ``` ## How to extract your frames. 1. skip the frames that don't matter to you (e.g. custom assert code) 2. identify how many frames are part of your code -> `length` 3. extract `length` frames ``` def mycode_traceback_levels(tb): length = 0 while tb and is_mycode(tb): tb = tb.tb_next length += 1 return length ``` ## Example handler. ``` def handle_exception(type, value, tb): # 1. skip custom assert code, e.g. # while tb and is_custom_assert_code(tb): # tb = tb.tb_next # 2. only display your code length = mycode_traceback_levels(tb) print ''.join(traceback.format_exception(type, value, tb, length)) ``` install the handler: ``` sys.excepthook = handle_exception ``` ## What next? You could adjust `length` to add one or more levels if you still want some info about where the failure is outside of your own code. see also <https://gist.github.com/dnozay/b599a96dc2d8c69b84c6>
Two word boundaries (\b) to isolate a single word
31,950,532
2
2015-08-11T19:41:17Z
31,950,573
8
2015-08-11T19:43:29Z
[ "python", "regex" ]
I am trying to match the word that appears immediately after a number - in the sentence below, it is the word "meters". > The tower is 100 **meters** tall. Here's the pattern that I tried which didn't work: ## **`\d+\s*(\b.+\b)`** But this one did: ## **`\d+\s*(\w+)`** The first incorrect pattern matched this: > The tower is 100 **meters tall**. I didn't want the word "tall" to be matched. I expected the following behavior: **`\d+`** `match one or more occurrence of a digit` **`\s*`** `match any or no spaces` **`(`** `start new capturing group` **`\b`** `find the word/non-word boundary` **`.+`** `match 1 or more of everything except new line` **`\b`** `find the next word/non-word boundary` **`)`** `stop capturing group` The problem is I don't know tiddly-twat about regex, and I am very much a noob as a noob can be. I am practicing by making my own problems and trying to solve them - this is one of them. Why didn't the match stop at the second break `(\b)`? --- This is Python flavored [Here's the regex101 test link of the above regex.](https://regex101.com/r/iJ1xE3/1)
It didn't stop because `+` is [**greedy**](http://www.rexegg.com/regex-quantifiers.html#greedytrap) by default, you want `+?` for a non-greedy match. A concise explanation — `*` and `+` are greedy quantifiers/operators meaning they will match as much as they can and still allow the remainder of the regular expression to match. You need to follow these operators with `?` for a non-greedy match, going in the above order it would be (`*?`) "zero or more" or (`+?`) "one or more" — but preferably "as few as possible". Also a word boundary `\b` matches positions where one side is a word character (letter, digit or underscore OR a unicode letter, digit or underscore in Python 3) and the other side is not a word character. I wouldn't use `\b` around the `.` if you're unclear what's in between the boundaries.
Start IPython notebook server without running web browser?
31,953,518
11
2015-08-11T23:11:25Z
31,953,548
13
2015-08-11T23:14:43Z
[ "python", "ipython" ]
I would like to use Emacs as main editor for ipython notebooks (with package [ein](http://tkf.github.io/emacs-ipython-notebook/#install)). I want to ask you if there is a way to run the server without the need to open a web browser.
Is this what you want? ``` $ ipython notebook --no-browser ```
Counting tuples in a list, no matter the order of each element within the tuples
31,953,807
3
2015-08-11T23:45:41Z
31,953,834
7
2015-08-11T23:48:59Z
[ "python", "list", "collections", "counter" ]
I have a question about counting occurrences within a list in Python. Here's the list: ``` aList = [(11, 0), (9, 7), (23, 9), (25, 3), (9, 9), (21, 2), (10, 9), (14, 14), (8, 13), (14, 9), (11, 4), (1, 14), (3, 9), (3, 1), (11, 9), (9, 1), (7, 0), (9, 3), (9, 3), (16, 11), (9, 7), (9, 13), (11, 9), (26, 18), (18, 9), (11, 14), (9, 9), (24, 26), (12, 21), (1, 14), (3, 14), (15, 14), (26, 9), (11, 3), (4, 14), (9, 14), (26, 4), (7, 26), (9, 3), (13, 3), (9, 24), (14, 9), (3, 26), (7, 25), (5, 9), (9, 5), (14, 4), (9, 0), (4, 26), (4, 26), (9, 9), (18, 18), (9, 7), (7, 6), (9, 9), (14, 13), (11, 9), (3, 9), (9, 15), (25, 9), (10, 24), (0, 4), (10, 3), (8, 12), (9, 4), (20, 9), (9, 9), (6, 9), (9, 8), (9, 9), (24, 16), (9, 11), (14, 9), (7, 12), (1, 9), (9, 13), (5, 13), (9, 9), (25, 9), (4, 9), (1, 3), (10, 9), (12, 9), (9, 9), (11, 11), (14, 3), (9, 25), (16, 1), (25, 16), (25, 16), (5, 9), (9, 3), (5, 1), (10, 24), (10, 25), (24, 1), (9, 1), (24, 9), (9, 7), (25, 3)] ``` As you can see, this is a list of tuples. I need to count the occurrences of each tuple no matter the order of each element within the tuples. I'm trying to use Collections' counter like this: ``` cnt = Counter() for l in aList: cnt[l] += 1 print cnt ``` Tuples like (3, 9) and (9, 3) should be counted as identical, which my code doesn't do right now. Is there a way to achieve this kind of counts with counter? Or should I use another method? Thanks!
This should do it: ``` counter = Counter(tuple(sorted(tup)) for tup in your_list) print counter ```
Add column sum as new column in PySpark dataframe
31,955,309
5
2015-08-12T02:59:12Z
31,955,747
10
2015-08-12T03:55:56Z
[ "python", "apache-spark", "pyspark", "spark-dataframe" ]
I'm using PySpark and I have a Spark dataframe with a bunch of numeric columns. I want to add a column that is the sum of all the other columns. Suppose my dataframe had columns "a", "b", and "c". I know I can do this: ``` df.withColumn('total_col', df.a + df.b + df.c) ``` The problem is that I don't want to type out each column individually and add them, especially if I have a lot of columns. I want to be able to do this automatically or by specifying a list of column names that I want to add. Is there another way to do this?
This was not obvious. I see no row-based sum of the columns defined in the spark Dataframes API. # Version 2 This can be done in a fairly simple way: ``` newdf = df.withColumn('total', sum(df[col] for col in df.columns)) ``` `df.columns` is supplied by pyspark as a list of strings giving all of the column names in the Spark Dataframe. For a different sum, you can supply any other list of column names instead. I did not try this as my first solution because I wasn't certain how it would behave. But it works. # Version 1 This is overly complicated, but works as well. You can do this: 1. use `df.columns` to get a list of the names of the columns 2. use that names list to make a list of the columns 3. pass that list to something that will invoke the column's overloaded add function in a [fold-type functional manner](http://stackoverflow.com/questions/10366374/what-is-the-pythonic-equivalent-to-the-fold-function-from-functional-program) With python's [reduce](https://docs.python.org/2/library/functions.html#reduce), some knowledge of how operator overloading works, and the pyspark code for columns [here](https://github.com/apache/spark/blob/master/python/pyspark/sql/column.py) that becomes: ``` def column_add(a,b): return a.__add__(b) newdf = df.withColumn('total_col', reduce(column_add, ( df[col] for col in df.columns ) )) ``` Note this is a python reduce, not a spark RDD reduce, and the parenthesis term in the second parameter to reduce requires the parenthesis because it is a list generator expression. **Tested, Works!** ``` $ pyspark >>> df = sc.parallelize([{'a': 1, 'b':2, 'c':3}, {'a':8, 'b':5, 'c':6}, {'a':3, 'b':1, 'c':0}]).toDF().cache() >>> df DataFrame[a: bigint, b: bigint, c: bigint] >>> df.columns ['a', 'b', 'c'] >>> def column_add(a,b): ... return a.__add__(b) ... >>> df.withColumn('total', reduce(column_add, ( df[col] for col in df.columns ) )).collect() [Row(a=1, b=2, c=3, total=6), Row(a=8, b=5, c=6, total=19), Row(a=3, b=1, c=0, total=4)] ```
Numpy elementwise product of 3d array
31,957,364
6
2015-08-12T06:17:54Z
31,958,728
7
2015-08-12T07:30:09Z
[ "python", "arrays", "numpy", "matrix", "vectorization" ]
I have two 3d arrays A and B with shape (N, 2, 2) that I would like to multiply element-wise according to the N-axis with a matrix product on each of the 2x2 matrix. With a loop implementation, it looks like ``` C[i] = dot(A[i], B[i]) ``` Is there a way I could do this without using a loop? I've looked into tensordot, but haven't been able to get it to work. I think I might want something like `tensordot(a, b, axes=([1,2], [2,1]))` but that's giving me an NxN matrix.
It seems you are doing matrix-multiplications for each slice along the first axis. For the same, you can use [`np.einsum`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.einsum.html) like so - ``` np.einsum('ijk,ikl->ijl',A,B) ``` Runtime tests and verify results - ``` In [179]: N = 10000 ...: A = np.random.rand(N,2,2) ...: B = np.random.rand(N,2,2) ...: ...: def einsum_based(A,B): ...: return np.einsum('ijk,ikl->ijl',A,B) ...: ...: def forloop(A,B): ...: N = A.shape[0] ...: C = np.zeros((N,2,2)) ...: for i in range(N): ...: C[i] = np.dot(A[i], B[i]) ...: return C ...: In [180]: np.allclose(einsum_based(A,B),forloop(A,B)) Out[180]: True In [181]: %timeit forloop(A,B) 10 loops, best of 3: 54.9 ms per loop In [182]: %timeit einsum_based(A,B) 100 loops, best of 3: 5.92 ms per loop ```
How to understand expression lists in Python
31,958,341
8
2015-08-12T07:11:30Z
31,958,494
7
2015-08-12T07:18:56Z
[ "python", "list" ]
When I read the Python document today, I found `Expression lists` on [Python Documents](https://docs.python.org/3/reference/expressions.html#expression-lists), the description on the site like this: > `expression_list ::= expression ( "," expression )* [","]` > > *An expression list containing at least one comma yields a tuple. The length of the tuple is the number of expressions in the list. The expressions are evaluated from left to right.* > > *The trailing comma is required only to create a single tuple (a.k.a. a singleton); it is optional in all other cases. A single expression without a trailing comma doesn’t create a tuple, but rather yields the value of that expression. (To create an empty tuple, use an empty pair of parentheses: ().)* Because the examples are not given on the site, So I just wondering anyone can give a brief description about this, and give a example about its usage. Thank a lots.
Here are some samples to help you understand what is going on: > An expression list containing at least one comma yields a tuple. This means, that if you have `1,2`, this will create a tuple. The length is how many items you have. > The trailing comma is required only to create a single tuple (a.k.a. a > singleton); it is optional in all other cases. This means that if you want to create a tuple with one item, you need to have a comma at the end, like this `1,`, otherwise: > A single expression without a trailing comma doesn’t create a tuple, > but rather yields the value of that expression. So `1` is not creating a tuple, what will happen is the express will be evaluated. This sounds like an obvious point but it makes sense if you write `(1)` and then expect it to be evaluated as a tupe (in the case of `(1)`, it will be evaluated to the integer value `1`). Finally > (To create an empty tuple, use an empty pair of parentheses: ().) If for some reason you want to create an empty tuple as an expression, use the following special syntax `()` It is a common practice to surround expressions (especially in the case of tuples) with (), but this is not required - although sometimes it helps with readability. `1,2` and `(1,2)` are equal: ``` >>> a = 1,2 >>> type(a) <type 'tuple'> >>> b = (1,2) >>> type(b) <type 'tuple'> >>> a == b True ```
Python string formatting with percent sign
31,964,930
14
2015-08-12T12:14:25Z
31,964,966
16
2015-08-12T12:16:09Z
[ "python", "string", "python-3.x" ]
I am trying to do exactly the following: ``` >>> x = (1,2) >>> y = 'hello' >>> '%d,%d,%s' % (x[0], x[1], y) '1,2,hello' ``` However, I have a long `x`, more than two items, so I tried: ``` >>> '%d,%d,%s' % (*x, y) ``` but it is syntax error. What would be the proper way of doing this without indexing like the first example?
`str % ..` accepts a tuple as a right-hand operand, so you can do the following: ``` >>> x = (1, 2) >>> y = 'hello' >>> '%d,%d,%s' % (x + (y,)) # Building a tuple of `(1, 2, 'hello')` '1,2,hello' ``` Your try should work in Python 3. where [`Additional Unpacking Generalizations`](https://www.python.org/dev/peps/pep-0448/) is supported, but not in Python 2.x: ``` >>> '%d,%d,%s' % (*x, y) '1,2,hello' ```
Python string formatting with percent sign
31,964,930
14
2015-08-12T12:14:25Z
31,964,980
10
2015-08-12T12:17:00Z
[ "python", "string", "python-3.x" ]
I am trying to do exactly the following: ``` >>> x = (1,2) >>> y = 'hello' >>> '%d,%d,%s' % (x[0], x[1], y) '1,2,hello' ``` However, I have a long `x`, more than two items, so I tried: ``` >>> '%d,%d,%s' % (*x, y) ``` but it is syntax error. What would be the proper way of doing this without indexing like the first example?
Perhaps have a look at [str.format()](https://docs.python.org/2/library/stdtypes.html#str.format). ``` >>> x = (5,7) >>> template = 'first: {}, second: {}' >>> template.format(*x) 'first: 5, second: 7' ``` ## Update: For completeness I am also including *additional unpacking generalizations* described by [PEP 448](https://www.python.org/dev/peps/pep-0448/). The extended syntax was introduced in **Python 3.5**, and the following is no longer a syntax error: ``` >>> x = (5, 7) >>> y = 42 >>> template = 'first: {}, second: {}, last: {}' >>> template.format(*x, y) # valid in Python3.5+ 'first: 5, second: 7, last: 42' ``` In **Python 3.4 and below**, however, if you want to pass additional arguments after the unpacked tuple, you are probably best off to pass them as *named arguments*: ``` >>> x = (5, 7) >>> y = 42 >>> template = 'first: {}, second: {}, last: {last}' >>> template.format(*x, last=y) 'first: 5, second: 7, last: 42' ``` This avoids the need to build a new tuple containing one extra element at the end.
what is the difference between x.type and type(x) in Python?
31,966,126
3
2015-08-12T13:04:37Z
31,966,200
8
2015-08-12T13:07:51Z
[ "python", "theano" ]
Consider the following lines ``` import theano.tensor as T x = T.dscalar('x') y = T.dscalar('y') z = x+y ``` And then, ``` In [15]: type(x) Out[15]: theano.tensor.var.TensorVariable ``` while, ``` In [16]: x.type Out[16]: TensorType(float64, scalar) ``` Why type(x) and x.type give two different pieces of information ? What information is conveyed by them ? I also see that referring to [Theano tutorial](http://deeplearning.net/software/theano/tutorial/adding.html) , ``` >>> type(x) <class 'theano.tensor.basic.TensorVariable'> >>> x.type TensorType(float64, scalar) ``` Why type(x) output is different in my case ? Are these caused by version specific implementation differences and what is signified by this difference ?
`type(x)` is a builtin. `x.type` is an attribute that's defined in your object. They are completely seperate, `type(x)` returns what type of object `x` is and `x.type` does whatever the object wants it to. In this case, it returns some information on the type of object it is
IPython notebook won't read the configuration file
31,974,797
11
2015-08-12T20:30:24Z
31,982,416
22
2015-08-13T07:47:41Z
[ "python", "ipython", "ipython-notebook", "jupyter" ]
I used the following command to initialize a profile: ``` ipython profile create myserver ``` Added thses lines to `~/.ipython/profile_myserver/ipython_notebook_config.py`: ``` c = get_config() c.NotebookApp.ip = '*' c.NotebookApp.port = 8889 ``` Tried starting the notebook with: ``` ipython notebook --profile=myserver --debug ``` It does not read the config file at all. This is the log output: ``` [W 16:26:56.607 NotebookApp] Unrecognized alias: '--profile=myserver', it will probably have no effect. [D 16:26:56.609 NotebookApp] Config changed: [D 16:26:56.609 NotebookApp] {'profile': u'myserver', 'NotebookApp': {'log_level': 10}} ... [I 16:26:56.665 NotebookApp] 0 active kernels [I 16:26:56.665 NotebookApp] The IPython Notebook is running at: http://localhost:8888/ ``` Since I've explicitly specified port 8889 and it still runs on 8888, it clearly ignores the config file. What am I missing?
IPython has now moved to **[version 4.0](http://blog.jupyter.org/2015/08/12/first-release-of-jupyter/)**, which means that if you are using it, it will be reading its configuration from `~/.jupyter`, not `~/.ipython`. You have to create a new configuration file with ``` jupyter notebook --generate-config ``` and then edit the resulting `~/.jupyter/jupyter_notebook_config.py` file according to your needs. More installation instructions [here](https://jupyter.readthedocs.org/en/latest/config.html).
Detecting lines and shapes in OpenCV using Python
31,974,843
8
2015-08-12T20:32:51Z
32,077,775
9
2015-08-18T16:25:58Z
[ "python", "opencv", "image-processing" ]
I've been playing around with OpenCV (cv2) and detecting lines and shapes. Say that my daughter drew a drawing, like so: [![enter image description here](http://i.stack.imgur.com/3jiNT.png)](http://i.stack.imgur.com/3jiNT.png) I am trying to write a Python script that would analyze the drawing and convert it into hard lines/shapes, something like: [![enter image description here](http://i.stack.imgur.com/5b0XP.png)](http://i.stack.imgur.com/5b0XP.png) That being said, I have installed opencv and tried to play around with it, but have had no luck aside from being able to draw a single vertical line through the image. Below is my code so far, any pointers or suggestions as to how I should go about doing this with opencv would be greatly appreciated. ``` import cv2 import numpy as np class File(object): def __init__(self, filename): self.filename = filename def open(self, filename=None, mode='r'): if filename is None: filename = self.filename return cv2.imread(filename), open(filename, mode) def save(self, image=None, filename_override=None): filename = "output/" + self.filename.split('/')[-1] if filename_override: filename = "output/" + filename_override return cv2.imwrite(filename, image) class Image(object): def __init__(self, image): self.image = image def grayscale(self): return cv2.cvtColor(self.image, cv2.COLOR_BGR2GRAY) def edges(self): return cv2.Canny(self.image, 0, 255) def lines(self): lines = cv2.HoughLinesP(self.image, 1, np.pi/2, 6, None, 50, 10) for line in lines[0]: pt1 = (line[0],line[1]) pt2 = (line[2],line[3]) cv2.line(self.image, pt1, pt2, (0,0,255), 2) if __name__ == '__main__': File = File('images/a.png') Image = Image(File.open()[0]) Image.image = Image.grayscale() Image.lines() File.save(Image.image) ``` Unfortunately, for a simple square drawing, all I get back is: [![enter image description here](http://i.stack.imgur.com/p46aO.png)](http://i.stack.imgur.com/p46aO.png) where the vertical line in the box is the output from the code.
Here is my attempt. It's in C++, but can be easily ported to python since most are OpenCV functions. A brief outline of the method, comments in the code should help, too. 1. Load the image 2. Convert to grayscale 3. Binaryze the image (threshold) 4. Thinning, to have thin contours and help `findContours` 5. Get contours 6. For each contour, get convex hull (to handle open contours), and classify according to *circularity*. Handle each shape differently. * **Circle** : find the minimum encolsing circle, or the best fitting ellipse * **Recrangle** : find the boundinx box, or the minimum oriented bounding box. * **Triangle** : search for the intersection of the minimum enclosing circle with the original shape, as they would intersect in the three vertices of the triangle. NOTES: * I needed to modify the original image to 3 channel RGB from a png with transparency. * The *thinning* code is from [here](https://github.com/bsdnoobz/zhang-suen-thinning). There is also the Python version. * *Circularity* is defined as: A measures how close to a circle the shape is. E.g. a regular hexagon has higher circularity than say a square. Is defined as (\frac{4\*\pi\*Area}{perimeter \* perimeter}). This means that a circle has a circularity of 1, circularity of a square is 0.785, and so on. * Because of the contours, there may be multiple detection for each shape. These can be filtered out according to, for example, intersection over union condition. I did't inserted this part in the code for now, since it requires additional logic that isn't strictly related to the main task of finding the shapes. **UPDATE** - Just noticed that in OpenCV 3.0.0 there is the function [minEnclosingTriangle](http://docs.opencv.org/3.0-beta/modules/imgproc/doc/structural_analysis_and_shape_descriptors.html#minenclosingtriangle). This might be helpful to use instead of my procedure to find the triangle vertices. However, since inserting this function in the code would be trivial, I'll leave my procedure in the code in case one doesn't have OpenCV 3.0.0. The code: ``` #include <opencv2\opencv.hpp> #include <vector> #include <iostream> using namespace std; using namespace cv; ///////////////////////////////////////////////////////////////////////////////////////////// // Thinning algorithm from here: // https://github.com/bsdnoobz/zhang-suen-thinning ///////////////////////////////////////////////////////////////////////////////////////////// void thinningIteration(cv::Mat& img, int iter) { CV_Assert(img.channels() == 1); CV_Assert(img.depth() != sizeof(uchar)); CV_Assert(img.rows > 3 && img.cols > 3); cv::Mat marker = cv::Mat::zeros(img.size(), CV_8UC1); int nRows = img.rows; int nCols = img.cols; if (img.isContinuous()) { nCols *= nRows; nRows = 1; } int x, y; uchar *pAbove; uchar *pCurr; uchar *pBelow; uchar *nw, *no, *ne; // north (pAbove) uchar *we, *me, *ea; uchar *sw, *so, *se; // south (pBelow) uchar *pDst; // initialize row pointers pAbove = NULL; pCurr = img.ptr<uchar>(0); pBelow = img.ptr<uchar>(1); for (y = 1; y < img.rows - 1; ++y) { // shift the rows up by one pAbove = pCurr; pCurr = pBelow; pBelow = img.ptr<uchar>(y + 1); pDst = marker.ptr<uchar>(y); // initialize col pointers no = &(pAbove[0]); ne = &(pAbove[1]); me = &(pCurr[0]); ea = &(pCurr[1]); so = &(pBelow[0]); se = &(pBelow[1]); for (x = 1; x < img.cols - 1; ++x) { // shift col pointers left by one (scan left to right) nw = no; no = ne; ne = &(pAbove[x + 1]); we = me; me = ea; ea = &(pCurr[x + 1]); sw = so; so = se; se = &(pBelow[x + 1]); int A = (*no == 0 && *ne == 1) + (*ne == 0 && *ea == 1) + (*ea == 0 && *se == 1) + (*se == 0 && *so == 1) + (*so == 0 && *sw == 1) + (*sw == 0 && *we == 1) + (*we == 0 && *nw == 1) + (*nw == 0 && *no == 1); int B = *no + *ne + *ea + *se + *so + *sw + *we + *nw; int m1 = iter == 0 ? (*no * *ea * *so) : (*no * *ea * *we); int m2 = iter == 0 ? (*ea * *so * *we) : (*no * *so * *we); if (A == 1 && (B >= 2 && B <= 6) && m1 == 0 && m2 == 0) pDst[x] = 1; } } img &= ~marker; } void thinning(const cv::Mat& src, cv::Mat& dst) { dst = src.clone(); dst /= 255; // convert to binary image cv::Mat prev = cv::Mat::zeros(dst.size(), CV_8UC1); cv::Mat diff; do { thinningIteration(dst, 0); thinningIteration(dst, 1); cv::absdiff(dst, prev, diff); dst.copyTo(prev); } while (cv::countNonZero(diff) > 0); dst *= 255; } int main() { RNG rng(123); // Read image Mat3b src = imread("path_to_image"); // Convert to grayscale Mat1b gray; cvtColor(src, gray, COLOR_BGR2GRAY); // Binarize Mat1b bin; threshold(gray, bin, 127, 255, THRESH_BINARY_INV); // Perform thinning thinning(bin, bin); // Create result image Mat3b res = src.clone(); // Find contours vector<vector<Point>> contours; findContours(bin.clone(), contours, CV_RETR_LIST, CV_CHAIN_APPROX_NONE); // For each contour for (vector<Point>& contour : contours) { // Compute convex hull vector<Point> hull; convexHull(contour, hull); // Compute circularity, used for shape classification double area = contourArea(hull); double perimeter = arcLength(hull, true); double circularity = (4 * CV_PI * area) / (perimeter * perimeter); // Shape classification if (circularity > 0.9) { // CIRCLE //{ // // Fit an ellipse ... // RotatedRect rect = fitEllipse(contour); // Scalar color = Scalar(rng.uniform(0, 255), rng.uniform(0, 255), rng.uniform(0, 255)); // ellipse(res, rect, color, 5); //} { // ... or find min enclosing circle Point2f center; float radius; minEnclosingCircle(contour, center, radius); Scalar color = Scalar(rng.uniform(0, 255), rng.uniform(0, 255), rng.uniform(0, 255)); circle(res, center, radius, color, 5); } } else if (circularity > 0.75) { // RECTANGLE //{ // // Minimum oriented bounding box ... // RotatedRect rect = minAreaRect(contour); // Point2f pts[4]; // rect.points(pts); // Scalar color = Scalar(rng.uniform(0, 255), rng.uniform(0, 255), rng.uniform(0, 255)); // for (int i = 0; i < 4; ++i) // { // line(res, pts[i], pts[(i + 1) % 4], color, 5); // } //} { // ... or bounding box Rect box = boundingRect(contour); Scalar color = Scalar(rng.uniform(0, 255), rng.uniform(0, 255), rng.uniform(0, 255)); rectangle(res, box, color, 5); } } else if (circularity > 0.7) { // TRIANGLE // Select the portion of the image containing only the wanted contour Rect roi = boundingRect(contour); Mat1b maskRoi(bin.rows, bin.cols, uchar(0)); rectangle(maskRoi, roi, Scalar(255), CV_FILLED); Mat1b triangle(roi.height, roi.height, uchar(0)); bin.copyTo(triangle, maskRoi); // Find min encolsing circle on the contour Point2f center; float radius; minEnclosingCircle(contour, center, radius); // decrease the size of the enclosing circle until it intersects the contour // in at least 3 different points (i.e. the 3 vertices) vector<vector<Point>> vertices; do { vertices.clear(); radius--; Mat1b maskCirc(bin.rows, bin.cols, uchar(0)); circle(maskCirc, center, radius, Scalar(255), 5); maskCirc &= triangle; findContours(maskCirc.clone(), vertices, CV_RETR_LIST, CV_CHAIN_APPROX_NONE); } while (vertices.size() < 3); // Just get the first point in each vertex blob. // You could get the centroid for a little better accuracy Scalar color = Scalar(rng.uniform(0, 255), rng.uniform(0, 255), rng.uniform(0, 255)); line(res, vertices[0][0], vertices[1][0], color, 5); line(res, vertices[1][0], vertices[2][0], color, 5); line(res, vertices[2][0], vertices[0][0], color, 5); } else { cout << "Some other shape..." << endl; } } return 0; } ``` The results (`minEnclosingCircle` and `boundingRect`): [![enter image description here](http://i.stack.imgur.com/RxFJx.png)](http://i.stack.imgur.com/RxFJx.png) The results (`fitEllipse` and `minAreaRect`): [![enter image description here](http://i.stack.imgur.com/ZvSfE.png)](http://i.stack.imgur.com/ZvSfE.png)
Open S3 object as a string with Boto3
31,976,273
21
2015-08-12T22:10:33Z
31,976,895
29
2015-08-12T23:07:10Z
[ "python", "amazon-s3", "boto", "boto3" ]
I'm aware that with Boto 2 it's possible to open an S3 object as a string with: get\_contents\_as\_string() <http://boto.readthedocs.org/en/latest/ref/file.html?highlight=contents%20string#boto.file.key.Key.get_contents_as_string> Is there an equivalent function in boto3 ?
This isn't in the boto3 documentation. This worked for me: ``` object.get()["Body"].read() ``` object being an s3 object: <http://boto3.readthedocs.org/en/latest/reference/services/s3.html#object>
Open S3 object as a string with Boto3
31,976,273
21
2015-08-12T22:10:33Z
35,376,156
12
2016-02-13T04:41:11Z
[ "python", "amazon-s3", "boto", "boto3" ]
I'm aware that with Boto 2 it's possible to open an S3 object as a string with: get\_contents\_as\_string() <http://boto.readthedocs.org/en/latest/ref/file.html?highlight=contents%20string#boto.file.key.Key.get_contents_as_string> Is there an equivalent function in boto3 ?
`read` will return bytes. At least for Python 3, if you want to return a string, you have to decode using the right encoding: ``` import boto3 s3 = boto3.resource('s3') obj = s3.Object(bucket, key) obj.get()['Body'].read().decode('utf-8') ```
Is there a more pythonic way to populate a this list?
31,981,563
4
2015-08-13T07:01:57Z
31,981,585
8
2015-08-13T07:03:11Z
[ "python", "list" ]
I want to clean the strings from a django query so it can be used in latex ``` items = [] items_to_clean = items.objects.get.all().values() for dic in items_to_clean: items.append(dicttolatex(dic)) ``` This is my standard aproach to this task. Can this somehow be solved whith list comprehension. since `dicttolatex` is a function returning a dict.
You can avoid repeated calls to `append` by using a list comprehension: ``` items = [dicttolatex(dic) for dic in items_to_clean] ```
Specifying exact Python version for Travis CI in combination with tox
31,985,877
4
2015-08-13T10:39:12Z
31,990,486
7
2015-08-13T14:04:47Z
[ "python", "travis-ci", "tox" ]
I have the following .travis.yml: ``` language: python env: - TOXENV=py27 - TOXENV=py34 install: - pip install -U tox script: - tox ``` and the following tox.ini: ``` [tox] envlist = py27,py34 [testenv] commands = py.test tests/ deps = -rtests/test_requirements.txt ``` I need Python 3.4.3, which is [available since awhile back](https://github.com/travis-ci/travis-ci/issues/4632) in Travis. How can I specify this exact version of Python in .travis.yml so tox can use the correct version for the `py34` environment?
Inspired by `pip`'s [.travis.yml](https://github.com/pypa/pip/blob/166f3d20e27f06c1ca74d30ec6ceed688f295b47/.travis.yml) it seems easiest to specify the Travis matrix with different environment variables: ``` matrix: include: - python: 3.4.3 env: TOXENV=py34 - python: 2.7 env: TOXENV=py27 ```
Put multiple items in a python queue
31,987,207
2
2015-08-13T11:41:11Z
31,987,220
7
2015-08-13T11:41:50Z
[ "python", "queue" ]
Suppose you have an iterable `items` containing items that should be put in a queue `q`. Of course you can do it like this: ``` for i in items: q.put(i) ``` But it feels unnecessary to write this in two lines - is that supposed to be pythonic? Is there no way to do something more readable - i.e. like this ``` q.put(*items) ```
Using the built-in `map` function : ``` map(q.put, items) ``` It will apply `q.put` to all your items in your list. Useful one-liner. --- For Python 3, you can use it as following : ``` list(map(q.put, items)) ``` Or also : ``` from collections import deque deque(map(q.put, items)) ``` But at this point, the `for` loop is quite more readable.
numpy array, difference between a /= x vs. a = a / x
31,987,713
19
2015-08-13T12:03:48Z
31,987,859
29
2015-08-13T12:10:20Z
[ "python", "arrays", "numpy", "integer-division", "in-place" ]
I'm using python 2.7.3, when I execute the following piece of code: ``` import numpy as np a = np.array([[1,2,3],[4,5,6]]) a = a / float(2**16 - 1) print a ``` This will result in he following output: ``` >> array([[1.52590219e-05, 3.05180438e-05, 4.57770657e-05], >> [6.10360876e-05, 7.62951095e-05, 9.15541314e-05]]) ``` Exactly as expected, however when I execute the following piece of code: ``` import numpy as np a = np.array([[1,2,3],[4,5,6]]) a /= float(2**16 - 1) print a ``` I get the following output: ``` >> array([[0, 0, 0], >> [0, 0, 0]]) ``` I expected the same output as in the previous example, I don't understand the different ouput, which seems to be a result of using `a /= float(2**16 - 1)` vs `a = a / float(2**16 - 1)`.
[From the documentation:](http://docs.scipy.org/doc/numpy/reference/arrays.ndarray.html#arithmetic-and-comparison-operations) > **Warning:** > > In place operations will perform the calculation using the precision decided by the data type of the two operands, but will silently downcast the result (if necessary) so it can fit back into the array. Therefore, for mixed precision calculations, `A {op}= B` can be different than `A = A {op} B`. For example, suppose `a = ones((3,3))`. Then, `a += 3j` is different than `a = a + 3j`: while they both perform the same computation, `a += 3` casts the result to fit back in `a`, whereas `a = a + 3j` re-binds the name `a` to the result. Since your array was an array of integers, when using the in-place operations, the result will be downcasted to integers again. If you change your array so it stores floats originally, then the results (which are floats) can be stored in the original array, and your code will work fine: ``` >>> a = np.array([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]) >>> a /= float(2**16 - 1) >>> a array([[ 1.52590219e-05, 3.05180438e-05, 4.57770657e-05], [ 6.10360876e-05, 7.62951095e-05, 9.15541314e-05]]) ```
Better way to parse and search a string?
31,992,222
4
2015-08-13T15:14:14Z
31,999,847
8
2015-08-13T23:06:38Z
[ "python", "rust" ]
I have been looking to speed up a basic Python function which basically just takes a line of text and checks the line for a substring. The Python program is as follows: ``` import time def fun(line): l = line.split(" ", 10) if 'TTAGGG' in l[9]: pass # Do nothing line = "FCC2CCMACXX:4:1105:10758:14389# 81 chrM 1 32 10S90M = 16151 16062 CATCACGATGGATCACAGGTCTATCACCCTATTAACCACTCACGGGAGCTTTCCATGCATTTGGTATTTTCGTCTGGGGGGTGTGCACGCTTAGGGGATAGCATTG bbb^Wcbbbbccbbbcbccbba]WQG^bbcdcb_^_c_^`ccdddeeeeeffggggiiiiihiiiiihiiihihiiiihghhiihgfgfgeeeeebbb NM:i:1 AS:i:85 XS:i:65 RG:Z:1_DB31" time0 = time.time() for i in range(10000): fun(line) print time.time() - time0 ``` I wanted to see if I could use some of the high level features of Rust to possibly gain some performance, but the code runs considerably slower. The Rust conversion is: ``` extern crate regex; extern crate time; use regex::Regex; fn main() { let line = "FCC2CCMACXX:4:1105:10758:14389# 81 chrM 1 32 10S90M = 16151 16062 CATCACGATGGATCACAGGTCTATCACCCTATTAACCACTCACGGGAGCTTTCCATGCATTTGGTATTTTCGTCTGGGGGGTGTGCACGCTTAGGGGATAGCATTG bbb^Wcbbbbccbbbcbccbba]WQG^bbcdcb_^_c_^`ccdddeeeeeffggggiiiiihiiiiihiiihihiiiihghhiihgfgfgeeeeebbb NM:i:1 AS:i:85 XS:i:65 RG:Z:1_DB31"; let substring: &str = "TTAGGG"; let time0: f64 = time::precise_time_s(); for _ in 0..10000 { fun(line, substring); } let time1: f64 = time::precise_time_s(); let elapsed: f64 = time1 - time0; println!("{}", elapsed); } fn fun(line: &str, substring: &str) { let l: Vec<&str> = line.split(" ") .enumerate() .filter(|&(i, _)| i==9) .map(|(_, e) | e) .collect(); let re = Regex::new(substring).unwrap(); if re.is_match(&l[0]) { // Do nothing } } ``` On my machine, Python times this at 0.0065s vs Rusts 1.3946s. Just checking some basic timings, the `line.split()` part of the code takes around 1s, and the regex step is around 0.4s. Can this really be right, or is there an issue with timing this properly?
As a baseline, I ran your Python program with Python 2.7.6. Over 10 runs, it had a mean time of 12.2ms with a standard deviation of 443μs. I don't know how you got the very good time of **6.5ms**. Running your Rust code with Rust 1.4.0-dev (`febdc3b20`), without optimizations, I got a mean of 958ms and a standard deviation of 33ms. Running your code with optimizations (`cargo run --release`), I got a mean of 34.6ms and standard deviation of 495μs. **Always do benchmarking in release mode**. There are further optimizations you can do: Compiling the regex once, outside of the timing loop: ``` fn main() { // ... let substring = "TTAGGG"; let re = Regex::new(substring).unwrap(); // ... for _ in 0..10000 { fun(line, &re); } // ... } fn fun(line: &str, re: &Regex) { // ... } ``` Produces an average of 10.4ms with a standard deviation of 678μs. Switching to a substring match: ``` fn fun(line: &str, substring: &str) { // ... if l[0].contains(substring) { // Do nothing } } ``` Has a mean of 8.7ms and a standard deviation of 334μs. And finally, if you look at just the one result instead of collecting everything into a vector: ``` fn fun(line: &str, substring: &str) { let col = line.split(" ").nth(9); if col.map(|c| c.contains(substring)).unwrap_or(false) { // Do nothing } } ``` Has a mean of 6.30ms and standard deviation of 114μs.
Why can't Python see environment variables?
31,993,885
2
2015-08-13T16:38:26Z
31,993,903
11
2015-08-13T16:39:09Z
[ "python", "bash", "environment-variables" ]
I'm working on Debian Jessie with Python 2. Why can't Python's `environ` see environment variables that are visible in bash? ``` # echo $SECRET_KEY xxx-xxx-xxxx # python >>> from os import environ >>> environ["SECRET_KEY"] Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/root/.virtualenvs/prescribing/lib/python2.7/UserDict.py", line 23, in __getitem__ raise KeyError(key) KeyError: 'SECRET_KEY' ``` I set these environment variables using `/etc/environment` - not sure if that's relevant: ``` SECRET_KEY=xxx-xxx-xxx ``` I had to run `source /etc/environment` to get bash to see them, which I thought was strange. UPDATE: `printenv SECRET_KEY` produces nothing, so I guess `SECRET_KEY` is a shell not an environment variable.
You need to *export* environment variables for child processes to see them: ``` export SECRET_KEY ``` Demo: ``` $ SECRET_KEY='foobar' $ bin/python -c "import os; print os.environ.get('SECRET_KEY', 'Nonesuch')" Nonesuch $ export SECRET_KEY $ bin/python -c "import os; print os.environ.get('SECRET_KEY', 'Nonesuch')" foobar ``` You can combine the setting and exporting in one step: ``` export SECRET_KEY=xxx-xxx-xxxx ``` Note that new variables in `/etc/environment` do not show up in your existing shells automatically, not until you have a *new login*. For a GUI desktop, you'll have to log out and log in again, for SSH sessions you'll have to create a new SSH login. Only then will you get a new tree of processes with the changes present. Using `source /etc/environment` only sets 'local' variables (the file is not a script). See [How to reload /etc/environment without rebooting?](http://superuser.com/questions/339617/how-to-reload-etc-environment-without-rebooting) over on Super User.
WebAssembly, JavaScript, and other languages
31,994,034
10
2015-08-13T16:45:38Z
31,994,562
10
2015-08-13T17:13:21Z
[ "javascript", "c#", "python", "webassembly" ]
With the advent of the New Era of the Web, WebAssembly, which is to be designed in cooperation by Google, Microsoft, Apple, and Mozilla: > **WebAssembly High-Level Goals** > > 1. Define a portable, size- and load-time-efficient binary format to serve as a compilation target which can be compiled to execute at native speed by taking advantage of common hardware capabilities available on a wide range of platforms, including mobile and IoT > > [read more...](https://github.com/WebAssembly/design/blob/master/HighLevelGoals.md) I would like to ask those who already possess this knowledge: Can potentially any programming language be compiled to WebAssembly once its made? Let it be C#, Java, Python, JavaScript, Ruby. If this is the case - could a web developer choose any language to accomplish things he would achieve with JavaScript now?
The goal is indeed to support any language, but supporting any language is difficult to pull off without huge delays. WebAssembly is currently focusing on languages that are traditionally compiled ahead-of-time, work well with on linear memory heap, and which don't require dynamic recompilation, runtime code loading, or garbage collections. Some of these constraints are there to get to a Minimum Viable Product as early as possible, and take into account what existing in-browser compilers can do. Note that the MVP won't support threads. Threads will be added shortly after. Python, JavaScript and Ruby can easily be supported by compiling an interpreter, written in C/C++, to WebAssembly. Later versions of WebAssembly will support JIT-compilation, but engines like V8 will have to target WebAssembly as if it were a new ISA (e.g. on par with x86-64 / ARM / ...). C# and Java require similar GC and stack manipulation primitives. That's also on the roadmap, but after MVP, threads, and dynamic linking. Note that the languages may work just fine, but supporting all their libraries is also difficult! We (browser engineers) can work towards supporting languages well, but we need communities to build up around great library support. On your last sentence: yes WebAssembly should be able to do many things JavaScript can do because it'll ahve access to the same Web APIs. Its goal isn't to replace JavaScript though: it's to complement JavaScript, and avoid adding features to JavaScript for the sake of supporting other languages. Keep JavaScript evolution for folks who target JavaScript, and evolve WebAssembly to be JavaScript's cool sidekick who likes other languages.
Python 3: How can object be instance of type?
31,995,472
9
2015-08-13T18:07:49Z
31,995,548
15
2015-08-13T18:12:41Z
[ "python", "python-3.x", "python-3.4" ]
In Python 3, `object` is an instance of `type` and `type` is also an instance of `object`! How is it possible that each class is derived from the other? Any implementation details? I checked this using `isinstance(sub, base)`, which, according to Python documentation, checks if sub class is derived from base class: ``` isinstance(object, type) Out[1]: True isinstance(type, object) Out[2]: True ```
This is one of the edge cases in Python: * Everything in Python is an object, so since `object` is the base type of everything, `type` (being something in Python) is an instance of `object`. * Since `object` is the base *type* of everything, `object` is also a *type*, which makes `object` an instance of `type`. Note that this relationship is nothing you can replicate with your own *things* in Python. It’s a single exception that is built into the language. --- On the implementation side, the two names are represented by `PyBaseObject_Type` (for `object`) and `PyType_Type` (for `type`). When you use `isinstance`, the type check—in the very last step, after everything else has failed—is done by [`type_is_subtype_base_chain`](https://hg.python.org/cpython/file/1dd4f473c627/Objects/typeobject.c#l1344): ``` type_is_subtype_base_chain(PyTypeObject *a, PyTypeObject *b) { do { if (a == b) return 1; a = a->tp_base; } while (a != NULL); return (b == &PyBaseObject_Type); } ``` This essentially keeps going up the type hierarchy of `a` and checks the resulting type against `b`. If it cannot find one, then the last resort is to check whether `b` is actually `object` in which case the function returns true: since everything is an object. So the “everything is an instance of `object`” part is actually hardcoded into the instance check. And as for why `object` is a `type`, this is actually even simpler because it’s simply defined that way in the [declaration of `PyBaseObject_Type`](https://hg.python.org/cpython/file/1dd4f473c627/Objects/typeobject.c#l3294): ``` PyTypeObject PyBaseObject_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "object", /* tp_name */ sizeof(PyObject), /* tp_basicsize */ … ``` The `PyVarObject_HEAD_INIT` essentially sets the core type information stuff, including the base type, which is `PyType_Type`. There are actually two more consequences of this relationship: * Since everything is an object, `object` is also an instance of `object`: `isinstance(object, object)` * Since `PyType_Type` is also implemented with the same `PyVarObject_HEAD_INIT`, `type` is also a type: `isinstance(type, type)`.
Plotting oceans in maps using basemap and python
31,996,071
4
2015-08-13T18:42:57Z
32,120,065
7
2015-08-20T13:47:52Z
[ "python", "plot", "matplotlib-basemap" ]
I am plotting the netCDF file available here: <https://goo.gl/QyUI4J> Using the code below, the map looks like this: [![enter image description here](http://i.stack.imgur.com/VVt0y.png)](http://i.stack.imgur.com/VVt0y.png) However, I want the oceans to be in white color. Better still, I want to be able to specify what color the oceans show up in. How do I change the code below to do that? Right now, the issue is that the oceans are getting plotted on the data scale. (please note that the netCDF file is huge ~3.5 GB). ``` import pdb, os, glob, netCDF4, numpy from matplotlib import pyplot as plt from mpl_toolkits.basemap import Basemap def plot_map(path_nc, var_name): """ Plot var_name variable from netCDF file :param path_nc: Name of netCDF file :param var_name: Name of variable in netCDF file to plot on map :return: Nothing, side-effect: plot an image """ nc = netCDF4.Dataset(path_nc, 'r', format='NETCDF4') tmax = nc.variables['time'][:] m = Basemap(projection='robin',resolution='c',lat_0=0,lon_0=0) m.drawcoastlines() m.drawcountries() # find x,y of map projection grid. lons, lats = get_latlon_data(path_nc) lons, lats = numpy.meshgrid(lons, lats) x, y = m(lons, lats) nc_vars = numpy.array(nc.variables[var_name]) # Plot! m.drawlsmask(land_color='white',ocean_color='white') cs = m.contourf(x,y,nc_vars[len(tmax)-1,:,:],numpy.arange(0.0,1.0,0.1),cmap=plt.cm.RdBu) # add colorbar cb = m.colorbar(cs,"bottom", size="5%", pad='2%') cb.set_label('Land cover percentage '+var_name+' in '+os.path.basename(path_nc)) plt.show() plot_map('perc_crops.nc','LU_Corn.nc') ```
You need to use [`maskoceans`](http://matplotlib.org/basemap/api/basemap_api.html#mpl_toolkits.basemap.maskoceans) on your `nc_vars` dataset Before `contourf`, insert this ``` nc_new = maskoceans(lons,lats,nc_vars[len(tmax)-1,:,:]) ``` and then call `contourf` with the newly masked dataset i.e. ``` cs = m.contourf(x,y,nc_new,numpy.arange(0.0,1.0,0.1),cmap=plt.cm.RdBu) ``` To dictate the ocean colour, you can either drop the call to `drawslmask` if you want white oceans or specify an ocean colour in that call - e.g. insert `m.drawlsmask(land_color='white',ocean_color='cyan')`. I've given the working code with as few alterations to yours as possible below. Uncomment the call to `drawslmask` to see cyan coloured oceans. ### Output [![enter image description here](http://i.stack.imgur.com/x8BJl.png)](http://i.stack.imgur.com/x8BJl.png) # Full working version of code ``` import pdb, os, glob, netCDF4, numpy from matplotlib import pyplot as plt from mpl_toolkits.basemap import Basemap, maskoceans def plot_map(path_nc, var_name): """ Plot var_name variable from netCDF file :param path_nc: Name of netCDF file :param var_name: Name of variable in netCDF file to plot on map :return: Nothing, side-effect: plot an image """ nc = netCDF4.Dataset(path_nc, 'r', format='NETCDF4') tmax = nc.variables['time'][:] m = Basemap(projection='robin',resolution='c',lat_0=0,lon_0=0) m.drawcoastlines() m.drawcountries() # find x,y of map projection grid. lons, lats = nc.variables['lon'][:],nc.variables['lat'][:] # N.B. I had to substitute the above for unknown function get_latlon_data(path_nc) # I guess it does the same job lons, lats = numpy.meshgrid(lons, lats) x, y = m(lons, lats) nc_vars = numpy.array(nc.variables[var_name]) #mask the oceans in your dataset nc_new = maskoceans(lons,lats,nc_vars[len(tmax)-1,:,:]) #plot! #optionally give the oceans a colour with the line below #Note - if land_color is omitted it will default to grey #m.drawlsmask(land_color='white',ocean_color='cyan') cs = m.contourf(x,y,nc_new,numpy.arange(0.0,1.0,0.1),cmap=plt.cm.RdBu) # add colorbar cb = m.colorbar(cs,"bottom", size="5%", pad='2%') cb.set_label('Land cover percentage '+var_name+' in '+os.path.basename(path_nc)) plt.show() plot_map('perc_crops.nc','LU_Corn.nc') ``` --- ***P.S.*** That's a big file to test!!
Why does python allow spaces between an object and the method name after the "."
31,996,132
2
2015-08-13T18:46:00Z
31,996,173
7
2015-08-13T18:48:35Z
[ "python", "python-2.7" ]
Does anyone know why python allows you to put an unlimited amount of spaces between an object and the name of the method being called the "." ? Here are some examples: ``` >>> x = [] >>> x. insert(0, 'hi') >>> print x ['hi'] ``` Another example: ``` >>> d = {} >>> d ['hi'] = 'there' >>> print d {'hi': 'there'} ``` It is the same for classes as well. ``` >>> myClass = type('hi', (), {'there': 'hello'}) >>> myClass. there 'hello' ``` I am using python 2.7 I tried doing some google searches and looking at the python source code, but I cannot find any reason why this is allowed.
The `.` acts like an operator. You can do `obj . attr` the same way you can do `this + that` or `this * that` or the like. The [language reference](https://docs.python.org/2/reference/lexical_analysis.html#whitespace-between-tokens) says: > Except at the beginning of a logical line or in string literals, the whitespace characters space, tab and formfeed can be used interchangeably to separate tokens. Because this rule is so general, I would assume the code that does it is very early in the parsing process. It's nothing specific to `.`. It just ignores all whitespace everywhere except at the beginning of the line or inside a string.
Python: keras shape mismatch error
31,997,366
3
2015-08-13T20:00:30Z
32,938,020
10
2015-10-04T20:26:27Z
[ "python", "keras" ]
I am trying to build a very simple multilayer perceptron (MLP) in `keras`: ``` model = Sequential() model.add(Dense(16, 8, init='uniform', activation='tanh')) model.add(Dropout(0.5)) model.add(Dense(8, 2, init='uniform', activation='tanh')) sgd = SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True) model.compile(loss='mean_squared_error', optimizer=sgd) model.fit(X_train, y_train, nb_epoch=1000, batch_size=50) score = model.evaluate(X_test, y_test, batch_size=50) ``` My training data shape: `X_train.shape` gives `(34180, 16)` The labels belong to binary class with shape: `y_train.shape` gives `(34180,)` So my `keras` code should produce the network with following connection: `16x8 => 8x2` which produces the shape mismatch error: ``` ValueError: Input dimension mis-match. (input[0].shape[1] = 2, input[1].shape[1] = 1) Apply node that caused the error: Elemwise{sub,no_inplace}(Elemwise{Composite{tanh((i0 + i1))}}[(0, 0)].0, <TensorType(float64, matrix)>) Inputs types: [TensorType(float64, matrix), TensorType(float64, matrix)] Inputs shapes: [(50, 2), (50, 1)] Inputs strides: [(16, 8), (8, 8)] ``` At `Epoch 0` at line `model.fit(X_train, y_train, nb_epoch=1000, batch_size=50)`. Am I overseeing something obvious in Keras? **EDIT:** I have gone through the question [here](http://stackoverflow.com/questions/30384908/python-keras-neural-network-theano-package-returns-an-error-about-data-dimensi/30386018#30386018) but does not solve my problem
I had the same problem and then found this thread; <https://github.com/fchollet/keras/issues/68> It appears for you to state a final output layer of 2 or for any number of categories the labels need to be of a categorical type where essentially this is a binary vector for each observation e.g a 3 class output vector [0,2,1,0,1,0] becomes [[1,0,0],[0,0,1],[0,1,0],[1,0,0],[0,1,0],[1,0,0]]. The np\_utils.to\_categorical function solved this for me; ``` from keras.utils import np_utils, generic_utils y_train, y_test = [np_utils.to_categorical(x) for x in (y_train, y_test)] ```
Python 2.7 - Why python encode a string when .append() in a list?
32,007,092
6
2015-08-14T09:45:27Z
32,007,326
11
2015-08-14T09:56:57Z
[ "python", "string", "list", "append" ]
My problem String ``` # -*- coding: utf-8 -*- print ("################################") foo = "СТ142Н.0000" print (type(foo)) print("foo: "+foo) foo_l = [] foo_l.append(foo) print ("List: " ) print (foo_l) print ("List decode: ") print([x.decode("UTF-8") for x in foo_l]) print("Pop: "+foo_l.pop()) ``` Print result: ``` ################################ <type 'str'> foo: СТ142Н.0000 List: ['\xd0\xa1\xd0\xa2142\xd0\x9d.0000'] List decode: [u'\u0421\u0422142\u041d.0000'] Pop: СТ142Н.0000 ``` This **works fine** , I just write the string "CT142H.0000" by hand tiping with keyboard (Its the same code) ``` print ("################################") foo = "CT142H.0000" print(type(foo)) print("foo: "+foo) foo_l = [] foo_l.append(foo) print ("List: ") print (foo_l) print ("List decode: ") print([x.decode("UTF-8") for x in foo_l]) print("Pop: "+foo_l.pop()) ``` Print result: ``` ################################ <type 'str'> foo: CT142H.0000 List: ['CT142H.0000'] List decode: [u'CT142H.0000'] Pop: CT142H.0000 ``` Why python encode the first string when I append it into a list? # ----------------------------------------------- This is currently solved, I was worried about thats chars, I put the "result" in JSON and then in a website, finally in the website it works fine! # ----------------------------------------------- I found another solution, but no is a correct solution, cause you will have problems in some cases. ``` json.dumps(list, ensure_ascii=False) ``` Thanks for all!
Because even though they look like normal `C` / `T` / `H` characters they are actually not those characters. They are *Cyrillic* characters. > С - [Cyrillic Capital letter ES](http://www.fileformat.info/info/unicode/char/0421/index.htm) > Т - [Cyrillic Capital letter TE](http://www.fileformat.info/info/unicode/char/0422/index.htm) > Н - [Cyrillic Capital letter EN](http://www.fileformat.info/info/unicode/char/041d/index.htm) You would need to check wherever you got those characters from , on why they are so. On why they got printed using the `\x..` representation, is because when you print a `list` , the `__str__()` method on list is called, but list itself calls `__repr__()` on its elements, and hence you get the internal representation of the strings. You would get similar result if you do - ``` print(repr(foo)) ``` for the first case.
How to efficiently join a list with commas and add "and" before the last element
32,008,737
3
2015-08-14T11:15:11Z
32,008,908
9
2015-08-14T11:24:30Z
[ "python", "list" ]
I've been going through [Automatetheboringstuff](http://automatetheboringstuff.com/) and came across a challenge called Comma Code (end of [chapter 4](https://automatetheboringstuff.com/chapter4/)). You have to write a function that takes a list and print out a string, joining the elements with a comma and adding "and" before the last element. Keeping in mind that I am fairly new to python, or programing for that matter, it was still a manageable task, but the output had a comma before the inserted "and". So I revised the code to clean that up. This is my code: ``` def comma_separator(someList): """The function comma_separator takes a list and joins it into a string with (", ") and adds " and " before the last value.""" if type(someList) is list and bool(someList) is True: return ", ".join(someList[:-1]) + " and " + someList[-1] else: print("Pass a non-empty list as the argument.") ``` Is there a better way to do it? Is there a module that can do this?
You'll have to account for the case where you have just the *one* element: ``` def comma_separator(sequence): if not sequence: return '' if len(sequence) == 1: return sequence[0] return '{} and {}'.format(', '.join(sequence[:-1]), sequence[-1]) ``` Note that `bool(sequence) is True` is a very elaborate way of testing for a non-empty list; simply using `if sequence:` is enough as the `if` statement looks for boolean truth *already*. Arguably, calling the function with anything other than a sequence (something that can be indexed and has a length) should just result in an exception. You generally do not test for types in functions like these. If you *did* have to test for a type, use `isinstance(list, sequence)` to at least allow for subclasses. I'd also make it an error to pass in an empty list. You could turn that exception into a `ValueError`: ``` def comma_separator(sequence): if len(sequence) > 1: return '{} and {}'.format(', '.join(sequence[:-1]), sequence[-1]) try: return sequence[0] except IndexError: raise ValueError('Must pass in at least one element') ``` Demo of the latter: ``` >>> def comma_separator(sequence): ... if len(sequence) > 1: ... return '{} and {}'.format(', '.join(sequence[:-1]), sequence[-1]) ... try: ... return sequence[0] ... except IndexError: ... raise ValueError('Must pass in at least one element') ... >>> comma_separator(['foo', 'bar', 'baz']) 'foo, bar and baz' >>> comma_separator(['foo', 'bar']) 'foo and bar' >>> comma_separator(['foo']) 'foo' >>> comma_separator([]) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 7, in comma_separator ValueError: Must pass in at least one element ```
Is sympy pretty printing broken in new jupyter notebook?
32,010,945
7
2015-08-14T13:11:51Z
32,051,577
11
2015-08-17T13:22:49Z
[ "python", "sympy", "jupyter" ]
I have previously used pretty printing of math in the ipython notebook. After upgrading to jupyter (also upgrades many other ipython-related packages), pretty printing no longer works like before. I use this code in the top of my notebooks to set it up: ``` import sympy as sp sp.init_printing() ``` I have also tried this with the `use_latex=True` and `use_latex='mathjax'` arguments to `init_printing`, but that does not help. In all cases, expressions are printed in plain text after upgrading. See <https://gist.github.com/josteinbf/78dae5085dec0aa19a48#file-sympy_pp-ipynb> for a complete example in the form of a notebook. There are no error messages or warnings, neither in the notebook nor in the console running jupyter. How to fix (or at least debug) this problem?
I also encountered this issue, the fix is to upgrade your `sympy` version. I found that 0.7.6 reproduces the error, but 0.7.7 has it fixed. At the moment this isn't available via `pip`, but can be found via the [github repo](https://github.com/sympy/sympy).
Convert categorical data in pandas dataframe
32,011,359
7
2015-08-14T13:31:50Z
32,011,969
22
2015-08-14T14:01:35Z
[ "python", "pandas" ]
I have a dataframe with this type of data (too many columns): ``` col1 int64 col2 int64 col3 category col4 category col5 category ``` Columns seems like this: ``` Name: col3, dtype: category Categories (8, object): [B, C, E, G, H, N, S, W] ``` I want to convert all value in columns to integer like this: ``` [1, 2, 3, 4, 5, 6, 7, 8] ``` I solved this for one column by this: ``` dataframe['c'] = pandas.Categorical.from_array(dataframe.col3).codes ``` Now I have two columns in my dataframe - old 'col3' and new 'c' and need to drop old columns. That's bad practice. It's work but in my dataframe many columns and I don't want do it manually. How do this pythonic and just cleverly?
First, to convert a Categorical column to its numerical codes, you can do this easier with: `dataframe['c'].cat.codes`. Further, it is possible to select automatically all columns with a certain dtype in a dataframe using `select_dtypes`. This way, you can apply above operation on multiple and automatically selected columns. First making an example dataframe: ``` In [75]: df = pd.DataFrame({'col1':[1,2,3,4,5], 'col2':list('abcab'), 'col3':list('ababb')}) In [76]: df['col2'] = df['col2'].astype('category') In [77]: df['col3'] = df['col3'].astype('category') In [78]: df.dtypes Out[78]: col1 int64 col2 category col3 category dtype: object ``` Then by using `select_dtypes` to select the columns, and then applying `.cat.codes` on each of these columns, you can get the following result: ``` In [80]: cat_columns = df.select_dtypes(['category']).columns In [81]: cat_columns Out[81]: Index([u'col2', u'col3'], dtype='object') In [83]: df[cat_columns] = df[cat_columns].apply(lambda x: x.cat.codes) In [84]: df Out[84]: col1 col2 col3 0 1 0 0 1 2 1 1 2 3 2 0 3 4 0 1 4 5 1 1 ```
Pandas: resample timeseries with groupby
32,012,012
5
2015-08-14T14:04:02Z
32,012,129
8
2015-08-14T14:10:21Z
[ "python", "pandas", "group-by", "time-series" ]
Given the below pandas DataFrame: ``` In [115]: times = pd.to_datetime(pd.Series(['2014-08-25 21:00:00','2014-08-25 21:04:00', '2014-08-25 22:07:00','2014-08-25 22:09:00'])) locations = ['HK', 'LDN', 'LDN', 'LDN'] event = ['foo', 'bar', 'baz', 'qux'] df = pd.DataFrame({'Location': locations, 'Event': event}, index=times) df Out[115]: Event Location 2014-08-25 21:00:00 foo HK 2014-08-25 21:04:00 bar LDN 2014-08-25 22:07:00 baz LDN 2014-08-25 22:09:00 qux LDN ``` I would like resample the data to aggregate it hourly by count while grouping by location to produce a data frame that looks like this: ``` Out[115]: HK LDN 2014-08-25 21:00:00 1 1 2014-08-25 22:00:00 0 2 ``` I've tried various combinations of resample() and groupby() but with no luck. How would I go about this?
You could use a [`pd.TimeGrouper`](http://pandas.pydata.org/pandas-docs/stable/cookbook.html#resampling) to group the DatetimeIndex'ed DataFrame by hour: ``` grouper = df.groupby([pd.TimeGrouper('1H'), 'Location']) ``` use `count` to count the number of events in each group: ``` grouper['Event'].count() # Location # 2014-08-25 21:00:00 HK 1 # LDN 1 # 2014-08-25 22:00:00 LDN 2 # Name: Event, dtype: int64 ``` use [`unstack`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.unstack.html) to move the `Location` index level to a column level: ``` grouper['Event'].count().unstack() # Out[49]: # Location HK LDN # 2014-08-25 21:00:00 1 1 # 2014-08-25 22:00:00 NaN 2 ``` and then use `fillna` to change the NaNs into zeros. --- Putting it all together, ``` grouper = df.groupby([pd.TimeGrouper('1H'), 'Location']) result = grouper['Event'].count().unstack('Location').fillna(0) ``` yields ``` Location HK LDN 2014-08-25 21:00:00 1 1 2014-08-25 22:00:00 0 2 ```
PEP 3130: Difference between switch case and if statement code blocks
32,013,751
8
2015-08-14T15:37:30Z
32,014,023
10
2015-08-14T15:51:04Z
[ "python" ]
In [PEP 3103](https://www.python.org/dev/peps/pep-3103), Guido is discussing adding a switch/case statement to Python with the various schools of thought, methods and objects. In that he makes [this statement](https://www.python.org/dev/peps/pep-3103/#option-2): > Another objection is that the first-use rule allows obfuscated code > like this: > > ``` > def foo(x, y): > switch x: > case y: > print 42 > ``` > > To the untrained eye (not familiar with Python) this code would be equivalent to this: > > ``` > def foo(x, y): > if x == y: > print 42 > ``` > > but that's not what it does (unless it is always called with the same value as the second argument). This has been addressed by suggesting that the case expressions should not be allowed to reference local variables, but this is somewhat arbitrary. I wouldn't have considered myself untrained or unfamiliar with Python but nothing jumps out at me as these two blocks of code being different. What is it that he is referencing that would have made these two pieces of code different in execution?
You need to read the description at the beginning of that section. "The oldest proposal to deal with this is to freeze the dispatch dict the first time the switch is executed." That implies that the value of `y` will be cached when the switch statement first runs, such that if you first call it as: ``` foo(10,10) ``` Subsequent calls, such as `foo(20,20)`, will actually be comparing: ``` switch x: case 10: print 42 ```
Should I always close stdout explicitly?
32,014,310
2
2015-08-14T16:07:47Z
32,014,383
8
2015-08-14T16:12:38Z
[ "python", "c++", "windows", "pipe", "subprocess" ]
I am trying to integrate a small Win32 C++ program which reads from stdin and writes the decoded result (˜128 kbytes)to the output stream. I read entire input into buffer with ``` while (std::cin.get(c)) { } ``` After I write entire output to the stdout. Everything works fine when I run the application from command line eg `test.exe < input.bin > output.bin`, however this small app is supposed to be run from Python. I expect that Python `subprocess.communicate` is supposed to be used, the docs say: > Interact with process: Send data to stdin. Read data from stdout and > stderr, until end-of-file is reached. Wait for process to terminate. So `communicate()` will wait until the end-of-file before waiting my app to finish - is EOF supposed to happen when my application exits? Or should I explicitly do fclose(stderr) and fclose(stdout)?
**Don't close stdout** In the general case, it is actually wrong, since it is possible to register a function with [`atexit()`](http://www.cplusplus.com/reference/cstdlib/atexit/) which tries to write to stdout, and this will break if stdout is closed. When the process terminates, all handles are closed by the operating system automatically. This includes stdout, so you are not responsible for closing it manually. (Technically, the C++ runtime will [normally](http://www.cplusplus.com/reference/cstdlib/exit/) try to flush and close all C++ streams before the OS even has a chance to get involved, but the OS absolutely *must* close any handles which the runtime, for [whatever](http://www.cplusplus.com/reference/cstdlib/quick_exit/) [reason](http://www.cplusplus.com/reference/exception/terminate/), misses.) In specialized circumstances, it may be useful to close standard streams (for example, when daemonizing), but it should be done with great care. It's usually a good idea to redirect to or from the null device (`/dev/null` on Unix, `nul` on Windows) so that code expecting to interact with those streams will still work. On Unix, this is done with [`freopen(3)`](http://linux.die.net/man/3/freopen); Windows has [an equivalent function](https://msdn.microsoft.com/en-us/library/wk2h68td.aspx), but it's part of the POSIX API and may not work well with standard Windows I/O.
Django tutorial, Getting: TypeError at /admin/ argument to reversed() must be a sequence
32,015,044
4
2015-08-14T16:49:26Z
32,015,269
12
2015-08-14T17:04:51Z
[ "python", "django-1.8" ]
I'm working my way through the django tutorial for version 1.8 and I am getting an error that I am stuck on and can't seem to figure out. I thought I was following the tutorial pretty much to the T. I have the following tree set up: `. ├── dj_project │   ├── __init__.py │   ├── __init__.pyc │   ├── settings.py │   ├── settings.pyc │   ├── urls.py │   ├── urls.pyc │   ├── wsgi.py │   └── wsgi.pyc ├── manage.py └── polls ├── admin.py ├── admin.pyc ├── __init__.py ├── __init__.pyc ├── migrations │   ├── 0001_initial.py │   ├── 0001_initial.pyc │   ├── __init__.py │   └── __init__.pyc ├── models.py ├── models.pyc ├── tests.py ├── urls.py ├── urls.pyc ├── views.py └── views.pyc` and have, just as in the tutorial for **polls/urls.py**: ``` from django.conf.urls import url from . import views urlpatterns = { url(r'^$', views.index, name='index'), } ``` and for my **dj\_project/urls.py**: ``` from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^polls/', include('polls.urls')), url(r'^admin/', include(admin.site.urls)), ] ``` and in **polls/views.py** i have: ``` from django.shortcuts import render from django.http import HttpResponse def index(request): return HttpResponse("is there something here?") ``` so when I go to `<mysite>/polls` I see "is there something here", but if I go to `<mysite>/admin`, I get the error: `TypeError at /admin/ argument to reversed() must be a sequence`. If I remove polls from urlpatterns in `dj_project/urls.py`, the admin comes in fine. What might be the problem? I can't seem to figure it out.
In the **polls/urls.py** file, you are declaring the urlpatterns as dict, it must be a list. change the ``` urlpatterns = { url(r'^$', views.index, name='index'), } ``` to: ``` urlpatterns = [ url(r'^$', views.index, name='index'), ] ```
convert strings into python dict
32,017,755
4
2015-08-14T19:56:24Z
32,017,839
8
2015-08-14T20:01:45Z
[ "python", "dictionary" ]
I have a string which is as follows ``` my_string = '"sender" : "md-dgenie", "text" : "your dudegenie code is 6326. welcome to the world of dudegenie! your wish, my command!", "time" : "1439155575925", "name" : "John"' ``` I want to construct a dict from the above string. I tried something as suggested [here](http://stackoverflow.com/questions/5783417/using-python-to-parse-colon-delimited-string-to-an-object) ``` split_text = my_string.split(",") for i in split_text : print i ``` then I got output as shown below: ``` "sender" : "md-dgenie" "text" : "your dudegenie code is 6632. welcome to the world of dudegenie! your wish my command!" ### finds "," here and splits it here too. "time" : "1439155803426" "name" : "p" ``` I want output as key pair values of a dictionary as given below : ``` my_dict = { "sender" : "md-dgenie", "text" : "your dudegenie code is 6632. welcome to the world of dudegenie! your wish, my command!", "time" : "1439155803426", "name" : "p" } ``` Basically I want to skip that "," from the sentence and construct a dict. Any suggestions would be great! Thanks in advance!
Your string is *almost* already a python dict, so you could just enclose it in braces and then [evaluate it](https://docs.python.org/2/library/ast.html#ast.literal_eval) as such: ``` import ast my_dict = ast.literal_eval('{{{0}}}'.format(my_string)) ```
Matplotlib Crashing tkinter Application
32,019,556
2
2015-08-14T22:32:20Z
34,109,240
8
2015-12-05T18:26:16Z
[ "python", "user-interface", "matplotlib", "tkinter", "ttk" ]
I am building an application that embeds a matplotlib figure into the GUI. The problem is that my app is crashing as soon as I add anything from matplotlib into my code (except for the imports, those work as usual). The problem occurs in my class `Solver_App` at `tk.Tk.__init__(self, *args, **kwargs)`. When I run the code, I get a massive error and the app crashes. Here is some of my code: ``` import tkinter as tk from tkinter import ttk import matplotlib from matplotlib import pyplot as plt from mpl_toolkits.mplot3d import Axes3D from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg from matplotlib.figure import Figure # Setting up figures for integration in GUI: fig_3D = plt.figure() fig_2D = plt.figure() a_3D = fig_3D.add_subplot(111, projection="3d") a_2D = fig_2D.add_subplot(111) a_3D.plot_wireframe([1, 2, 3, 4, 5], [1, 3, 7, 6, 4], [1, 2, 3, 4, 5], color="blue") class Solver_App(tk.Tk, ttk.Frame): def __init__(self, *args, **kwargs): tk.Tk.__init__(self, *args, **kwargs) # This is where the app crashes. # Equation frame holds everything related to the input and configuration of the equations. equation_frame = ttk.Frame(self) equation_frame.pack(side="bottom", fill="x", pady=50, padx=50) # More code goes here... # There are more classes with a similar setup as the one above... app = Solver_App() app.mainloop() ``` And here is the massive error I get when running the code: ``` 2015-08-14 15:18:29.142 Python[50796:18837594] -[NSApplication _setup:]: unrecognized selector sent to instance 0x10216a830 2015-08-14 15:18:29.143 Python[50796:18837594] An uncaught exception was raised 2015-08-14 15:18:29.143 Python[50796:18837594] -[NSApplication _setup:]: unrecognized selector sent to instance 0x10216a830 2015-08-14 15:18:29.144 Python[50796:18837594] ( 0 CoreFoundation 0x00007fff9901b03c __exceptionPreprocess + 172 1 libobjc.A.dylib 0x00007fff9436476e objc_exception_throw + 43 2 CoreFoundation 0x00007fff9901e0ad -[NSObject(NSObject) doesNotRecognizeSelector:] + 205 3 CoreFoundation 0x00007fff98f63e24 ___forwarding___ + 1028 4 CoreFoundation 0x00007fff98f63998 _CF_forwarding_prep_0 + 120 5 Tk 0x00000001024ad527 TkpInit + 476 6 Tk 0x0000000102427aca Tk_Init + 1788 7 _tkinter.so 0x00000001006e5f2d Tcl_AppInit + 77 8 _tkinter.so 0x00000001006e30d6 Tkinter_Create + 934 9 Python 0x00000001000e44ce PyEval_EvalFrameEx + 28894 10 Python 0x00000001000e5ced PyEval_EvalCodeEx + 2349 11 Python 0x000000010003e8ba function_call + 186 12 Python 0x000000010000d3c8 PyObject_Call + 104 13 Python 0x00000001000e0cb9 PyEval_EvalFrameEx + 14537 14 Python 0x00000001000e5ced PyEval_EvalCodeEx + 2349 15 Python 0x000000010003e8ba function_call + 186 16 Python 0x000000010000d3c8 PyObject_Call + 104 17 Python 0x000000010002802c method_call + 140 18 Python 0x000000010000d3c8 PyObject_Call + 104 19 Python 0x000000010007b831 slot_tp_init + 81 20 Python 0x0000000100072d14 type_call + 212 21 Python 0x000000010000d3c8 PyObject_Call + 104 22 Python 0x00000001000e1b09 PyEval_EvalFrameEx + 18201 23 Python 0x00000001000e5ced PyEval_EvalCodeEx + 2349 24 Python 0x00000001000e5daf PyEval_EvalCode + 63 25 Python 0x000000010011048e PyRun_FileExFlags + 206 26 Python 0x000000010011083d PyRun_SimpleFileExFlags + 717 27 Python 0x000000010012810e Py_Main + 3262 28 Python 0x0000000100000e32 Python + 3634 29 Python 0x0000000100000c84 Python + 3204 30 ??? 0x0000000000000002 0x0 + 2 ) 2015-08-14 15:18:29.144 Python[50796:18837594] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSApplication _setup:]: unrecognized selector sent to instance 0x10216a830' *** First throw call stack: ( 0 CoreFoundation 0x00007fff9901b03c __exceptionPreprocess + 172 1 libobjc.A.dylib 0x00007fff9436476e objc_exception_throw + 43 2 CoreFoundation 0x00007fff9901e0ad -[NSObject(NSObject) doesNotRecognizeSelector:] + 205 3 CoreFoundation 0x00007fff98f63e24 ___forwarding___ + 1028 4 CoreFoundation 0x00007fff98f63998 _CF_forwarding_prep_0 + 120 5 Tk 0x00000001024ad527 TkpInit + 476 6 Tk 0x0000000102427aca Tk_Init + 1788 7 _tkinter.so 0x00000001006e5f2d Tcl_AppInit + 77 8 _tkinter.so 0x00000001006e30d6 Tkinter_Create + 934 9 Python 0x00000001000e44ce PyEval_EvalFrameEx + 28894 10 Python 0x00000001000e5ced PyEval_EvalCodeEx + 2349 11 Python 0x000000010003e8ba function_call + 186 12 Python 0x000000010000d3c8 PyObject_Call + 104 13 Python 0x00000001000e0cb9 PyEval_EvalFrameEx + 14537 14 Python 0x00000001000e5ced PyEval_EvalCodeEx + 2349 15 Python 0x000000010003e8ba function_call + 186 16 Python 0x000000010000d3c8 PyObject_Call + 104 17 Python 0x000000010002802c method_call + 140 18 Python 0x000000010000d3c8 PyObject_Call + 104 19 Python 0x000000010007b831 slot_tp_init + 81 20 Python 0x0000000100072d14 type_call + 212 21 Python 0x000000010000d3c8 PyObject_Call + 104 22 Python 0x00000001000e1b09 PyEval_EvalFrameEx + 18201 23 Python 0x00000001000e5ced PyEval_EvalCodeEx + 2349 24 Python 0x00000001000e5daf PyEval_EvalCode + 63 25 Python 0x000000010011048e PyRun_FileExFlags + 206 26 Python 0x000000010011083d PyRun_SimpleFileExFlags + 717 27 Python 0x000000010012810e Py_Main + 3262 28 Python 0x0000000100000e32 Python + 3634 29 Python 0x0000000100000c84 Python + 3204 30 ??? 0x0000000000000002 0x0 + 2 ) libc++abi.dylib: terminating with uncaught exception of type NSException ``` I have been referencing code from a tutorial [found here](<http://pythonprogramming.net/how-to-embed-matplotlib-graph-tkinter-gui/>"How to embed a Matplotlib graph to your Tkinter GUI"), but their example seems to work fine. What is causing this problem and how can it be fixed? * I am using Python 3.4, matplotlib 1.4.3, and running Mac OS Yosemite.
You need to set the TkAgg backend explicitly. I could reproduce your bug. With the following code, the problem is resolved. ``` import matplotlib matplotlib.use("TkAgg") from matplotlib import pyplot as plt ``` Note that setting the TkAgg backend *after* importing pyplot does not work either; it crashes too. You need to set it before importing pyplot. (Tested with MPL 1.4.3, tkinter.TkVersion 8.6)
sudo: pip: command not found in CentOS
32,020,594
6
2015-08-15T01:19:37Z
32,020,625
16
2015-08-15T01:27:31Z
[ "python", "centos", "pip" ]
I use CentOS and I installed pip to `/usr/local/python-dir/bin/pip`. I made a link to `/usr/local/bin/pip`. Then I executed `sudo pip install xxx`, it reported an error like this: ``` sudo: pip: command not found ``` I see `$PATH` is all right: ``` /usr/local/bin:/usr/bin:/bin:/usr/local/sbin:/usr/sbin ``` However, I can only execute pip this way: ``` sudo /usr/local/bin/pip install xxx ``` How can I configure PATH or something else? Thanks a lot.
For security reasons, `sudo` does not rely on the `$PATH` set in your environment. There is a `secure_path` option in `/etc/sudoers` that specifies the `PATH` that `sudo` will use for locating binaries. For example: ``` Defaults secure_path = /sbin:/bin:/usr/sbin:/usr/bin ``` Just add `/usr/local/bin` to this PATH, or get used to typing: ``` sudo `which pip` install xxx ```
Reference template variable within Jinja expression
32,024,551
2
2015-08-15T12:07:16Z
32,024,636
7
2015-08-15T12:17:57Z
[ "python", "flask", "jinja2" ]
I have a route defined like this: ``` @app.route('/magic/<filename>') def moremagic(filename): pass ``` And now in a template I want to call that route using `url_for()` like so: ``` <h1>you uploaded {{ name }}<h1> <a href="{{ url_for('/magic/<filename>') }}">Click to see magic happen</a> ``` I have tried: ``` <a href="{{ url_for('/magic', filename={{ name }}) }}">Click to see magic happen</a> ``` That throws a `jinja2.TemplateSyntaxError: expected token ':' got }` Can anyone suggest how to get the `{{ name }}` that appears in the template into the `url_for()` so that when I click I call the correct `app.route`?
Everything inside the `{{ ... }}` is a Python-like expression. You don't need to use another `{{ ... }}` inside that to reference variables. Drop the extra brackets: ``` <h1>you uploaded {{ name }}<h1> <a href="{{ url_for('/magic', filename=name) }}">Click to see magic happen</a> ```
subtracting the mean of each row in numpy with broadcasting
32,030,343
5
2015-08-15T23:23:22Z
32,030,456
9
2015-08-15T23:40:17Z
[ "python", "numpy" ]
I try to subtract the mean of each row of a matrix in numpy using broadcasting but I get an error. Any idea why? Here is the code: ``` from numpy import * X = random.rand(5, 10) Y = X - X.mean(axis = 1) ``` Error: ``` ValueError: operands could not be broadcast together with shapes (5,10) (5,) ``` Thanks!
The `mean` method is a *reduction* operation, meaning it converts a 1-d collection of numbers to a single number. When you apply a reduction to an n-dimensional array along an axis, numpy collapses that dimension to the reduced value, resulting in an (n-1)-dimensional array. In your case, since `X` has shape (5, 10), and you performed a reduction along axis 1, you end up with an array with shape (5,): ``` In [8]: m = X.mean(axis=1) In [9]: m.shape Out[9]: (5,) ``` When you try to subtract this result from `X`, you are trying to subtract an array with shape (5,) from an array with shape (5, 10). These shapes are not compatible for [broadcasting](http://docs.scipy.org/doc/numpy/reference/ufuncs.html#broadcasting). (Take a look at [the description of broadcasting in the User Guide](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html).) For broadcasting to work the way you want, the result of the `mean` operation should be an array with shape (5, 1) (to be compatible with the shape (5, 10)). In recent versions of numpy, the reduction operations, incuding `mean`, have an argument called `keepdims` that tells the function to not collapse the reduced dimension. Instead, a trivial dimension with length 1 is kept: ``` In [10]: m = X.mean(axis=1, keepdims=True) In [11]: m.shape Out[11]: (5, 1) ``` With older versions of numpy, you can use `reshape` to restore the collapsed dimension: ``` In [12]: m = X.mean(axis=1).reshape(-1, 1) In [13]: m.shape Out[13]: (5, 1) ``` So, depending on your version of numpy, you can do this: ``` Y = X - X.mean(axis=1, keepdims=True) ``` or this: ``` Y = X - X.mean(axis=1).reshape(-1, 1) ```
Replace single quotes with double with exclusion of some elements
32,031,353
11
2015-08-16T02:47:08Z
32,529,140
8
2015-09-11T17:35:31Z
[ "python", "regex", "replace", "nlp" ]
I want to replace all single quotes in the string with double with the exception of occurrences such as "n't", "'ll", "'m" etc. ``` input="the stackoverflow don\'t said, \'hey what\'" output="the stackoverflow don\'t said, \"hey what\"" ``` Code 1:(@<https://stackoverflow.com/users/918959/antti-haapala>) ``` def convert_regex(text): return re.sub(r"(?<!\w)'(?!\w)|(?<!\w)'(?=\w)|(?<=\w)'(?!\w)", '"', text) ``` There are 3 cases: ' is NOT preceded and is NOT followed by a alphanumeric character; or is not preceded, but followed by an alphanumeric character; or is preceded and not followed by an alphanumeric character. Issue: That doesn't work on words that end in an apostrophe, i.e. most possessive plurals, and it also doesn't work on informal abbreviations that start with an apostrophe. Code 2:(@<https://stackoverflow.com/users/953482/kevin>) ``` def convert_text_func(s): c = "_" #placeholder character. Must NOT appear in the string. assert c not in s protected = {word: word.replace("'", c) for word in ["don't", "it'll", "I'm"]} for k,v in protected.iteritems(): s = s.replace(k,v) s = s.replace("'", '"') for k,v in protected.iteritems(): s = s.replace(v,k) return s ``` Too large set of words to specify, as how can one specify persons' etc. Please help. **Edit 1:** I am using @anubhava's brillant answer. I am facing this issue. Sometimes, there language translations which the approach fail. Code= ``` text=re.sub(r"(?<!s)'(?!(?:t|ll|e?m|s|d|ve|re|clock)\b)", '"', text) ``` Problem: In text, 'Kumbh melas' melas is a Hindi to English translation not plural possessive nouns. ``` Input="Similar to the 'Kumbh melas', celebrated by the banks of the holy rivers of India," Output=Similar to the "Kumbh melas', celebrated by the banks of the holy rivers of India, Expected Output=Similar to the "Kumbh melas", celebrated by the banks of the holy rivers of India, ``` I am looking maybe to add a condition that somehow fixes it. Human-level intervention is the last option. **Edit 2:** Naive and long approach to fix: ``` def replace_translations(text): d = enchant.Dict("en_US") words=tokenize_words(text) punctuations=[x for x in string.punctuation] for i,word in enumerate(words): print i,word if(i!=len(words) and word not in punctuations and d.check(word)==False and words[i+1]=="'"): text=text.replace(words[i]+words[i+1],words[i]+"\"") return text ``` Are there any corner cases I am missing or are there any better approaches?
## First attempt You can also use this regex: ``` (?:(?<!\w)'((?:.|\n)+?'?)'(?!\w)) ``` [DEMO IN REGEX101](https://regex101.com/r/rG6gN0/3) This regex match whole sentence/word with both quoting marks, from beginning and end, but also campure the content of quotation inside group nr 1, so you can replace matched part with `"\1"`. * `(?<!\w)` - negative lookbehind for non-word character, to exclude words like: "you'll", etc., but to allow the regex to match quatations after characters like `\n`,`:`,`;`,`.` or `-`,etc. The assumption that there will always be a whitespace before quotation is risky. * `'` - single quoting mark, * `(?:.|\n)+?'?)` - non capturing group: one or more of any character or new line (to match multiline sentences) with lazy quantifire (to avoid matching from first to last single quoting mark), followed by optional single quoting sing, if there would be two in a row * `'(?!\w)` - single quotes, followed by non-word character, to exclude text like "i'm", "you're" etc. where quoting mark is beetwen words, ## The s' case However it still has problem with matching sentences with apostrophes occurs after word ending with s, like: `'the classes' hours'`. I think it is impossible to distinguish with regex when `s` followed by `'` should be treated as end of quotation, or as or `s` with apostrophes. But I figured out a kind of limited work around for this problem, with regex: ``` (?:(?<!\w)'((?:.|\n)+?'?)(?:(?<!s)'(?!\w)|(?<=s)'(?!([^']|\w'\w)+'(?!\w)))) ``` [DEMO IN REGEX101](https://regex101.com/r/rG6gN0/8) [PYTHON IMPLEMENTATION](https://ideone.com/EDD2uD) with additional alternative for cases with `s'`: `(?<!s)'(?!\w)|(?<=s)'(?!([^']|\w'\w)+'(?!\w)` where: * `(?<!s)'(?!\w)` - if there is no `s` before `'`, match as regex above (first attempt), * `(?<=s)'(?!([^']|\w'\w)+'(?!\w)` - if there is `s` before `'`, end a match on this `'` only if there is no other `'` followed by non-word character in following text, before end or before another `'` (but only `'` preceded by letter other than `s`, or opening of next quotaion). The `\w'\w` is to include in such match a `'` wich are between letters, like in `i'm`, etc. this regex should match wrong only it there is couple `s'` cases in a row. Still, it is far from perfect solution. ## Flaws of \w Also, using `\w` there is always chance that `'` would occur after sybol or non-`[a-zA-Z_0-9]` but still letter character, like some local language character, and then it will be treated as beginning of a quatation. It could be avoided by replacing `(?<!\w)` and `(?!\w)` with `(?<!\p{L})` and `(?!\p{L})` or something like `(?<=^|[,.?!)\s])`, etc., positive lookaround for characters wich can occour in sentence before quatation. However a list could be quite long.
Select everything but a list of columns from pandas dataframe
32,032,836
7
2015-08-16T07:29:28Z
32,032,989
8
2015-08-16T07:53:45Z
[ "python", "pandas" ]
Is it possible to select the negation of a given list from pandas dataframe?. For instance, say I have the following dataframe ``` T1_V2 T1_V3 T1_V4 T1_V5 T1_V6 T1_V7 T1_V8 1 15 3 2 N B N 4 16 14 5 H B N 1 10 10 5 N K N ``` and I want to get out all columns but column T1\_V6. I would normally do that this way: ``` df = df[["T1_V2","T1_V3","T1_V4","T1_V5","T1_V7","T1_V8"]] ``` My question is on whether there is a way to this the other way around, something like this ``` df = df[!["T1_V6"]] ```
If your column names are strings you can do it like this: ``` df[df.columns - ["T1_V6"]] ``` --- However, the "set minus" doesn't work for numeric column names so this is probably the preferred way to do it (works also with numeric column names): ``` df[df.columns.difference(["T1_V6"])] ```
Why is pandas.to_datetime slow for non standard time format such as '2014/12/31'
32,034,689
6
2015-08-16T11:42:40Z
32,034,914
8
2015-08-16T12:09:54Z
[ "python", "csv", "pandas", "python-datetime", "string-to-datetime" ]
I have a .csv file in such format ``` timestmp, p 2014/12/31 00:31:01:9200, 0.7 2014/12/31 00:31:12:1700, 1.9 ... ``` and when read via `pd.read_csv` and convert the time str to datetime using `pd.to_datetime`, the performance drops dramatically. Here is a minimal example. ``` import re import pandas as pd d = '2014-12-12 01:02:03.0030' c = re.sub('-', '/', d) %timeit pd.to_datetime(d) %timeit pd.to_datetime(c) %timeit pd.to_datetime(c, format="%Y/%m/%d %H:%M:%S.%f") ``` and the performances are: ``` 10000 loops, best of 3: 62.4 µs per loop 10000 loops, best of 3: 181 µs per loop 10000 loops, best of 3: 82.9 µs per loop ``` so, how could I improve the performance of `pd.to_datetime` when reading date from a csv file?
This is because pandas falls back to `dateutil.parser.parse` for parsing the strings when it has a non-default format or when no `format` string is supplied (this is much more flexible, but also slower). As you have shown above, you can improve the performance by supplying a `format` string to `to_datetime`. Or another option is to use `infer_datetime_format=True` --- Apparently, the `infer_datetime_format` cannot infer when there are microseconds. With an example without those, you can see a large speed-up: ``` In [28]: d = '2014-12-24 01:02:03' In [29]: c = re.sub('-', '/', d) In [30]: s_c = pd.Series([c]*10000) In [31]: %timeit pd.to_datetime(s_c) 1 loops, best of 3: 1.14 s per loop In [32]: %timeit pd.to_datetime(s_c, infer_datetime_format=True) 10 loops, best of 3: 105 ms per loop In [33]: %timeit pd.to_datetime(s_c, format="%Y/%m/%d %H:%M:%S") 10 loops, best of 3: 99.5 ms per loop ```
Python order a dict by key value
32,036,125
3
2015-08-16T14:23:15Z
32,036,142
7
2015-08-16T14:25:16Z
[ "python", "sorting", "dictionary" ]
I've been trying to order my dict that has keys with this format: `"0:0:0:0:0:x"` where x is the variable that get incremented while filling the dict. Since dictionaries doesn't insert in order, and I need the key-value values to be showed ordered, I tried to use ``` collections.OrderedDict(sorted(observation_values.items()) ``` where observation\_values is my dict, but values are ordered caring about the first number, like this: ``` "0:0:0:0:0:0": [0.0], "0:0:0:0:0:1": [0.0], "0:0:0:0:0:10": [279.5], "0:0:0:0:0:100": [1137.8], "0:0:0:0:0:101": [1159.4], "0:0:0:0:0:102": [1180.3], "0:0:0:0:0:103": [1193.6]... ``` till `"0:0:0:0:0:109"` then back to `"0:0:0:0:0:11"` and then again `"0:0:0:0:0:110"`, `..:111`, `..:112`. How can I avoid using only most significant numbers to order?
You are sorting strings, so they are sorted lexicographically, not numerically. Give `sorted()` a custom sort key: ``` sortkey = lambda i: [int(e) for e in i[0].split(':')] collections.OrderedDict(sorted(observation_values.items(), key=sortkey)) ``` This takes the key of each key-value pair (`i[0]`), splitting it on the `:` colon and converting each number in that key to an integer. Now the keys will be sorted lexicographically across the parts, and numerically per part; now `0:0:0:0:0:1` sorts before `0:0:0:0:0:100` and both sort before `0:0:0:0:1:0`.
How can i remove extra "s" from django admin panel?
32,047,686
3
2015-08-17T10:07:10Z
32,047,877
7
2015-08-17T10:16:58Z
[ "python", "django", "django-models" ]
I am really very much irritated by the extra "s" added after my class name in django admin eg class 'About' in my model.py becomes 'Abouts' in admin section. And i want it not to add extra 's'. Here is my model.py file- ``` class About(models.Model): about_desc = models.TextField(max_length=5000) def __unicode__(self): # __str__ on Python 3 return str(self.about_desc) ``` Please anybody suggest me how django can solve my problem.
You can add another class called `Meta` in your model to specify plural display name. For example, if the model's name is `Category`, the admin displays `Categorys`, but by adding the `Meta` class, we can change it to `Categories`. I have changed your code to fix the issue: ``` class About(models.Model): about_desc = models.TextField(max_length=5000) def __unicode__(self): # __str__ on Python 3 return str(self.about_desc) class Meta: verbose_name_plural = "about" ``` For more `Meta` options, refer to <https://docs.djangoproject.com/en/1.8/ref/models/options/>
Python float and int behavior
32,052,573
3
2015-08-17T14:09:31Z
32,052,647
10
2015-08-17T14:12:55Z
[ "python", "floating-point-conversion" ]
when i try to check whether float variable contain exact integer value i get the folowing strange behaviour. My code : ``` x = 1.7 print x, (x == int(x)) x += 0.1 print x, (x == int(x)) x += 0.1 print x, (x == int(x)) x += 0.1 print x, (x == int(x)) print "----------------------" x = **2.7** print x, (x == int(x)) x += 0.1 print x, (x == int(x)) x += 0.1 print x, (x == int(x)) x += 0.1 print x, (x == int(x)) ``` I get the folowing strange output (last line is the problem): ``` 1.7 False 1.8 False 1.9 False 2.0 True ---------------------- 2.7 False 2.8 False 2.9 False 3.0 False ``` Any idea why `2.0` is `true` and `3.0` is `false` ?
the problem is not with conversion but with **addition**. ``` int(3.0) == 3.0 ``` returns **True** as expected. The probelm is that floating points are not infinitely accurate, and you cannot expect 2.7 + 0.1 \* 3 to be 3.0 ``` >>> 2.7 + 0.1 + 0.1 + 0.1 3.0000000000000004 >>> 2.7 + 0.1 + 0.1 + 0.1 == 3.0 False ``` As suggested by @SuperBiasedMan it is worth noting that in OPs approach the problem was somehow hidden due to the use of printing (string conversion) which simplifies data representation to maximize readability ``` >>> print 2.7 + 0.1 + 0.1 + 0.1 3.0 >>> str(2.7 + 0.1 + 0.1 + 0.1) '3.0' >>> repr(2.7 + 0.1 + 0.1 + 0.1) '3.0000000000000004' ```
Python - how to run multiple coroutines concurrently using asyncio?
32,054,066
9
2015-08-17T15:21:54Z
32,056,300
13
2015-08-17T17:25:31Z
[ "python", "python-3.x", "websocket", "python-asyncio" ]
I'm using the [`websockets`](https://github.com/aaugustin/websockets) library to create a websocket server in Python 3.4. Here's a simple echo server: ``` import asyncio import websockets @asyncio.coroutine def connection_handler(websocket, path): while True: msg = yield from websocket.recv() if msg is None: # connection lost break yield from websocket.send(msg) start_server = websockets.serve(connection_handler, 'localhost', 8000) asyncio.get_event_loop().run_until_complete(start_server) asyncio.get_event_loop().run_forever() ``` Let's say we – additionally – wanted to send a message to the client whenever some event happens. For simplicity, let's send a message periodically every 60 seconds. How would we do that? I mean, because `connection_handler` is constantly waiting for incoming messages, the server can only take action *after* it has received a message from the client, right? What am I missing here? Maybe this scenario requires a framework based on events/callbacks rather than one based on coroutines? [Tornado](http://www.tornadoweb.org/en/stable/websocket.html)?
**TL;DR** Use [`asyncio.ensure_future()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.ensure_future) to run several coroutines concurrently. --- > Maybe this scenario requires a framework based on events/callbacks rather than one based on coroutines? Tornado? No, you don't need any other framework for this. The whole idea the asynchronous application vs synchronous is that it doesn't block, while waiting for result. It doesn't matter how it is implemented, using coroutines or callbacks. > I mean, because connection\_handler is constantly waiting for incoming messages, the server can only take action after it has received a message from the client, right? What am I missing here? In synchronous application you will write something like `msg = websocket.recv()`, which would block whole application until you receive message (as you described). But in the asynchronous application it's completely different. When you do `msg = yield from websocket.recv()` you say something like: suspend execution of `connection_handler()` until `websocket.recv()` will produce something. Using `yield from` inside coroutine returns control back to the event loop, so some other code can be executed, while we're waiting for result of `websocket.recv()`. Please, refer to [documentation](https://docs.python.org/3/library/asyncio-task.html#coroutines) to better understand how coroutines work. > Let's say we – additionally – wanted to send a message to the client whenever some event happens. For simplicity, let's send a message periodically every 60 seconds. How would we do that? You can use [`asyncio.async()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.async) to run as many coroutines as you want, before executing blocking call for [starting event loop](https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.BaseEventLoop.run_forever). ``` import asyncio import websockets # here we'll store all active connections to use for sending periodic messages connections = [] @asyncio.coroutine def connection_handler(connection, path): connections.append(connection) # add connection to pool while True: msg = yield from connection.recv() if msg is None: # connection lost connections.remove(connection) # remove connection from pool, when client disconnects break else: print('< {}'.format(msg)) yield from connection.send(msg) print('> {}'.format(msg)) @asyncio.coroutine def send_periodically(): while True: yield from asyncio.sleep(5) # switch to other code and continue execution in 5 seconds for connection in connections: print('> Periodic event happened.') yield from connection.send('Periodic event happened.') # send message to each connected client start_server = websockets.serve(connection_handler, 'localhost', 8000) asyncio.get_event_loop().run_until_complete(start_server) asyncio.async(send_periodically()) # before blocking call we schedule our coroutine for sending periodic messages asyncio.get_event_loop().run_forever() ``` Here is an example client implementation. It asks you to enter name, receives it back from the echo server, waits for two more messages from server (which are our periodic messages) and closes connection. ``` import asyncio import websockets @asyncio.coroutine def hello(): connection = yield from websockets.connect('ws://localhost:8000/') name = input("What's your name? ") yield from connection.send(name) print("> {}".format(name)) for _ in range(3): msg = yield from connection.recv() print("< {}".format(msg)) yield from connection.close() asyncio.get_event_loop().run_until_complete(hello()) ``` Important points: 1. In Python 3.4.4 `asyncio.async()` was renamed to [`asyncio.ensure_future()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.ensure_future). 2. There are special methods for scheduling [delayed calls](https://docs.python.org/3/library/asyncio-eventloop.html#delayed-calls), but they don't work with coroutines.
Scrapy with TOR (Windows)
32,054,558
5
2015-08-17T15:47:49Z
32,188,821
8
2015-08-24T18:05:41Z
[ "python", "windows", "scrapy", "tor" ]
I created a Scrapy project with several spiders to crawl some websites. Now I want to use TOR to: 1. Hide my ip from the crawled servers; 2. Associate my requests to different ips, simulating accesses from different users. I have read some info about this, for example: [using tor with scrapy framework](http://stackoverflow.com/questions/8084423/using-tor-with-scrapy-framework), [How to connect to https site with Scrapy via Polipo over TOR?](http://stackoverflow.com/questions/17820824/how-to-connect-to-https-site-with-scrapy-via-polipo-over-tor?rq=1) The answers from these links weren't helpful to me. What are the steps that I should take to make Scrapy work properly with TOR? EDIT 1: Considering answer 1, I started by installing TOR. As I am using Windows I downloaded the TOR Expert Bundle (<https://www.torproject.org/dist/torbrowser/5.0.1/tor-win32-0.2.6.10.zip>) and read the chapter about how to configure TOR as a relay (<https://www.torproject.org/docs/tor-doc-windows.html.en>). Unfortunately there is little or any information about how to do it on Windows. If I unzip the downloaded archive and run the file Tor\Tor.exe nothing happens. However, I can see in the Task Manager that a new process is instantiated. I don't know what is the best way to proceed from here.
After a lot of research, I found a way to setup my Scrapy project to work with TOR on Windows OS: 1. Download TOR Expert Bundle for Windows (1) and unzip the files to a folder (ex. \tor-win32-0.2.6.10). 2. The recent TOR's versions for Windows don't come with a graphical user interface (2). It is probably possible to setup TOR only through config files and cmd commands but for me, the best option was to use Vidalia. Download it (3) and unzip the files to a folder (ex. vidalia-standalone-0.2.21-win32). Run "Start Vidalia.exe" and go to Settings. On the "General" tab, point Vidalia to TOR (\tor-win32-0.2.6.10\Tor\tor.exe). 3. Check on "Advanced" tab and "Tor Configuration File" section the torrc file. I have the next ports configured: ControlPort 9151 SocksPort 9050 4. Click Start Tor on the Vidalia Control Panel UI. After some processing you should se on the status the message "Connected to the Tor network!". 5. Download Polipo proxy (4) and unzip the files to a folder (ex. polipo-1.1.0-win32). Read about this proxy on the link 5. 6. Edit the file config.sample and add the next lines to it (in the beginning of the file, for example): socksParentProxy = "localhost:9050" socksProxyType = socks5 diskCacheRoot = "" 7. Start Polipo through cmd. Go to the folder where you unzipped the files and enter the next command "polipo.exe -c config.sample". 8. Now you have Polipo and TOR up and running. Polipo will redirect any request to TOR through port 9050 with SOCKS protocol. Polipo will receive any HTTP request to redirect trough port 8123. 9. Now you can follow the rest of the tutorial "Torifying Scrapy Project On Ubuntu" (6). Continue in the step where the tutorial explains how to test the TOR/Polipo communications. Links: 1. <https://www.torproject.org/download/download.html.en> 2. <http://tor.stackexchange.com/questions/6496/tor-expert-bundle-on-windows-no-installation-instructions> 3. <https://people.torproject.org/~erinn/vidalia-standalone-bundles/> 4. <http://www.pps.univ-paris-diderot.fr/~jch/software/files/polipo/> 5. <http://www.pps.univ-paris-diderot.fr/~jch/software/polipo/tor.html> 6. <http://blog.privatenode.in/torifying-scrapy-project-on-ubuntu/>
HTTPSHandler error while installing pip with python 2.7.9
32,054,580
8
2015-08-17T15:48:42Z
32,068,819
11
2015-08-18T09:39:59Z
[ "python", "installation", "openssl", "pip", "virtualenv" ]
Hi I am trying to install pip with python 2.7.9 but keep getting following error. I want to create python virtual env. ``` python get-pip.py Traceback (most recent call last): File "get-pip.py", line 17767, in <module> main() File "get-pip.py", line 162, in main bootstrap(tmpdir=tmpdir) File "get-pip.py", line 82, in bootstrap import pip File "/tmp/tmp_Tfw2V/pip.zip/pip/__init__.py", line 15, in <module> File "/tmp/tmp_Tfw2V/pip.zip/pip/vcs/subversion.py", line 9, in <module> File "/tmp/tmp_Tfw2V/pip.zip/pip/index.py", line 30, in <module> File "/tmp/tmp_Tfw2V/pip.zip/pip/wheel.py", line 35, in <module> File "/tmp/tmp_Tfw2V/pip.zip/pip/_vendor/distlib/scripts.py", line 14, in <module> File "/tmp/tmp_Tfw2V/pip.zip/pip/_vendor/distlib/compat.py", line 31, in <module> ImportError: cannot import name HTTPSHandler ``` I guess this is something related to openssl libraries. Since i don't have sudo access I would like to install it in home folder from source. Any idea how to do it?
Make sure you have openssl and openssl-devel installed before you build Python 2.7 ``` yum install openssl openssl-devel ``` or ``` apt-get install openssl openssl-devel ``` or (for Debian): ``` apt-get install libssl-dev ``` To rebuild Python ``` cd ~ wget https://www.python.org/ftp/python/2.7.9/Python-2.7.9.tgz tar xzf Python-2.7.9.tgz cd Python-2.7.9 ./configure make install ``` Then the `python get-pip.py` should work.
Exiting Python Debugger ipdb
32,055,062
13
2015-08-17T16:13:11Z
32,096,090
16
2015-08-19T12:53:42Z
[ "python", "debugging", "workflow", "exit", "ipdb" ]
I use ipdb fairly often in a way to just jump to a piece of code that is *isolated* i.e. it is hard to write a real script that uses it. Instead I write a minimal test case with mocking and jump into it. Exemplary for the workflow: ``` def func(): ... import ipdb ipdb.set_trace() ... def test_case(): ... func() ... ``` Then, invoke ``` py.test test_file.py -s -k test_case ``` Now, usually I just check one variable or two, and then want to quit. Change the code and do it over again. How do I quit? The manual says `q` quits the debugger. It doesn't (really). You have to quit a few times before the debugger actually terminates. The same behavior for Ctrl-C and Ctrl-D (with the additional frustration that hitting Ctrl-D several times eventually quits the terminal, too). Is there a smart way to force quit? Is this workflow even sensible? What is the standard way to do it?
I put the following in my `.pdbrc` ``` import os alias kk os.system('kill -9 %d' % os.getpid()) ``` `kk` kills the debugger and (the process that trigger the debugger).
Python3 AttributeError: 'list' object has no attribute 'clear'
32,055,768
4
2015-08-17T16:52:22Z
32,055,799
9
2015-08-17T16:54:45Z
[ "python", "list", "python-3.x", "attributeerror", "python-3.2" ]
I am working on a Linux machine with Python version 3.2.3. Whenever I try to do `list.clear()` I get an exception ``` >>> l = [1, 2, 3, 4, 5, 6, 7] >>> l.clear() Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'list' object has no attribute 'clear' ``` At the same time on my Mac with Python 3.4.3 the same code runs smoothly. Can it be due to the difference between Python versions or is there something I'm missing?
`list.clear` was added in Python 3.3. See the [4.6.3. Mutable Sequence Types](https://docs.python.org/3/library/stdtypes.html?highlight=clear#mutable-sequence-types): > *New in version 3.3*: *clear()* and *copy()* methods. > > ... > > *s.clear()* removes all items from *s* (same as *del s[:]*) From the [issue 10516](http://bugs.python.org/issue10516): > **Terry J. Reedy** > > Add *list.clear()* method with obvious semantics. > > Pro: > > 1. parallel to *set*/*dict*/*defaultdict*/*deque.clear()*, usable in generic mutable collection function; > 2. makes it easier to switch between list and other collection class; > 3. current alternatives are not as obvious; > 4. some people seem to expect it. > > Anti: > > 1. unneeded; *del l[:]* or *l[:]=[]* do same already. > > Guido: (python-ideas list, 'Set Syntax' thread, today) "FWIW I'm fine > with adding list.clear() to 3.3." > > **Raymond Hettinger** > > Guido approved these both in a thread earlier this year. The reasoning for *copy()* was the same as for *clear()*, some folks > couldn't cope with: *b = a[:]*
Python: Is there any difference between "del a" and "del(a)"?
32,060,273
9
2015-08-17T21:50:14Z
32,060,347
10
2015-08-17T21:55:37Z
[ "python" ]
As far as I can tell, both `del a` and `del(a)` seems to work with the same effect. If that's the case, why would Python allow `del` to exist both as a statement and a function?
`del` is always a statement. Using parenthesis doesn't mean you're making a function call, but you're grouping expressions. `(1)` is just the same as `1`.
Probability function to generate values instead of calling random
32,065,067
3
2015-08-18T06:29:08Z
32,065,189
9
2015-08-18T06:35:56Z
[ "python", "statistics" ]
In my python code there are a few places where I have a population where there is `x` chance of something happening to each individual, but I just need the amount of people affected. ``` amount = 0 population = 500 chance = 0.05 for p in range(population): if random.random() < chance: amount += 1 ``` My gut tells me there must be a less brute force way to do this than calling random.random() 500 times. Some math or stats terminology or function that I don't know. ``` amount = population * chance * random.random() ``` is too variable for what I need.
The distribution of the sum of *n* 0-1 random variables, each with probability *p* is called a [binomial distribution](https://en.wikipedia.org/wiki/Binomial_distribution) with parameters *n* and *p*. I believe [`numpy.random.binomial`](https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.binomial.html) will do what you want.
Python Matplotlib - Impose shape dimensions with Imsave
32,069,041
6
2015-08-18T09:49:42Z
32,127,060
9
2015-08-20T19:47:31Z
[ "python", "matplotlib", "shape" ]
I plot a great number of pictures with matplotlib in order to make video with it but when i try to make the video i saw the shape of the pictures is not the same in time...It induces some errors. Is there a command to impose the shape of the output when i use Imsave? You can see a part of my code : ``` plt.close() fig, axes = plt.subplots(nrows=2, ncols=3) ###Figures composante X plt.tight_layout(pad=0.05, w_pad=0.001, h_pad=2.0) ax1 = plt.subplot(231) # creates first axis ax1.set_xticks([0,2000,500,1000,1500]) ax1.set_yticks([0,2000,500,1000,1500]) ax1.tick_params(labelsize=8) i1 = ax1.imshow(U,cmap='hot',extent=(X.min(),2000,Y.min(),2000), vmin=U.min(), vmax=U.max()) cb1=plt.colorbar(i1,ax=ax1,ticks=[U.min(),(U.min()+U.max())/2., U.max()],fraction=0.046, pad=0.04,format='%.2f') cb1.ax.tick_params(labelsize=8) ax1.set_title("$ \mathrm{Ux_{mes} \/ (pix)}$", y=1.05, fontsize=12) ax2 = plt.subplot(232) # creates second axis ax2.set_xticks([0,2000,500,1000,1500]) ax2.set_yticks([0,2000,500,1000,1500]) i2=ax2.imshow(UU,cmap='hot',extent=(X.min(),2000,Y.min(),2000), vmin=UU.min(), vmax=UU.max()) ax2.set_title("$\mathrm{Ux_{cal} \/ (pix)}$", y=1.05, fontsize=12) ax2.set_xticklabels([]) ax2.set_yticklabels([]) cb2=plt.colorbar(i2,ax=ax2,fraction=0.046, pad=0.04,ticks=[UU.min(),(UU.min()+UU.max())/2.,UU.max()],format='%.2f') cb2.ax.tick_params(labelsize=8) ax3 = plt.subplot(233) # creates first axis ax3.set_xticks([0,2000,500,1000,1500]) ax3.set_yticks([0,2000,500,1000,1500]) i3 = ax3.imshow(resU,cmap='hot',extent=(X.min(),2000,Y.min(),2000),vmin=0.,vmax=0.1) ax3.imshow(scipy.ndimage.filters.gaussian_filter(masquey2, 3),cmap='hot',alpha=0.2,extent=(X.min(),2000,Y.min(),2000)) ax3.set_title("$\mathrm{\mid \/ Ux_{mes} - Ux_{cal}\mid \/ (pix)}$ ", y=1.05, fontsize=12) cb3=plt.colorbar(i3,ax=ax3,fraction=0.046, pad=0.04,ticks=[0.,0.1],format='%.2f') ax3.set_xticklabels([]) ax3.set_yticklabels([]) cb3.ax.tick_params(labelsize=8) plt.gcf().tight_layout() ``` I m using "plt.gcf().tight\_layout()" in order to have figures which dont superimpose...
If you're saving figures out to images on disk, you can do something like this to set the size: ``` fig.set_size_inches(10, 15) fig.savefig('image.png', dpi=100) ``` If you just want to display at a certain size you can try: ``` plt.figure(figsize=(1,1)) ``` Where the dimensions are set in inches. Here is an explanation of parameters that can be set with Figures: <http://matplotlib.org/api/figure_api.html#matplotlib.figure.Figure>
How do i check if input is a date
32,071,978
2
2015-08-18T12:06:20Z
32,072,044
7
2015-08-18T12:09:34Z
[ "python", "function" ]
I want to define a function that will check if input is a date. If input is not a date i want it to say: sorry try again and if it is a date i need a program to stop. I tried many things but none of them worked and I don't have codes of what I tried because I deleted the function.
Use `datetime` library: ``` import datetime def validate(date_text): try: datetime.datetime.strptime(date_text, '%Y-%m-%d') except ValueError: raise ValueError("Incorrect data format, should be YYYY-MM-DD") ``` than validate like that: ``` validate('2015-08-18') ```
Python 3 In Memory Zipfile Error. string argument expected, got 'bytes'
32,075,135
6
2015-08-18T14:23:34Z
32,075,279
11
2015-08-18T14:29:24Z
[ "python", "python-3.x" ]
I have the following code to create an in memory zip file that throws an error running in Python 3. ``` from io import StringIO from pprint import pprint import zipfile in_memory_data = StringIO() in_memory_zip = zipfile.ZipFile( in_memory_data, "w", zipfile.ZIP_DEFLATED, False) in_memory_zip.debug = 3 filename_in_zip = 'test_filename.txt' file_contents = 'asdf' in_memory_zip.writestr(filename_in_zip, file_contents) ``` To be clear this is only a Python 3 problem. I can run the code fine on Python 2. To be exact I'm using Python 3.4.3. The stack trace is below: ``` Traceback (most recent call last): File "in_memory_zip_debug.py", line 14, in <module> in_memory_zip.writestr(filename_in_zip, file_contents) File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/zipfile.py", line 1453, in writestr self.fp.write(zinfo.FileHeader(zip64)) TypeError: string argument expected, got 'bytes' Exception ignored in: <bound method ZipFile.__del__ of <zipfile.ZipFile object at 0x1006e1ef0>> Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/zipfile.py", line 1466, in __del__ self.close() File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/zipfile.py", line 1573, in close self.fp.write(endrec) TypeError: string argument expected, got 'bytes' ```
`ZipFile` writes its data as bytes, not strings. This means you'll have to use `BytesIO` instead of `StringIO` on Python 3. The distinction between bytes and strings is new in Python 3. The [six](https://pythonhosted.org/six/) compatibility library has a `BytesIO` class for Python 2 if you want your program to be compatible with both.
Flask-Session extension vs default session
32,084,646
7
2015-08-19T00:26:46Z
32,085,122
9
2015-08-19T01:29:51Z
[ "python", "flask" ]
I'm using: ``` from flask import session @app.route('/') def main_page(): if session.get('key'): print ("session exist" + session.get('key')) else: print ("could not find session") session['key'] = '34544646###########' return render_template('index.html') ``` I don't have the Flask-Session extension installed but this still works fine. I'm trying to understand why and when is that extension imp to me. As far as I see, the default session works well for me.
The difference is in where the session data is stored. Flask's sessions are *client-side* sessions. Any data that you write to the session is written to a cookie and sent to the client to store. The client will send the cookie back to the server with every request, that is how the data that you write in the session remains available in subsequent requests. The data stored in the cookie is cryptographically signed to prevent any tampering. The `SECRET_KEY` setting from your configuration is used to generate the signature, so the data in your client-side sessions is secure as long as your secret key is kept private. Note that *secure* in this context means that the data in the session cannot be modified by a potential attacker. The data is still visible to anybody who knows how to look, so you should never write sensitive information in a client-side session. Flask-Session and Flask-KVSession are two extensions for Flask that implement *server-side* sessions. These sessions work exactly in the same way as the Flask native sessions from the point of view of your application, but they store the data in the server. The data is never sent to the client, so there is a bit of increased security. The client still receives a signed cookie, but the only data in the cookie is a *session ID* that references the file or database index in the server where the data is stored.
Compact way of writing (a + b == c or a + c == b or b + c == a)
32,085,675
133
2015-08-19T02:40:12Z
32,085,730
40
2015-08-19T02:46:22Z
[ "python", "boolean" ]
Is there a more compact or pythonic way to write the boolean expression ``` a + b == c or a + c == b or b + c == a ``` I came up with ``` a + b + c in (2*a, 2*b, 2*c) ``` but that is a little strange.
If you know you're only dealing with positive numbers, this will work, and is pretty clean: ``` a, b, c = sorted((a, b, c)) if a + b == c: do_stuff() ``` As I said, this only works for positive numbers; but if you *know* they're going to be positive, this is a very readable solution IMO, even directly in the code as opposed to in a function. You could do this, which might do a bit of repeated computation; but you didn't specify performance as your goal: ``` from itertools import permutations if any(x + y == z for x, y, z in permutations((a, b, c), 3)): do_stuff() ``` Or without `permutations()` and the possibility of repeated computations: ``` if any(x + y == z for x, y, z in [(a, b, c), (a, c, b), (b, c, a)]: do_stuff() ``` I would probably put this, or any other solution, into a function. Then you can just cleanly call the function in your code. Personally, unless I needed more flexibility from the code, I would just use the first method in your question. It's simple and efficient. I still might put it into a function: ``` def two_add_to_third(a, b, c): return a + b == c or a + c == b or b + c == a if two_add_to_third(a, b, c): do_stuff() ``` That's pretty Pythonic, and it's quite possibly the most efficient way to do it (the extra function call aside); although you shouldn't worry too much about performance anyway, unless it's actually causing an issue.
Compact way of writing (a + b == c or a + c == b or b + c == a)
32,085,675
133
2015-08-19T02:40:12Z
32,085,900
17
2015-08-19T03:07:59Z
[ "python", "boolean" ]
Is there a more compact or pythonic way to write the boolean expression ``` a + b == c or a + c == b or b + c == a ``` I came up with ``` a + b + c in (2*a, 2*b, 2*c) ``` but that is a little strange.
If you will only be using three variables then your initial method: ``` a + b == c or a + c == b or b + c == a ``` Is already very pythonic. If you plan on using more variables then your method of reasoning with: ``` a + b + c in (2*a, 2*b, 2*c) ``` Is very smart but lets think about why. Why does this work? Well through some simple arithmetic we see that: ``` a + b = c c = c a + b + c == c + c == 2*c a + b + c == 2*c ``` And this will have to hold true for either a,b, or c, meaning that yes it will equal `2*a`, `2*b`, or `2*c`. This will be true for any number of variables. So a good way to write this quickly would be to simply have a list of your variables and check their sum against a list of the doubled values. ``` values = [a,b,c,d,e,...] any(sum(values) in [2*x for x in values]) ``` This way, to add more variables into the equation all you have to do is edit your values list by 'n' new variables, not write 'n' equations
Compact way of writing (a + b == c or a + c == b or b + c == a)
32,085,675
133
2015-08-19T02:40:12Z
32,086,517
54
2015-08-19T04:20:34Z
[ "python", "boolean" ]
Is there a more compact or pythonic way to write the boolean expression ``` a + b == c or a + c == b or b + c == a ``` I came up with ``` a + b + c in (2*a, 2*b, 2*c) ``` but that is a little strange.
Python has an `any` function that does an `or` on all the elements of a sequence. Here I've converted your statement into a 3-element tuple. ``` any((a + b == c, a + c == b, b + c == a)) ``` Note that `or` is short circuiting, so if calculating the individual conditions is expensive it might be better to keep your original construct.
Compact way of writing (a + b == c or a + c == b or b + c == a)
32,085,675
133
2015-08-19T02:40:12Z
32,097,819
103
2015-08-19T14:06:14Z
[ "python", "boolean" ]
Is there a more compact or pythonic way to write the boolean expression ``` a + b == c or a + c == b or b + c == a ``` I came up with ``` a + b + c in (2*a, 2*b, 2*c) ``` but that is a little strange.
Solving the three equalities for a: ``` a in (b+c, b-c, c-b) ```
Compact way of writing (a + b == c or a + c == b or b + c == a)
32,085,675
133
2015-08-19T02:40:12Z
32,101,507
197
2015-08-19T17:01:07Z
[ "python", "boolean" ]
Is there a more compact or pythonic way to write the boolean expression ``` a + b == c or a + c == b or b + c == a ``` I came up with ``` a + b + c in (2*a, 2*b, 2*c) ``` but that is a little strange.
If we look at the Zen of Python, emphasis mine: > The Zen of Python, by Tim Peters > > Beautiful is better than ugly. > Explicit is better than implicit. > **Simple is better than complex.** > Complex is better than complicated. > Flat is better than nested. > Sparse is better than dense. > **Readability counts.** > Special cases aren't special enough to break the rules. > Although practicality beats purity. > Errors should never pass silently. > Unless explicitly silenced. > In the face of ambiguity, refuse the temptation to guess. > **There should be one-- and preferably only one --obvious way to do it.** > Although that way may not be obvious at first unless you're Dutch. > Now is better than never. > Although never is often better than *right* now. > **If the implementation is hard to explain, it's a bad idea.** > **If the implementation is easy to explain, it may be a good idea.** > Namespaces are one honking great idea -- let's do more of those! The most Pythonic solution is the one that is clearest, simplest, and easiest to explain: ``` a + b == c or a + c == b or b + c == a ``` Even better, you don't even need to know Python to understand this code! It's *that* easy. This is, without reservation, the best solution. Anything else is intellectual masturbation. Furthermore, this is likely the best performing solution as well, as it is the only one out of all the proposals that short circuits. If `a + b == c`, only a single addition and comparison is done.
Compact way of writing (a + b == c or a + c == b or b + c == a)
32,085,675
133
2015-08-19T02:40:12Z
32,102,240
12
2015-08-19T17:46:22Z
[ "python", "boolean" ]
Is there a more compact or pythonic way to write the boolean expression ``` a + b == c or a + c == b or b + c == a ``` I came up with ``` a + b + c in (2*a, 2*b, 2*c) ``` but that is a little strange.
The following code can be used to iteratively compare each element with the sum of the others, which is computed from sum of the whole list, excluding that element. ``` l = [a,b,c] any(sum(l)-e == e for e in l) ```
Compact way of writing (a + b == c or a + c == b or b + c == a)
32,085,675
133
2015-08-19T02:40:12Z
32,130,760
9
2015-08-21T00:55:34Z
[ "python", "boolean" ]
Is there a more compact or pythonic way to write the boolean expression ``` a + b == c or a + c == b or b + c == a ``` I came up with ``` a + b + c in (2*a, 2*b, 2*c) ``` but that is a little strange.
Python 3: ``` (a+b+c)/2 in (a,b,c) (a+b+c+d)/2 in (a,b,c,d) ... ``` It scales to any number of variables: ``` arr = [a,b,c,d,...] sum(arr)/2 in arr ``` However, in general I agree that unless you have more than three variables, the original version is more readable.
Compact way of writing (a + b == c or a + c == b or b + c == a)
32,085,675
133
2015-08-19T02:40:12Z
32,134,734
8
2015-08-21T07:31:22Z
[ "python", "boolean" ]
Is there a more compact or pythonic way to write the boolean expression ``` a + b == c or a + c == b or b + c == a ``` I came up with ``` a + b + c in (2*a, 2*b, 2*c) ``` but that is a little strange.
Don't try and simplify it. Instead, *name* what you're doing with a function: ``` def any_two_sum_to_third(a, b, c): return a + b == c or a + c == b or b + c == a if any_two_sum_to_third(foo, bar, baz): ... ``` Replace the condition with something "clever" might make it shorter, but it won't make it more readable. Leaving it how it is isn't very readable either however, because it's tricky to know *why* you're checking those three conditions at a glance. This makes it absolutely crystal clear what you're checking for. Regarding performance, this approach does add the overhead of a function call, but never sacrifice readability for performance unless you've found a bottleneck you absolutely must fix. And always measure, as some clever implementations are capable of optimizing away and inlining some function calls in some circumstances.
Can't install virtualenvwrapper on OSX 10.11 El Capitan
32,086,631
31
2015-08-19T04:33:56Z
32,095,725
43
2015-08-19T12:37:04Z
[ "python", "osx", "virtualenv", "virtualenvwrapper", "osx-elcapitan" ]
I recently wiped my Mac and reinstalled OSX El Capitan public beta 3. I installed pip with `sudo easy_install pip` and installed virtualenv with `sudo pip install virtualenv` and did not have any problems. Now, when I try to `sudo pip install virtualenvwrapper`, I get the following: ``` Users-Air:~ User$ sudo pip install virtualenvwrapper The directory '/Users/User/Library/Caches/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag. The directory '/Users/User/Library/Caches/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag. Collecting virtualenvwrapper Downloading virtualenvwrapper-4.6.0-py2.py3-none-any.whl Requirement already satisfied (use --upgrade to upgrade): virtualenv in /Library/Python/2.7/site-packages (from virtualenvwrapper) Requirement already satisfied (use --upgrade to upgrade): virtualenv-clone in /Library/Python/2.7/site-packages (from virtualenvwrapper) Collecting stevedore (from virtualenvwrapper) Downloading stevedore-1.7.0-py2.py3-none-any.whl Requirement already satisfied (use --upgrade to upgrade): pbr<2.0,>=1.3 in /Library/Python/2.7/site-packages (from stevedore->virtualenvwrapper) Requirement already satisfied (use --upgrade to upgrade): argparse in /Library/Python/2.7/site-packages (from stevedore->virtualenvwrapper) Collecting six>=1.9.0 (from stevedore->virtualenvwrapper) Downloading six-1.9.0-py2.py3-none-any.whl Installing collected packages: six, stevedore, virtualenvwrapper Found existing installation: six 1.4.1 DEPRECATION: Uninstalling a distutils installed project (six) has been deprecated and will be removed in a future version. This is due to the fact that uninstalling a distutils project will only partially uninstall the project. Uninstalling six-1.4.1: Exception: Traceback (most recent call last): File "/Library/Python/2.7/site-packages/pip-7.1.0-py2.7.egg/pip/basecommand.py", line 223, in main status = self.run(options, args) File "/Library/Python/2.7/site-packages/pip-7.1.0-py2.7.egg/pip/commands/install.py", line 299, in run root=options.root_path, File "/Library/Python/2.7/site-packages/pip-7.1.0-py2.7.egg/pip/req/req_set.py", line 640, in install requirement.uninstall(auto_confirm=True) File "/Library/Python/2.7/site-packages/pip-7.1.0-py2.7.egg/pip/req/req_install.py", line 726, in uninstall paths_to_remove.remove(auto_confirm) File "/Library/Python/2.7/site-packages/pip-7.1.0-py2.7.egg/pip/req/req_uninstall.py", line 125, in remove renames(path, new_path) File "/Library/Python/2.7/site-packages/pip-7.1.0-py2.7.egg/pip/utils/__init__.py", line 314, in renames shutil.move(old, new) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 302, in move copy2(src, real_dst) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 131, in copy2 copystat(src, dst) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 103, in copystat os.chflags(dst, st.st_flags) OSError: [Errno 1] Operation not permitted: '/tmp/pip-tTNnKQ-uninstall/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/six-1.4.1-py2.7.egg-info' ``` As the issue seems to be with the `six` package, manually trying to uninstall it with `sudo pip uninstall six` results in the same error. The output suggests using the `-H` flag as well, but I still get pretty much the same error: ``` Users-Air:~ User$ sudo -H pip install virtualenvwrapper Collecting virtualenvwrapper Downloading virtualenvwrapper-4.6.0-py2.py3-none-any.whl Requirement already satisfied (use --upgrade to upgrade): virtualenv in /Library/Python/2.7/site-packages (from virtualenvwrapper) Requirement already satisfied (use --upgrade to upgrade): virtualenv-clone in /Library/Python/2.7/site-packages (from virtualenvwrapper) Collecting stevedore (from virtualenvwrapper) Downloading stevedore-1.7.0-py2.py3-none-any.whl Requirement already satisfied (use --upgrade to upgrade): pbr<2.0,>=1.3 in /Library/Python/2.7/site-packages (from stevedore->virtualenvwrapper) Requirement already satisfied (use --upgrade to upgrade): argparse in /Library/Python/2.7/site-packages (from stevedore->virtualenvwrapper) Collecting six>=1.9.0 (from stevedore->virtualenvwrapper) Downloading six-1.9.0-py2.py3-none-any.whl Installing collected packages: six, stevedore, virtualenvwrapper Found existing installation: six 1.4.1 DEPRECATION: Uninstalling a distutils installed project (six) has been deprecated and will be removed in a future version. This is due to the fact that uninstalling a distutils project will only partially uninstall the project. Uninstalling six-1.4.1: Exception: Traceback (most recent call last): File "/Library/Python/2.7/site-packages/pip-7.1.0-py2.7.egg/pip/basecommand.py", line 223, in main status = self.run(options, args) File "/Library/Python/2.7/site-packages/pip-7.1.0-py2.7.egg/pip/commands/install.py", line 299, in run root=options.root_path, File "/Library/Python/2.7/site-packages/pip-7.1.0-py2.7.egg/pip/req/req_set.py", line 640, in install requirement.uninstall(auto_confirm=True) File "/Library/Python/2.7/site-packages/pip-7.1.0-py2.7.egg/pip/req/req_install.py", line 726, in uninstall paths_to_remove.remove(auto_confirm) File "/Library/Python/2.7/site-packages/pip-7.1.0-py2.7.egg/pip/req/req_uninstall.py", line 125, in remove renames(path, new_path) File "/Library/Python/2.7/site-packages/pip-7.1.0-py2.7.egg/pip/utils/__init__.py", line 314, in renames shutil.move(old, new) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 302, in move copy2(src, real_dst) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 131, in copy2 copystat(src, dst) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 103, in copystat os.chflags(dst, st.st_flags) OSError: [Errno 1] Operation not permitted: '/tmp/pip-fwQzor-uninstall/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/six-1.4.1-py2.7.egg-info' ``` I have disabled rootless with `sudo nvram boot-args="rootless=0"`, and this has had no effect. Any help would be appreciated!
You can manually install the dependencies that don't exist on a stock 10.11 install, then install the other packages with `--no-deps` to ignore the dependencies. That way it will skip `six` (and `argparse` which is also already installed). This works on my 10.11 beta 6 install: ``` sudo pip install pbr sudo pip install --no-deps stevedore sudo pip install --no-deps virtualenvwrapper ``` And no need to disable rootless.
Can't install virtualenvwrapper on OSX 10.11 El Capitan
32,086,631
31
2015-08-19T04:33:56Z
33,425,578
29
2015-10-29T22:15:59Z
[ "python", "osx", "virtualenv", "virtualenvwrapper", "osx-elcapitan" ]
I recently wiped my Mac and reinstalled OSX El Capitan public beta 3. I installed pip with `sudo easy_install pip` and installed virtualenv with `sudo pip install virtualenv` and did not have any problems. Now, when I try to `sudo pip install virtualenvwrapper`, I get the following: ``` Users-Air:~ User$ sudo pip install virtualenvwrapper The directory '/Users/User/Library/Caches/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag. The directory '/Users/User/Library/Caches/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag. Collecting virtualenvwrapper Downloading virtualenvwrapper-4.6.0-py2.py3-none-any.whl Requirement already satisfied (use --upgrade to upgrade): virtualenv in /Library/Python/2.7/site-packages (from virtualenvwrapper) Requirement already satisfied (use --upgrade to upgrade): virtualenv-clone in /Library/Python/2.7/site-packages (from virtualenvwrapper) Collecting stevedore (from virtualenvwrapper) Downloading stevedore-1.7.0-py2.py3-none-any.whl Requirement already satisfied (use --upgrade to upgrade): pbr<2.0,>=1.3 in /Library/Python/2.7/site-packages (from stevedore->virtualenvwrapper) Requirement already satisfied (use --upgrade to upgrade): argparse in /Library/Python/2.7/site-packages (from stevedore->virtualenvwrapper) Collecting six>=1.9.0 (from stevedore->virtualenvwrapper) Downloading six-1.9.0-py2.py3-none-any.whl Installing collected packages: six, stevedore, virtualenvwrapper Found existing installation: six 1.4.1 DEPRECATION: Uninstalling a distutils installed project (six) has been deprecated and will be removed in a future version. This is due to the fact that uninstalling a distutils project will only partially uninstall the project. Uninstalling six-1.4.1: Exception: Traceback (most recent call last): File "/Library/Python/2.7/site-packages/pip-7.1.0-py2.7.egg/pip/basecommand.py", line 223, in main status = self.run(options, args) File "/Library/Python/2.7/site-packages/pip-7.1.0-py2.7.egg/pip/commands/install.py", line 299, in run root=options.root_path, File "/Library/Python/2.7/site-packages/pip-7.1.0-py2.7.egg/pip/req/req_set.py", line 640, in install requirement.uninstall(auto_confirm=True) File "/Library/Python/2.7/site-packages/pip-7.1.0-py2.7.egg/pip/req/req_install.py", line 726, in uninstall paths_to_remove.remove(auto_confirm) File "/Library/Python/2.7/site-packages/pip-7.1.0-py2.7.egg/pip/req/req_uninstall.py", line 125, in remove renames(path, new_path) File "/Library/Python/2.7/site-packages/pip-7.1.0-py2.7.egg/pip/utils/__init__.py", line 314, in renames shutil.move(old, new) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 302, in move copy2(src, real_dst) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 131, in copy2 copystat(src, dst) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 103, in copystat os.chflags(dst, st.st_flags) OSError: [Errno 1] Operation not permitted: '/tmp/pip-tTNnKQ-uninstall/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/six-1.4.1-py2.7.egg-info' ``` As the issue seems to be with the `six` package, manually trying to uninstall it with `sudo pip uninstall six` results in the same error. The output suggests using the `-H` flag as well, but I still get pretty much the same error: ``` Users-Air:~ User$ sudo -H pip install virtualenvwrapper Collecting virtualenvwrapper Downloading virtualenvwrapper-4.6.0-py2.py3-none-any.whl Requirement already satisfied (use --upgrade to upgrade): virtualenv in /Library/Python/2.7/site-packages (from virtualenvwrapper) Requirement already satisfied (use --upgrade to upgrade): virtualenv-clone in /Library/Python/2.7/site-packages (from virtualenvwrapper) Collecting stevedore (from virtualenvwrapper) Downloading stevedore-1.7.0-py2.py3-none-any.whl Requirement already satisfied (use --upgrade to upgrade): pbr<2.0,>=1.3 in /Library/Python/2.7/site-packages (from stevedore->virtualenvwrapper) Requirement already satisfied (use --upgrade to upgrade): argparse in /Library/Python/2.7/site-packages (from stevedore->virtualenvwrapper) Collecting six>=1.9.0 (from stevedore->virtualenvwrapper) Downloading six-1.9.0-py2.py3-none-any.whl Installing collected packages: six, stevedore, virtualenvwrapper Found existing installation: six 1.4.1 DEPRECATION: Uninstalling a distutils installed project (six) has been deprecated and will be removed in a future version. This is due to the fact that uninstalling a distutils project will only partially uninstall the project. Uninstalling six-1.4.1: Exception: Traceback (most recent call last): File "/Library/Python/2.7/site-packages/pip-7.1.0-py2.7.egg/pip/basecommand.py", line 223, in main status = self.run(options, args) File "/Library/Python/2.7/site-packages/pip-7.1.0-py2.7.egg/pip/commands/install.py", line 299, in run root=options.root_path, File "/Library/Python/2.7/site-packages/pip-7.1.0-py2.7.egg/pip/req/req_set.py", line 640, in install requirement.uninstall(auto_confirm=True) File "/Library/Python/2.7/site-packages/pip-7.1.0-py2.7.egg/pip/req/req_install.py", line 726, in uninstall paths_to_remove.remove(auto_confirm) File "/Library/Python/2.7/site-packages/pip-7.1.0-py2.7.egg/pip/req/req_uninstall.py", line 125, in remove renames(path, new_path) File "/Library/Python/2.7/site-packages/pip-7.1.0-py2.7.egg/pip/utils/__init__.py", line 314, in renames shutil.move(old, new) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 302, in move copy2(src, real_dst) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 131, in copy2 copystat(src, dst) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 103, in copystat os.chflags(dst, st.st_flags) OSError: [Errno 1] Operation not permitted: '/tmp/pip-fwQzor-uninstall/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/six-1.4.1-py2.7.egg-info' ``` I have disabled rootless with `sudo nvram boot-args="rootless=0"`, and this has had no effect. Any help would be appreciated!
sudo pip install virtualenvwrapper --ignore-installed six Also works
Pandas Dataframe to RDD
32,090,714
5
2015-08-19T08:50:04Z
32,093,313
7
2015-08-19T10:45:56Z
[ "python", "apache-spark", "dataframe", "pyspark", "spark-dataframe" ]
Can I convert a Pandas Dataframe to RDD? ``` if isinstance(data2, pd.DataFrame): print 'is Dataframe' else: print 'is NOT Dataframe' ``` is Dataframe Here is the output when trying to use .rdd ``` dataRDD = data2.rdd print dataRDD AttributeError Traceback (most recent call last) <ipython-input-56-7a9188b07317> in <module>() ----> 1 dataRDD = data2.rdd 2 print dataRDD /usr/lib64/python2.7/site-packages/pandas/core/generic.pyc in __getattr__(self, name) 2148 return self[name] 2149 raise AttributeError("'%s' object has no attribute '%s'" % -> 2150 (type(self).__name__, name)) 2151 2152 def __setattr__(self, name, value): AttributeError: 'DataFrame' object has no attribute 'rdd' ``` I would like to use Pandas Dataframe and not sqlContext to build as I'm not sure if all the functions in Pandas DF are available in Spark. If this is not possible, is there anyone that can provide an example of using Spark DF
> Can I convert a Pandas Dataframe to RDD? Well, yes you can do it. Pandas Data Frames ``` pdDF = pd.DataFrame([("foo", 1), ("bar", 2)], columns=("k", "v")) print pdDF ## k v ## 0 foo 1 ## 1 bar 2 ``` can be converted to Spark Data Frames ``` pDF = sqlContext.createDataFrame(pdDF) spDF.show() ## +---+-+ ## | k|v| ## +---+-+ ## |foo|1| ## |bar|2| ## +---+-+ ``` and after that you can easily access underlaying RDD ``` spDF.rdd.first() ## Row(k=u'foo', v=1) ``` Still, I think your a wrong idea here. Pandas Data Frame is a local data structure. It is stored and processed locally on the driver. There is no data distribution or parallel processing and it doesn't use RDDs (hence no `rdd` attribute). Unlike Spark DataFrame it provides random access capabilities. Spark DataFrame is distributed data structures using RDDs behind the scenes. It can be accessed using either raw SQL (`sqlContext.sql`) or SQL like API (`df.where(col("foo") == "bar").groupBy(col("bar")).agg(sum(col("foobar")))`). There is no random access and it is immutable (no equivalent of Pandas `inplace`). Every transformation returns new DataFrame. > If this is not possible, is there anyone that can provide an example of using Spark DF Not really. It is far to broad topic for SO. Spark has a really good documentation and DataBricks provides some additional resources. For starters you check these: * [Introducing DataFrames in Spark for Large Scale Data Science](https://databricks.com/blog/2015/02/17/introducing-dataframes-in-spark-for-large-scale-data-science.html) * [Spark SQL and DataFrame Guide](http://spark.apache.org/docs/latest/sql-programming-guide.html)
morse code to english python3
32,094,525
3
2015-08-19T11:41:45Z
32,094,652
10
2015-08-19T11:48:05Z
[ "python", "dictionary" ]
i want to convert Morse Code to English using Python 3+ I have managed to convert english to morse code using this <http://code.activestate.com/recipes/578407-simple-morse-code-translator-in-python/> But i want to convert Morse Code to English I have attempted to do it one charecter at a time, but the problem is that morse code letters are not 1 charecter long like english letters, so E is "." and S is "...", the problem i have is that the dictionary loop will find the "." and match it to E, so instead of getting S i get "E E E" i tried to fix this by detecting spaces and doing it a word at a time, but instead of looking for the letters in the word it searches the entire word against the dictionary i'm new to Python and dictionaries and i don't know how to differeniate between an E "." and an S "..." when searching my dictionary Here is my code ``` # defines the dictionary to convert morse to english CODE_reversed = {'..-.': 'F', '-..-': 'X', '.--.': 'P', '-': 'T', '..---': '2', '....-': '4', '-----': '0', '--...': '7', '...-': 'V', '-.-.': 'C', '.': 'E', '.---': 'J', '---': 'O', '-.-': 'K', '----.': '9', '..': 'I', '.-..': 'L', '.....': '5', '...--': '3', '-.--': 'Y', '-....': '6', '.--': 'W', '....': 'H', '-.': 'N', '.-.': 'R', '-...': 'B', '---..': '8', '--..': 'Z', '-..': 'D', '--.-': 'Q', '--.': 'G', '--': 'M', '..-': 'U', '.-': 'A', '...': 'S', '.----': '1'} def main(): #takes user message and makes it upper case msg = input('MESSAGE: ') msg = msg.upper() addtolist = "" # creates blank string message = [] # creates blank list for i in msg: addtolist = addtolist + i # adds every letter in MSG into a string until it finds a space addtolist.upper() # makes every letter uppercase if i == " ": # if it detects a space message.extend(addtolist) # adds the previously created addtolist to a list, this makes one word addtolist = "" # clears previous variable for i in message: # for every word in the list str(i) # make it into a string print(CODE_reversed[i()]) # search the dictionary for that word if __name__ == "__main__": main() ``` This code takes a word, and tries to look it up against the dictionary, but it doesn't work i have also tried searching each individual morse code letter against the dictionary but the problem is that you can't tell when a letter starts and ends, so "..." comes out as "EEE" instead of "S" and i don't know how to fix this i have also tried searching for solutions but have only found them in Java and i do not know Java
Once you define the mapping in one direction, you can use a dict comprehension to map it the other way ``` CODE = {'A': '.-', 'B': '-...', 'C': '-.-.', 'D': '-..', 'E': '.', 'F': '..-.', 'G': '--.', 'H': '....', 'I': '..', 'J': '.---', 'K': '-.-', 'L': '.-..', 'M': '--', 'N': '-.', 'O': '---', 'P': '.--.', 'Q': '--.-', 'R': '.-.', 'S': '...', 'T': '-', 'U': '..-', 'V': '...-', 'W': '.--', 'X': '-..-', 'Y': '-.--', 'Z': '--..', '0': '-----', '1': '.----', '2': '..---', '3': '...--', '4': '....-', '5': '.....', '6': '-....', '7': '--...', '8': '---..', '9': '----.' } CODE_REVERSED = {value:key for key,value in CODE.items()} ``` Then you can use `join` with a generator expression to perform the translations. ``` def to_morse(s): return ' '.join(CODE.get(i.upper()) for i in s) def from_morse(s): return ''.join(CODE_REVERSED.get(i) for i in s.split()) >>> to_morse('hello') '.... . .-.. .-.. ---' >>> from_morse('.... . .-.. .-.. ---') 'HELLO' ```
Python Gaussian Kernel density calculate score for new values
32,101,817
12
2015-08-19T17:18:55Z
32,146,454
9
2015-08-21T17:48:57Z
[ "python", "gaussian", "kde", "kernel-density" ]
this is my code: ``` import numpy as np from scipy.stats.kde import gaussian_kde from scipy.stats import norm from numpy import linspace,hstack from pylab import plot,show,hist import re import json attribute_file="path" attribute_values = [line.rstrip('\n') for line in open(attribute_file)] obs=[] #Assume the list obs as loaded obs=np.asarray(osservazioni) obs=np.sort(obs,kind='mergesort') x_min=osservazioni[0] x_max=osservazioni[len(obs)-1] # obtaining the pdf (my_pdf is a function!) my_pdf = gaussian_kde(obs) # plotting the result x = linspace(0,x_max,1000) plot(x,my_pdf(x),'r') # distribution function hist(obs,normed=1,alpha=.3) # histogram show() new_values = np.asarray([-1, 0, 2, 3, 4, 5, 768])[:, np.newaxis] for e in new_values: print (str(e)+" - "+str(my_pdf(e)*100*2)) ``` **Problem:** The obs array contains a list of all obs. I need to calcolate a score (between 0 and 1) for new values > [-1, 0, 2, 3, 4, 500, 768] So the value -1 must have a discrete score because it doesn't appears in the distribution but is next to the 1 value that is very common in the observations.
The reason for that is that you have many more 1's in your observations than 768's. So even if -1 is not exactly 1, it gets a high predicted value, because the histogram has a much larger larger value at 1 than at 768. Up to a multiplicative constant, the formula for prediction is: [![enter image description here](http://i.stack.imgur.com/EMAGM.gif)](http://i.stack.imgur.com/EMAGM.gif) where K is your kernel, D your observations and h your bandwitdh. Looking at [the doc for `gaussian_kde`](http://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.gaussian_kde.html), we see that if no value is provided for `bw_method`, it is estimated in some way, which here doesn't suit you. So you can try some different values: the larger the bandwidth, the more points far from your new data are taken into account, the limit case being an almost constant predicted function. On the other hand, a very small bandwidth only takes really close points into account, which is what I thing you want. Some graphs to illustrate the influence of the bandwidth: [![enter image description here](http://i.stack.imgur.com/bwOsM.png)](http://i.stack.imgur.com/bwOsM.png) Code used: ``` import matplotlib.pyplot as plt f, axarr = plt.subplots(2, 2, figsize=(10, 10)) for i, h in enumerate([0.01, 0.1, 1, 5]): my_pdf = gaussian_kde(osservazioni, h) axarr[i//2, i%2].plot(x, my_pdf(x), 'r') # distribution function axarr[i//2, i%2].set_title("Bandwidth: {0}".format(h)) axarr[i//2, i%2].hist(osservazioni, normed=1, alpha=.3) # histogram ``` With your current code, for x=-1, the value of K((x-x\_i)/h) for all x\_i's who are equal to 1 is smaller than 1, but you add up a lot of these values (there are 921 1s in your observations, and also 357 2s) On the other hand for x = 768, the value of the kernel is 1 for all x\_i's which are 768, but there are not many such points (39 to be precise). So here a lot of "small" terms make a larger sum than a small number of larger terms. If you don't want this behavior, you can decrease the size of your gaussian kernel : this way the penalty (K(-2)) paid because of the distance between -1 and 1 will be higher. But I think that this would be overfitting your observations. A formula to determine whether a new sample is acceptable (compared to your empirical distribution) or not is more of a statistical problem, you can have a look at `stats.stackexchange.com` You can always try to use a low value for the bandwidth, which will give you a peaked predicted function. Then you can normalize this function, dividing it by its maximal value. After that, all predicted values will be between 0 and 1: ``` maxDensityValue = np.max(my_pdf(x)) for e in new_values: print("{0} {1}".format(e, my_pdf(e)/maxDensityValue)) ```
Google App Engine app deployment
32,107,712
9
2015-08-20T00:25:02Z
34,694,577
14
2016-01-09T14:21:36Z
[ "python", "google-app-engine", "web-applications" ]
I'm trying to deploy a basic HelloWorld app on Google Engine following their tutorial for Python. I created a **helloworld.py** file and an **app.yaml** file and copied the code from their online tutorial. I signed up for Google App Engine and have tried everything but keep getting the following error: ``` 2015-08-19 19:22:08,006 ERROR appcfg.py:2438 An error occurred processing file '': HTTP Error 403: Forbidden Unexpected HTTP status 403. Aborting. Error 403: --- begin server output --- You do not have permission to modify this app (app_id=u'helloworld'). --- end server output --- If deploy fails you might need to 'rollback' manually. The "Make Symlinks..." menu option can help with command-line work. *** appcfg.py has finished with exit code 1 *** ``` Here is the code from helloworld.py: ``` import webapp2 class MainPage(webapp2.RequestHandler): def get(self): self.response.headers['Content-Type'] = 'text/plain' self.response.write('Hello, Udacity!') app = webapp2.WSGIApplication([ ('/', MainPage), ], debug=True) ``` And here is my code from the app.yaml file: ``` application: helloworld version: 1 runtime: python27 api_version: 1 threadsafe: true handlers: - url: /.* script: helloworld.app ``` Is there a problem with permissions i.e. Google App's or my laptop's settings? I have tried everything that's out there on stackoverflow so any new suggestions will be much appreciated!!
In my case, I got refused because the appcfg save my ouauth2 token in the file `~/.appcfg_oauth2_tokens`, which happen to be another account of appengine . Simply remove the file and try again. It should work. This is in Mac, I am not sure about windows though.
Set vs. set python
32,108,235
3
2015-08-20T01:40:45Z
32,108,276
8
2015-08-20T01:45:41Z
[ "python", "python-3.x" ]
What's the difference between `set("a")` and `sets.Set("a")`? Their types are different, but they seem to do the same thing. I can't find any resources online about it, but I've seen both used in examples.
You've tagged this Python 3, so the difference is that `sets` doesn't exist. Use `set`. In Python 2, the difference is that `sets` is deprecated. It's the old, slow, not-as-good version. Use `set`. This is explained in the [documentation for the `sets` module](https://docs.python.org/2/library/sets.html), which comes up instantly on a search for `Python sets`.
Equivalent of matlab "ans" and running shell commands
32,108,471
2
2015-08-20T02:07:07Z
32,108,552
7
2015-08-20T02:18:25Z
[ "python", "matlab", "shell" ]
These days, I'm transitiong from Matlab to Python after using Matlab/Octave for more than ten years. I have two quick questions: 1. In the Python interactive mode, is there anything corresponding to Matlab's `ans`? 2. How can I run shell commands in the Python interactive mode? Of course, I can use `os.system()`, but in Matlab we may run shell commands just by placing `!` before the actual command. Is there anything similar in Python?
Python interactive mode is Python. You will need to use `os.system` or an equivalent. Alternately, you can suspend Python with Ctrl-Z, and get back into it with `fg`. (Assuming UNIX-like environment.) The last evaluated expression is saved in the variable `_`: ``` >>> 1 + 2 3 >>> _ * 4 12 ```
Converting a `pandas.tslib.Timestamp` object to `datetime`
32,108,564
4
2015-08-20T02:19:55Z
32,113,406
10
2015-08-20T08:36:31Z
[ "python", "pandas" ]
I am trying to convert a `pandas.tslib.Timestamp` object to `datetime`.`df['orig_iss_dt']` is the `pandas.tslib.Timestamp` object. I used the answer [here](http://stackoverflow.com/questions/25852044/converting-pandas-tslib-timestamp-to-datetime-python) to try and do this, but find that `print(type(origination))` still returns the same type. ``` df['orig_iss_dt'] = df['orig_iss_dt'].apply(lambda x: datetime.date(x.year,x.month,x.day)) for (i, row) in df: origination = row.orig_iss_dt print(type(origination)) ```
The easiest way to convert a pandas `Timestamp` to `datetime.datetime` is to use the `to_pydatetime` method. This can be called on `Timestamp` directly or on the series: ``` In [15]: s = pd.Series(pd.date_range('2012-01-01', periods=3)) In [16]: s Out[16]: 0 2012-01-01 1 2012-01-02 2 2012-01-03 dtype: datetime64[ns] In [17]: s[0] Out[17]: Timestamp('2012-01-01 00:00:00') In [18]: s.dt.to_pydatetime() Out[18]: array([datetime.datetime(2012, 1, 1, 0, 0), datetime.datetime(2012, 1, 2, 0, 0), datetime.datetime(2012, 1, 3, 0, 0)], dtype=object) ``` But note that this is often times not needed, as `Timestamp` is a subclass of `datetime.datetime`.
How to implement the ReLU function in Numpy
32,109,319
7
2015-08-20T03:58:56Z
32,109,519
13
2015-08-20T04:22:14Z
[ "python", "numpy", "machine-learning", "neural-network" ]
I want to make simple neural network and I wish to use the ReLU function. Can someone give me a clue of how can I implement the function using numpy. Thanks for your time!
There are a couple of ways. ``` >>> x = np.random.random((3, 2)) - 0.5 >>> x array([[-0.00590765, 0.18932873], [-0.32396051, 0.25586596], [ 0.22358098, 0.02217555]]) >>> np.maximum(x, 0) array([[ 0. , 0.18932873], [ 0. , 0.25586596], [ 0.22358098, 0.02217555]]) >>> x * (x > 0) array([[-0. , 0.18932873], [-0. , 0.25586596], [ 0.22358098, 0.02217555]]) >>> (abs(x) + x) / 2 array([[ 0. , 0.18932873], [ 0. , 0.25586596], [ 0.22358098, 0.02217555]]) ``` If timing the results with the following code: ``` import numpy as np x = np.random.random((5000, 5000)) - 0.5 print("max method:") %timeit -n10 np.maximum(x, 0) print("multiplication method:") %timeit -n10 x * (x > 0) print("abs method:") %timeit -n10 (abs(x) + x) / 2 ``` We get: ``` max method: 10 loops, best of 3: 239 ms per loop multiplication method: 10 loops, best of 3: 145 ms per loop abs method: 10 loops, best of 3: 288 ms per loop ``` So the multiplication seems to be the fastest.
What is the difference between u' ' prefix and unicode() in python?
32,111,835
6
2015-08-20T07:17:52Z
32,111,908
11
2015-08-20T07:21:19Z
[ "python", "unicode", "utf-8" ]
What is the difference between `u''` prefix and `unicode()`? ``` # -*- coding: utf-8 -*- print u'上午' # this works print unicode('上午', errors='ignore') # this works but print out nothing print unicode('上午') # error ``` For the third `print`, the error shows: UnicodeDecodeError: 'ascii' codec can't decode byte 0xe4 in position 0 If I have a text file containing non-ascii characters, such as "上午", how to read it and print it out correctly?
* `u'..'` is a string literal, and decodes the characters according to the source encoding declaration. * `unicode()` is a function that converts another type to a `unicode` object, you've given it a *byte string literal*. It'll decode a byte string according to the default ASCII codec. So you created a byte string object using a different type of literal notation, then tried to convert it to a `unicode()` object, which fails because the default codec for `str` -> `unicode` conversions is ASCII. The two are quite different beasts. If you want to use the latter, you need to give it an explicit codec: ``` print unicode('上午', 'utf8') ``` The two are related in the same way that using `0xFF` and `int('0xFF', 0)` are related; the former defines an integer of value 255 using hex notation, the latter uses the `int()` function to extract an integer from a string. An alternative method would be to use the [`str.decode()` method](https://docs.python.org/2/library/stdtypes.html#str.decode): ``` print '上午'.decode('utf8') ``` Don't be tempted to use an error handler (such as `ignore'` or `'replace'`) unless you know what you are doing. `'ignore'` especially can mask underlying issues with having picked the wrong codec, for example. You may want to read up on Python and Unicode: * [Pragmatic Unicode](http://nedbatchelder.com/text/unipain.html) by Ned Batchelder * [The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)](http://joelonsoftware.com/articles/Unicode.html) by Joel Spolsky * The [Python Unicode HOWTO](http://docs.python.org/2/howto/unicode.html)
Why should not use list.sort in python
32,111,959
6
2015-08-20T07:24:07Z
32,111,976
8
2015-08-20T07:24:48Z
[ "python", "sorting" ]
While I was going through [Google Python Class Day 1 Part 2](https://www.youtube.com/watch?v=EPYupizJYQI) at 14:20 - 14:30 Guy says *"do not use `list.sort`"*. Also he mentioned that *"Dinosaurs use that!"* (i.e. it's an old way of doing sorting). But he did not mention the reason. Can anyone tell me why we should not use `list.sort`?
Because `list.sort()` will do an in-place sorting. So this changes the original list. But `sorted(list)` would create a new list instead of modifying the original. Example: ``` >>> s = [1,2,37,4] >>> s.sort() >>> s [1, 2, 4, 37] >>> s = [1,2,37,4,45] >>> sorted(s) [1, 2, 4, 37, 45] >>> s [1, 2, 37, 4, 45] ```
Why is math.floor(x/y) != x // y for two evenly divisible floats in Python?
32,123,583
23
2015-08-20T16:29:42Z
32,126,311
24
2015-08-20T19:03:36Z
[ "python", "division", "integer-division" ]
I have been reading about division and integer division in Python and the differences between division in Python2 vs Python3. For the most part it all makes sense. Python 2 uses integer division only when both values are integers. Python 3 always performs true division. Python 2.2+ introduced the `//` operator for integer division. Examples other programmers have offered work out nice and neat, such as: ``` >>> 1.0 // 2.0 # floors result, returns float 0.0 >>> -1 // 2 # negatives are still floored -1 ``` **How is `//` implemented? Why does the following happen:** ``` >>> import math >>> x = 0.5 >>> y = 0.1 >>> x / y 5.0 >>> math.floor(x/y) 5.0 >>> x // y 4.0 ``` Shouldn't `x // y = math.floor(x/y)`? These results were produced on python2.7, but since x and y are both floats the results should be the same on python3+. If there is some floating point error where `x/y` is actually `4.999999999999999` and `math.floor(4.999999999999999) == 4.0` wouldn't that be reflected in `x/y`? The following similar cases, however, aren't affected: ``` >>> (.5*10) // (.1*10) 5.0 >>> .1 // .1 1.0 ```
I didn't find the other answers satisfying. Sure, `.1` has no finite binary expansion, so our hunch is that representation error is the culprit. But that hunch alone doesn't really explain why `math.floor(.5/.1)` yields `5.0` while `.5 // .1` yields `4.0`. The punchline is that `a // b` is **actually** doing `floor((a - (a % b))/b)`, as opposed to simply `floor(a/b)`. ## .5 / .1 is *exactly* 5.0 First of all, note that the result of `.5 / .1` is **exactly** `5.0` in Python. This is the case even though `.1` cannot be exactly represented. Take this code, for instance: ``` from decimal import Decimal num = Decimal(.5) den = Decimal(.1) res = Decimal(.5/.1) print('num: ', num) print('den: ', den) print('res: ', res) ``` And the corresponding output: ``` num: 0.5 den: 0.1000000000000000055511151231257827021181583404541015625 res: 5 ``` This shows that `.5` can be represented with a finite binary expansion, but `.1` cannot. But it also shows that despite this, the result of `.5 / .1` *is* exactly `5.0`. This is because floating point division results in the loss of precision, and the amount by which `den` differs from `.1` is lost in the process. That's why `math.floor(.5 / .1)` works as you might expect: since `.5 / .1` *is* `5.0`, writing `math.floor(.5 / .1)` is just the same as writing `math.floor(5.0)`. ## So why doesn't `.5 // .1` result in 5? One might assume that `.5 // .1` is shorthand for `floor(.5 / .1)`, but this is not the case. As it turns out, the semantics differ. This is even though the [PEP says](https://www.python.org/dev/peps/pep-0238/): > Floor division will be implemented in all the Python numeric > types, and will have the semantics of > > ``` > a // b == floor(a/b) > ``` As it turns out, the semantics of `.5 // .1` are *actually* equivalent to: ``` floor((.5 - mod(.5, .1)) / .1) ``` where `mod` is the floating point remainder of `.5 / .1` rounded towards zero. This is made clear by reading the [Python source code](https://github.com/python/cpython/blob/829b49cbd2e4b1d573470da79ca844b730120f3d/Objects/floatobject.c#L578). *This* is where the fact that `.1` can't be exactly represented by binary expansion causes the problem. The floating point remainder of `.5 / .1` is **not** zero: ``` >>> .5 % .1 0.09999999999999998 ``` and it makes sense that it isn't. Since the binary expansion of `.1` is ever-so-slightly greater than the actual decimal `.1`, the largest integer `alpha` such that `alpha * .1 <= .5` (in our finite precision math) is `alpha = 4`. So `mod(.5, .1)` is nonzero, and is roughly `.1`. Hence `floor((.5 - mod(.5, .1)) / .1)` becomes `floor((.5 - .1) / .1)` becomes `floor(.4 / .1)` which equals `4`. And that's why `.5 // .1 == 4`. ## Why does `//` do that? The behavior of `a // b` may seem strange, but there's a reason for it's divergence from `math.floor(a/b)`. In his [blog](http://python-history.blogspot.com/2010/08/why-pythons-integer-division-floors.html) on the history of Python, Guido writes: > The integer division operation (//) and its sibling, the modulo > operation (%), go together and satisfy a nice mathematical > relationship (all variables are integers): > > ``` > a/b = q with remainder r > ``` > > such that > > ``` > b*q + r = a and 0 <= r < b > ``` > > (assuming a and b are >= 0). Now, Guido assumes that all variables are integers, but that relationship will still hold if `a` and `b` are floats, *if* `q = a // b`. If `q = math.floor(a/b)` the relationship *won't* hold in general. And so `//` might be preferred because it satisfies this nice mathematical relationship.
Python Assignment Operator Precedence - (a, b) = a[b] = {}, 5
32,127,908
21
2015-08-20T20:36:02Z
32,127,960
15
2015-08-20T20:39:49Z
[ "python", "variable-assignment" ]
I saw this Python snippet on [Twitter](https://twitter.com/fijall/status/634260102795685890) and was quite confused by the output: ``` >>> a, b = a[b] = {}, 5 >>> a {5: ({...}, 5)} ``` What is going on here?
From the [*Assignment statements* documentation](https://docs.python.org/2/reference/simple_stmts.html#assignment-statements): > An assignment statement evaluates the expression list (remember that this can be a single expression or a comma-separated list, the latter yielding a tuple) and assigns the single resulting object to each of the target lists, from left to right. You have two assignment target lists; `a, b`, and `a[b]`, the value `{}, 5` is assigned to those two targets from left to right. First the `{}, 5` tuple is unpacked to `a, b`. You now have `a = {}` and `b = 5`. Note that `{}` is mutable. Next you assign the same dictionary and integer to `a[b]`, where `a` evaluates to the dictionary, and `b` evaluates to `5`, so you are setting the key `5` in the dictionary to the tuple `({}, 5)` creating a circular reference. The `{...}` thus refers to the same object that `a` is already referencing. Because assignment takes place from left to right, you can break this down to: ``` a, b = {}, 5 a[b] = a, b ``` so `a[b][0]` is the same object as `a`: ``` >>> a, b = {}, 5 >>> a[b] = a, b >>> a {5: ({...}, 5)} >>> a[b][0] is a True ```
yield in list comprehensions and generator expressions
32,139,885
23
2015-08-21T12:05:06Z
32,139,977
22
2015-08-21T12:08:38Z
[ "python", "generator", "list-comprehension", "yield", "generator-expression" ]
The following behaviour seems rather counterintuitive to me (Python 3.4): ``` >>> [(yield i) for i in range(3)] <generator object <listcomp> at 0x0245C148> >>> list([(yield i) for i in range(3)]) [0, 1, 2] >>> list((yield i) for i in range(3)) [0, None, 1, None, 2, None] ``` The intermediate values of the last line are actually not always `None`, they are whatever we `send` into the generator, equivalent (I guess) to the following generator: ``` def f(): for i in range(3): yield (yield i) ``` It strikes me as funny that those three lines work at all. The [Reference](https://docs.python.org/3/reference/expressions.html#yield-expressions) says that `yield` is only allowed in a function definition (though I may be reading it wrong and/or it may simply have been copied from the older version). The first two lines produce a `SyntaxError` in Python 2.7, but the third line doesn't. Also, it seems odd * that a list comprehension returns a generator and not a list * and that the generator expression converted to a list and the corresponding list comprehension contain different values. Could someone provide more information?
Generator expressions, and set and dict comprehensions are compiled to (generator) function objects. In Python 3, list comprehensions get the same treatment; they are all, in essence, a new nested scope. You can see this if you try to disassemble a generator expression: ``` >>> dis.dis(compile("(i for i in range(3))", '', 'exec')) 1 0 LOAD_CONST 0 (<code object <genexpr> at 0x10f7530c0, file "", line 1>) 3 LOAD_CONST 1 ('<genexpr>') 6 MAKE_FUNCTION 0 9 LOAD_NAME 0 (range) 12 LOAD_CONST 2 (3) 15 CALL_FUNCTION 1 (1 positional, 0 keyword pair) 18 GET_ITER 19 CALL_FUNCTION 1 (1 positional, 0 keyword pair) 22 POP_TOP 23 LOAD_CONST 3 (None) 26 RETURN_VALUE >>> dis.dis(compile("(i for i in range(3))", '', 'exec').co_consts[0]) 1 0 LOAD_FAST 0 (.0) >> 3 FOR_ITER 11 (to 17) 6 STORE_FAST 1 (i) 9 LOAD_FAST 1 (i) 12 YIELD_VALUE 13 POP_TOP 14 JUMP_ABSOLUTE 3 >> 17 LOAD_CONST 0 (None) 20 RETURN_VALUE ``` The above shows that a generator expression is compiled to a code object, loaded as a function (`MAKE_FUNCTION` creates the function object from the code object). The `.co_consts[0]` reference lets us see the code object generated for the expression, and it uses `YIELD_VALUE` just like a generator function would. As such, the `yield` expression works in that context, as the compiler sees these as functions-in-disguise. Still, I view this as a bug; `yield` has no place in these expressions. The Python *grammar* allows it (which is why the code is compilable), but the [`yield` expression specification](https://docs.python.org/3/reference/expressions.html#yield-expressions) shows that using `yield` here should not actually work: > The yield expression is only used when defining a *generator* function and thus can only be used in the body of a function definition. This has already lead to [confusing bugs](http://bugs.python.org/issue10544), where someone tried to use `yield` in a generator function, inside a generator expression, expecting the `yield` to apply to the function. The Python developers are aware of this issue, with Guido on record stating this is not intended: > I think it is definitely wrong the way it works in 3.x. (Especially since it works as expected in 2.x.) > > I agree with Inyeol's preference of fixes: (1) make it work properly for listcomps as well as genexps, (2) if that's not possible, forbid yield in a genexp or listcomp. The differences between how `yield` in a list comprehension and `yield` in a generator expression operate stem from the differences in how these two expressions are implemented. In Python 3 a list comprehension uses `LIST_APPEND` calls to add the top of the stack to the list being built, while a generator expression instead yields that value. Adding in `(yield <expr>)` just adds another `YIELD_VALUE` opcode to either: ``` >>> dis.dis(compile("[(yield i) for i in range(3)]", '', 'exec').co_consts[0]) 1 0 BUILD_LIST 0 3 LOAD_FAST 0 (.0) >> 6 FOR_ITER 13 (to 22) 9 STORE_FAST 1 (i) 12 LOAD_FAST 1 (i) 15 YIELD_VALUE 16 LIST_APPEND 2 19 JUMP_ABSOLUTE 6 >> 22 RETURN_VALUE >>> dis.dis(compile("((yield i) for i in range(3))", '', 'exec').co_consts[0]) 1 0 LOAD_FAST 0 (.0) >> 3 FOR_ITER 12 (to 18) 6 STORE_FAST 1 (i) 9 LOAD_FAST 1 (i) 12 YIELD_VALUE 13 YIELD_VALUE 14 POP_TOP 15 JUMP_ABSOLUTE 3 >> 18 LOAD_CONST 0 (None) 21 RETURN_VALUE ``` The `YIELD_VALUE` opcode at bytecode indexes 15 and 12 respectively is extra, a cuckoo in the nest. So for the list-comprehension-turned-generator you have 1 yield producing the top of the stack each time (replacing the top of the stack with the `yield` return value), and for the generator expression variant you yield the top of the stack (the integer) and then yield *again*, but now the stack contains the return value of the `yield` and you get `None` that second time. For the list comprehension then, the intended `list` object output is still returned, but Python 3 sees this as a generator so the return value is instead attached to the [`StopIteration` exception](https://docs.python.org/3/library/exceptions.html#StopIteration) as the `value` attribute: ``` >>> from itertools import islice >>> listgen = [(yield i) for i in range(3)] >>> list(islice(listgen, 3)) # avoid exhausting the generator [0, 1, 2] >>> try: ... next(listgen) ... except StopIteration as si: ... print(si.value) ... [None, None, None] ``` Those `None` objects are the return values from the `yield` expressions. And to reiterate this again; this same issue applies to dictionary and set comprehension in Python 2 and Python 3 as well; in Python 2 the `yield` return values are still added to the intended dictionary or set object, and the return value is 'yielded' last instead of attached to the `StopIteration` exception: ``` >>> list({(yield k): (yield v) for k, v in {'foo': 'bar', 'spam': 'eggs'}.items()}) ['bar', 'foo', 'eggs', 'spam', {None: None}] >>> list({(yield i) for i in range(3)}) [0, 1, 2, set([None])] ```
Python rock, paper, scissors game. not always give correct answers
32,140,140
2
2015-08-21T12:17:08Z
32,140,225
10
2015-08-21T12:21:19Z
[ "python", "python-3.x" ]
I'm trying to make a simple ***Rock, Paper, Scissors*** game in **python 3.4** and it works to a certain degree but some time i get an output of "You Won Rock crushes Rock" even though i thought i have stop this from happening and only allowed certain outcomes of the code with my elif and if statements. So can anyone tell me why isn't this working sometimes. :) ``` import random count = 0 OPTIONS = ['rock', 'paper', 'scissors'] # then check if the user lose's, wins ties def computer(): return random.choice(OPTIONS) print("\n"+"-=-"*11) print("Welcome to ROCK, PAPER, SCISSORS") print(" GAME") print(" It's you Vs. the computer!") print("-=-"*11) while True: user = input("What do you choose Rock, Paper, Scissors: ").lower() if user in OPTIONS: # Possible user time a user can succeeds rock beats sicissor, sicissors cuts paper, paper covers rock if user == computer(): print("tie") elif user == 'rock' and computer() == 'scissors': print("\nYou Won! {} crushes {}".format(user.title(), computer().title())) elif user == 'scissors' and computer() =='rock': print("\nComputer Won! {} crushes {}".format(computer().title(), user.title() )) elif user == 'scissors' and computer() == 'paper': print("\nYou Won! {} cuts {}".format(user.title(), computer().title())) elif user == 'paper' and computer() == 'scissors': print("\nComputer Won! {} cuts {}".format(computer().title(), user.title())) elif user == 'paper' and computer() == 'rock': print("\nYou Won! {} covers {}".format(user.title(), computer().title())) elif user == 'rock' and computer() == 'paper': print("\nComputer Won! {} covers {}".format(computer().title(), user.title())) else: print("\nMake sure you choose ethier Rock, Paper or Scissors") enter code here ```
``` elif user == 'rock' and computer() == 'scissors': print("\nYou Won! {} crushes {}".format(user.title(), computer().title())) ``` Every time you call `computer()`, it generates a completely new value, independent of any previous calls. For example, in the code above it's entirely possible that the first `computer()` call returns "scissors", and the second one returns "rock". Call `computer()` only once in the loop, and store the result. Then use that value for the rest of your code. ``` while True: user = input("What do you choose Rock, Paper, Scissors: ").lower() if user in OPTIONS: computer_move = computer() # Possible user time a user can succeeds rock beats sicissor, sicissors cuts paper, paper covers rock if user == computer_move: print("tie") elif user == 'rock' and computer_move == 'scissors': print("\nYou Won! {} crushes {}".format(user.title(), computer_move.title())) #etc ```
Is "norm" equivalent to "Euclidean distance"?
32,141,856
5
2015-08-21T13:41:26Z
32,142,625
7
2015-08-21T14:16:01Z
[ "python", "arrays", "math", "numpy", "euclidean-distance" ]
I am not sure whether "norm" and "Euclidean distance" mean the same thing. Please could you help me with this distinction. I have an `n` by `m` array `a`, where `m` > 3. I want to calculate the Eculidean distance between the second data point `a[1,:]` to all the other points (including itself). So I used the `np.linalg.norm`, which outputs the norm of two given points. But I don't know if this is the right way of getting the EDs. ``` import numpy as np a = np.array([[0, 0, 0 ,0 ], [1, 1 , 1, 1],[2,2, 2, 3], [3,5, 1, 5]]) N = a.shape[0] # number of row pos = a[1,:] # pick out the second data point. dist = np.zeros((N,1), dtype=np.float64) for i in range(N): dist[i]= np.linalg.norm(a[i,:] - pos) ```
A [norm](https://en.wikipedia.org/wiki/Norm_(mathematics)) is a function that takes a vector as an input and returns a scalar value that can be interpreted as the "size", "length" or "magnitude" of that vector. More formally, norms are defined as having the following mathematical properties: * They scale multiplicatively, i.e. *Norm(a·**v**) = |a|·Norm(**v**)* for any scalar *a* * They satisfy the triangle inequality, i.e. *Norm(**u** + **v**) ≤ Norm(**u**) + Norm(**v**)* * The norm of a vector is zero if and only if it is the zero vector, i.e. *Norm(**v**) = 0 ⇔ **v** = **0*** The Euclidean norm (also known as the L² norm) is just one of many different norms - there is also the max norm, the Manhattan norm etc. The L² norm of a single vector is equivalent to the Euclidean distance from that point to the origin, and the L² norm of the difference between two vectors is equivalent to the Euclidean distance between the two points. --- As **@nobar**'s answer says, `np.linalg.norm(x - y, ord=2)` (or just `np.linalg.norm(x - y)`) will give you Euclidean distance between the vectors `x` and `y`. Since you want to compute the Euclidean distance between `a[1, :]` and every other row in `a`, you could do this a lot faster by eliminating the `for` loop and broadcasting over the rows of `a`: ``` dist = np.linalg.norm(a[1:2] - a, axis=1) ``` It's also easy to compute the Euclidean distance yourself using broadcasting: ``` dist = np.sqrt(((a[1:2] - a) ** 2).sum(1)) ``` The fastest method is probably [`scipy.spatial.distance.cdist`](http://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.cdist.html): ``` from scipy.spatial.distance import cdist dist = cdist(a[1:2], a)[0] ``` --- Some timings for a (1000, 1000) array: ``` a = np.random.randn(1000, 1000) %timeit np.linalg.norm(a[1:2] - a, axis=1) # 100 loops, best of 3: 5.43 ms per loop %timeit np.sqrt(((a[1:2] - a) ** 2).sum(1)) # 100 loops, best of 3: 5.5 ms per loop %timeit cdist(a[1:2], a)[0] # 1000 loops, best of 3: 1.38 ms per loop # check that all 3 methods return the same result d1 = np.linalg.norm(a[1:2] - a, axis=1) d2 = np.sqrt(((a[1:2] - a) ** 2).sum(1)) d3 = cdist(a[1:2], a)[0] assert np.allclose(d1, d2) and np.allclose(d1, d3) ```