title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
sequence
python: i have an error while trying this on my mac using IDLE on mac or terminal
40,062,854
<p>i want to see some info and get info about my os with python as in my tutorial but actually can't run this code:</p> <pre><code>import os F = os.popen('dir') </code></pre> <p>and this :</p> <pre><code>F.readline() ' Volume in drive C has no label.\n' F = os.popen('dir') # Read by sized blocks F.read(50) ' Volume in drive C has no label.\n Volume Serial Nu' os.popen('dir').readlines()[0] # Read all lines: index ' Volume in drive C has no label.\n' os.popen('dir').read()[:50] # Read all at once: slice ' Volume in drive C has no label.\n Volume Serial Nu' for line in os.popen('dir'): # File line iterator loop ... print(line.rstrip()) </code></pre> <p>this is the the error for the first on terminal, (on IDLE it return just an '</p> <p>f = open('dir') Traceback (most recent call last): File "", line 1, in FileNotFoundError: [Errno 2] No such file or directory: 'dir'</p> <p>I know on mac it should be different but how? to get the same result using macOS sierra.</p>
0
2016-10-15T18:43:52Z
40,062,950
<p><code>open</code> and <code>os.popen</code> <em>are entirely different</em><sup>*</sup>. </p> <p>The first one just opens a file (by default <em>for reading</em>), but the second one runs a command in your shell and gives you the ability to communicate with it (e.g. get the output). </p> <p>So, given that <code>open</code> opens the file for reading when you supply only the file's name, if such a file doesn't exist, it raises an error, which is the case here. </p> <p><code>os.popen</code> executes the given command on your computer as if you typed it in the terminal. </p> <hr> <p><sup>* There exists another function with a similar name: <code>os.open</code>, which is, again, <a href="http://stackoverflow.com/questions/7219511/whats-the-difference-between-io-open-and-os-open-on-python">different</a> from the ones mentioned earlier.</sup></p>
0
2016-10-15T18:52:18Z
[ "python", "osx" ]
python: i have an error while trying this on my mac using IDLE on mac or terminal
40,062,854
<p>i want to see some info and get info about my os with python as in my tutorial but actually can't run this code:</p> <pre><code>import os F = os.popen('dir') </code></pre> <p>and this :</p> <pre><code>F.readline() ' Volume in drive C has no label.\n' F = os.popen('dir') # Read by sized blocks F.read(50) ' Volume in drive C has no label.\n Volume Serial Nu' os.popen('dir').readlines()[0] # Read all lines: index ' Volume in drive C has no label.\n' os.popen('dir').read()[:50] # Read all at once: slice ' Volume in drive C has no label.\n Volume Serial Nu' for line in os.popen('dir'): # File line iterator loop ... print(line.rstrip()) </code></pre> <p>this is the the error for the first on terminal, (on IDLE it return just an '</p> <p>f = open('dir') Traceback (most recent call last): File "", line 1, in FileNotFoundError: [Errno 2] No such file or directory: 'dir'</p> <p>I know on mac it should be different but how? to get the same result using macOS sierra.</p>
0
2016-10-15T18:43:52Z
40,063,025
<p><code>os.popen</code> executes a program and returns a file-like object to read the program output. So, <code>os.popen('dir')</code> runs the <code>dir</code> command (which lists information about your hard drive) and gives you the result. <code>open</code> opens a file on your hard drive for reading.</p> <p>Your problem is that there is no file named <code>dir</code>. You likely wanted <code>f = os.popen(</code>dir<code>)</code> MAC is different than windows and the base directory listing command is <code>ls</code>. But most unixy systems have a <code>dir</code> command that lists files in a different format, so it should work for you.</p>
0
2016-10-15T18:59:15Z
[ "python", "osx" ]
How to make a dynamic grid in Python
40,062,870
<p>I am building an X's and O's (tic tac toe) application where the user can decide whether the grid is between 5X5 and 10X10, how do I write the code so that the grid is dynamic? </p> <p>At the moment this is all I have to make a grid of one size:</p> <pre><code> grid = [[0,0,0,0,0,0,0],[0,0,0,0,0,0],[0,0,0,0,0,0,0],[0,0,0,0,0,0,0],[0,0,0,0,0,0],[0,0,0,0,0,0,0]] </code></pre>
0
2016-10-15T18:45:08Z
40,063,123
<p>Code:</p> <pre><code>#defining size x = y = 5 #create empty list to hold rows grid = [] #for each row defined by Y, this loop will append a list containing X occurrences of "0" for row in range(y): grid.append(list("0"*x)) print grid </code></pre> <p>Output:</p> <pre><code>[['0', '0', '0', '0', '0'], ['0', '0', '0', '0', '0'], ['0', '0', '0', '0', '0'], ['0', '0', '0', '0', '0'], ['0', '0', '0', '0', '0']] </code></pre>
1
2016-10-15T19:07:50Z
[ "python", "grid" ]
How to make that multiply all numbers in list (Permutation) with smaller code?
40,062,948
<p>My problem is:</p> <pre><code> perm_list = list(range(a,b,-1)) if len(perm_list) == 1: print(perm_list[0]) elif len(perm_list) == 2: print(perm_list[0]* perm_list[1]) elif len(perm_list) == 3: </code></pre> <p>I cant find a way to make that smaller if i can do it would be awesome.<br> Because i will do that to 15, If i write that 15 times it will be bigger and more hard to write for me.<br> If there is a smaller was to make that can you guys please tell me?</p>
0
2016-10-15T18:52:06Z
40,062,991
<p>Just use the <code>itertools</code> library</p> <pre><code>from itertools import permutations lst = list(range(3)) result = list(permutations(lst, 2)) print(result) =&gt; [(0, 1), (0, 2), (1, 0), (1, 2), (2, 0), (2, 1)] print(list(permutations(lst, 3))) =&gt; [(0, 1, 2), (0, 2, 1), (1, 0, 2), (1, 2, 0), (2, 0, 1), (2, 1, 0)] </code></pre>
0
2016-10-15T18:56:03Z
[ "python", "python-3.x", "permutation" ]
Problems with querying multiindex table in HDF when using data_columns
40,062,965
<p>I try to query a multi-index table in a pandas HDF store, but it fails when using a query over the index and data_columns at the same time. This only occurs when <code>data_columns=True</code>. Any idea if this is expected, or how to avoid if I don't want to explicitly specify the data_columns?</p> <p>See the following example, it seems it does not recognize the index as a valid reference: </p> <pre><code>import pandas as pd import numpy as np file_path = 'D:\\test_store.h5' np.random.seed(1234) pd.set_option('display.max_rows',4) # simulate some data index = pd.MultiIndex.from_product([np.arange(10000,10200), pd.date_range('19800101',periods=500)], names=['id','date']) df = pd.DataFrame(dict(id2=np.random.randint(0, 1000, size=len(index)), w=np.random.randn(len(index))), index=index).reset_index().set_index(['id', 'date']) # store the data store = pd.HDFStore(file_path,mode='a',complib='blosc', complevel=9) store.append('df_dc_None', df, data_columns=None) store.append('df_dc_explicit', df, data_columns=['id2', 'w']) store.append('df_dc_True', df, data_columns=True) store.close() # query the data start = '19810201' print(pd.read_hdf(file_path,'df_dc_None', where='date&gt;start &amp; id=10000')) print(pd.read_hdf(file_path,'df_dc_True', where='id2&gt;500')) print(pd.read_hdf(file_path,'df_dc_explicit', where='date&gt;start &amp; id2&gt;500')) try: print(pd.read_hdf(file_path,'df_dc_True', where='date&gt;start &amp; id2&gt;500')) except ValueError as err: print(err) </code></pre>
2
2016-10-15T18:53:58Z
40,069,108
<p>It's an interesting question, indeed!</p> <p>I can't explain the following difference (why do we have index columns indexed when using <code>data_columns=None</code> (default due to the <code>docstring</code> of the <code>HDFStore.append</code> method) and we don't have them indexed when using <code>data_columns=True</code>):</p> <pre><code>In [114]: store.get_storer('df_dc_None').table Out[114]: /df_dc_None/table (Table(100000,), shuffle, blosc(9)) '' description := { "index": Int64Col(shape=(), dflt=0, pos=0), "values_block_0": Int32Col(shape=(1,), dflt=0, pos=1), "values_block_1": Float64Col(shape=(1,), dflt=0.0, pos=2), "date": Int64Col(shape=(), dflt=0, pos=3), "id": Int64Col(shape=(), dflt=0, pos=4)} byteorder := 'little' chunkshape := (1820,) autoindex := True colindexes := { "date": Index(6, medium, shuffle, zlib(1)).is_csi=False, "id": Index(6, medium, shuffle, zlib(1)).is_csi=False, "index": Index(6, medium, shuffle, zlib(1)).is_csi=False} In [115]: store.get_storer('df_dc_True').table Out[115]: /df_dc_True/table (Table(100000,), shuffle, blosc(9)) '' description := { "index": Int64Col(shape=(), dflt=0, pos=0), "values_block_0": Int64Col(shape=(1,), dflt=0, pos=1), "values_block_1": Int64Col(shape=(1,), dflt=0, pos=2), "id2": Int32Col(shape=(), dflt=0, pos=3), "w": Float64Col(shape=(), dflt=0.0, pos=4)} byteorder := 'little' chunkshape := (1820,) autoindex := True colindexes := { "w": Index(6, medium, shuffle, zlib(1)).is_csi=False, "index": Index(6, medium, shuffle, zlib(1)).is_csi=False, "id2": Index(6, medium, shuffle, zlib(1)).is_csi=False} </code></pre> <p>NOTE: pay attention at <code>colindexes</code> in the output above.</p> <p>But using the following simple hack we can "fix" this:</p> <pre><code>In [116]: store.append('df_dc_all', df, data_columns=df.head(1).reset_index().columns) In [118]: store.get_storer('df_dc_all').table Out[118]: /df_dc_all/table (Table(100000,), shuffle, blosc(9)) '' description := { "index": Int64Col(shape=(), dflt=0, pos=0), "id": Int64Col(shape=(), dflt=0, pos=1), "date": Int64Col(shape=(), dflt=0, pos=2), "id2": Int32Col(shape=(), dflt=0, pos=3), "w": Float64Col(shape=(), dflt=0.0, pos=4)} byteorder := 'little' chunkshape := (1820,) autoindex := True colindexes := { "w": Index(6, medium, shuffle, zlib(1)).is_csi=False, "date": Index(6, medium, shuffle, zlib(1)).is_csi=False, "id": Index(6, medium, shuffle, zlib(1)).is_csi=False, "index": Index(6, medium, shuffle, zlib(1)).is_csi=False, "id2": Index(6, medium, shuffle, zlib(1)).is_csi=False} </code></pre> <p>check:</p> <pre><code>In [119]: pd.read_hdf(file_path,'df_dc_all', where='date&gt;start &amp; id2&gt;500') Out[119]: id2 w id date 10000 1981-02-02 935 0.245637 1981-02-04 994 0.291287 ... ... ... 10199 1981-05-11 680 -0.370745 1981-05-12 812 -0.880742 [10121 rows x 2 columns] </code></pre>
2
2016-10-16T10:08:57Z
[ "python", "pandas", "dataframe", "pytables", "hdf" ]
Fill a multidimensional array efficiently that have many if else statements
40,063,034
<p>I want to fill an 4dim numpy array in a specific and efficient way. Because I don't know better I startet to write the code with if else statements, but that doesn't look nice, is probably slow and I also can not be really sure if I thought about every combination. Here is the code which I stopped writing down:</p> <pre><code>sercnew2 = numpy.zeros((gn, gn, gn, gn)) for x1 in range(gn): for x2 in range(gn): for x3 in range(gn): for x4 in range(gn): if x1 == x2 == x3 == x4: sercnew2[x1, x2, x3, x4] = ewp[x1] elif x1 == x2 == x3 != x4: sercnew2[x1, x2, x3, x4] = ewp[x1] * ewp[x4] elif x1 == x2 == x4 != x3: sercnew2[x1, x2, x3, x4] = ewp[x1] * ewp[x3] elif x1 == x3 == x4 != x2: sercnew2[x1, x2, x3, x4] = ewp[x1] * ewp[x2] elif x2 == x3 == x4 != x1: sercnew2[x1, x2, x3, x4] = ewp[x2] * ewp[x1] elif x1 == x2 != x3 == x4: sercnew2[x1, x2, x3, x4] = ewp[x1] * ewp[x3] elif ... many more combinations which have to be considered </code></pre> <p>So basically what should happen is, that if all variables (x1, x2, x3, x4) are different from each other, the entry would be: </p> <pre><code>sercnew2[x1, x2, x3, x4] = ewp[x1]* ewp[x2] * ewp[x3] * ewp[x4] </code></pre> <p>Now if lets say the variable x2 and x4 is the same then:</p> <pre><code>sercnew2[x1, x2, x3, x4] = ewp[x1]* ewp[x2] * ewp[x3] </code></pre> <p>Others examples can be seen in the code above. Basically if two or more variables are the same, then I only consider on of them. I hope the pattern is clear. Otherwise please let me note and I will try to express my problem better. I am pretty sure, that there is a much more intelligent way to do it. Hope you know better and thanks in advance :) </p>
4
2016-10-15T18:59:57Z
40,063,118
<p>I don't really know what you mean by saying that those variables are the same, but if indeed they are, than all you have to do is just use <code>set()</code>.</p> <pre><code>from functools import reduce from operator import mul sercnew2 = numpy.zeros((gn, gn, gn, gn)) for x1 in range(gn): for x2 in range(x1, gn): for x3 in range(x2, gn): for x4 in range(x3, gn): set_ = [ewp[n] for n in set([x1, x2, x3, x4])] sercnew2[x1, x2, x3, x4] = reduce(mul, set_, 1) </code></pre> <p>The way it works is that it creates a <code>set()</code> which delete duplicates, and later with <code>reduce</code> function I pick first number from the <code>set_</code>, multiplies it with <code>1</code> (the initializer value), and the result of this is going to be passed to <code>reduce</code> as first argument, and second will be the second item from <code>set_</code>. Sorry for my bad explanation.</p>
3
2016-10-15T19:06:56Z
[ "python", "arrays", "numpy" ]
Fill a multidimensional array efficiently that have many if else statements
40,063,034
<p>I want to fill an 4dim numpy array in a specific and efficient way. Because I don't know better I startet to write the code with if else statements, but that doesn't look nice, is probably slow and I also can not be really sure if I thought about every combination. Here is the code which I stopped writing down:</p> <pre><code>sercnew2 = numpy.zeros((gn, gn, gn, gn)) for x1 in range(gn): for x2 in range(gn): for x3 in range(gn): for x4 in range(gn): if x1 == x2 == x3 == x4: sercnew2[x1, x2, x3, x4] = ewp[x1] elif x1 == x2 == x3 != x4: sercnew2[x1, x2, x3, x4] = ewp[x1] * ewp[x4] elif x1 == x2 == x4 != x3: sercnew2[x1, x2, x3, x4] = ewp[x1] * ewp[x3] elif x1 == x3 == x4 != x2: sercnew2[x1, x2, x3, x4] = ewp[x1] * ewp[x2] elif x2 == x3 == x4 != x1: sercnew2[x1, x2, x3, x4] = ewp[x2] * ewp[x1] elif x1 == x2 != x3 == x4: sercnew2[x1, x2, x3, x4] = ewp[x1] * ewp[x3] elif ... many more combinations which have to be considered </code></pre> <p>So basically what should happen is, that if all variables (x1, x2, x3, x4) are different from each other, the entry would be: </p> <pre><code>sercnew2[x1, x2, x3, x4] = ewp[x1]* ewp[x2] * ewp[x3] * ewp[x4] </code></pre> <p>Now if lets say the variable x2 and x4 is the same then:</p> <pre><code>sercnew2[x1, x2, x3, x4] = ewp[x1]* ewp[x2] * ewp[x3] </code></pre> <p>Others examples can be seen in the code above. Basically if two or more variables are the same, then I only consider on of them. I hope the pattern is clear. Otherwise please let me note and I will try to express my problem better. I am pretty sure, that there is a much more intelligent way to do it. Hope you know better and thanks in advance :) </p>
4
2016-10-15T18:59:57Z
40,063,184
<p>You can do it in a single for loop too. Building on Divakar's Trick for a list of indexes, the first thing we need to do is figure out how to extract only the unique indices of a given element in the 4d array <code>sercnew2</code>.</p> <p>One of the fastest ways to do this (Refer: <a href="https://www.peterbe.com/plog/uniqifiers-benchmark" rel="nofollow">https://www.peterbe.com/plog/uniqifiers-benchmark</a>) is using sets. Then, we simply have to initialize <code>sercnew2</code> as an array of ones, rather than zeros.</p> <pre><code>from itertools import product import numpy as np sercnew2 = np.ones((gn, gn, gn, gn)) n_dims=4 idx = list(product(np.arange(gn), repeat=n_dims)) for i,j,k,l in idx: unique_items = set((i,j,k,l)) for ele in unique_items: sercnew2[i,j,k,l] *= ewp[ele] </code></pre> <p>EDIT: As @unutbu suggested, we could also use the cartesian_product function from <a href="http://stackoverflow.com/a/11146645/5714445">http://stackoverflow.com/a/11146645/5714445</a> to speed up the initialization of <code>idx</code></p> <p>Edit2: In case you are having difficulty understanding what <code>product</code> from <code>itertools</code> does, it provides all permutations. For instance, suppose <code>gn=2</code>, with repeat dimension set to 4, you get</p> <pre><code>[0, 0, 0, 0] [0, 0, 0, 1] [0, 0, 1, 0] [0, 0, 1, 1] [0, 1, 0, 0] [0, 1, 0, 1] [0, 1, 1, 0] [0, 1, 1, 1] [1, 0, 0, 0] [1, 0, 0, 1] [1, 0, 1, 0] [1, 0, 1, 1] [1, 1, 0, 0] [1, 1, 0, 1] [1, 1, 1, 0] [1, 1, 1, 1] </code></pre>
2
2016-10-15T19:14:25Z
[ "python", "arrays", "numpy" ]
Fill a multidimensional array efficiently that have many if else statements
40,063,034
<p>I want to fill an 4dim numpy array in a specific and efficient way. Because I don't know better I startet to write the code with if else statements, but that doesn't look nice, is probably slow and I also can not be really sure if I thought about every combination. Here is the code which I stopped writing down:</p> <pre><code>sercnew2 = numpy.zeros((gn, gn, gn, gn)) for x1 in range(gn): for x2 in range(gn): for x3 in range(gn): for x4 in range(gn): if x1 == x2 == x3 == x4: sercnew2[x1, x2, x3, x4] = ewp[x1] elif x1 == x2 == x3 != x4: sercnew2[x1, x2, x3, x4] = ewp[x1] * ewp[x4] elif x1 == x2 == x4 != x3: sercnew2[x1, x2, x3, x4] = ewp[x1] * ewp[x3] elif x1 == x3 == x4 != x2: sercnew2[x1, x2, x3, x4] = ewp[x1] * ewp[x2] elif x2 == x3 == x4 != x1: sercnew2[x1, x2, x3, x4] = ewp[x2] * ewp[x1] elif x1 == x2 != x3 == x4: sercnew2[x1, x2, x3, x4] = ewp[x1] * ewp[x3] elif ... many more combinations which have to be considered </code></pre> <p>So basically what should happen is, that if all variables (x1, x2, x3, x4) are different from each other, the entry would be: </p> <pre><code>sercnew2[x1, x2, x3, x4] = ewp[x1]* ewp[x2] * ewp[x3] * ewp[x4] </code></pre> <p>Now if lets say the variable x2 and x4 is the same then:</p> <pre><code>sercnew2[x1, x2, x3, x4] = ewp[x1]* ewp[x2] * ewp[x3] </code></pre> <p>Others examples can be seen in the code above. Basically if two or more variables are the same, then I only consider on of them. I hope the pattern is clear. Otherwise please let me note and I will try to express my problem better. I am pretty sure, that there is a much more intelligent way to do it. Hope you know better and thanks in advance :) </p>
4
2016-10-15T18:59:57Z
40,063,414
<p>Really hoping that I have got it! Here's a vectorized approach -</p> <pre><code>from itertools import product n_dims = 4 # Number of dims # Create 2D array of all possible combinations of X's as rows idx = np.sort(np.array(list(product(np.arange(gn), repeat=n_dims))),axis=1) # Get all X's indexed values from ewp array vals = ewp[idx] # Set the duplicates along each row as 1s. With the np.prod coming up next, #these 1s would not affect the result, which is the expected pattern here. vals[:,1:][idx[:,1:] == idx[:,:-1]] = 1 # Perform product along each row and reshape into multi-dim array out = vals.prod(1).reshape([gn]*n_dims) </code></pre>
3
2016-10-15T19:37:55Z
[ "python", "arrays", "numpy" ]
Casting an array of C structs to a numpy array
40,063,080
<p>A function I'm calling from a shared library returns a structure called info similar to this:</p> <pre><code>typedef struct cmplx { double real; double imag; } cmplx; typedef struct info{ char *name; int arr_len; double *real_data cmplx *cmplx_data; } info; </code></pre> <p>One of the fields of the structure is an array of doubles while the other is an array of complex numbers. How do I convert the array of complex numbers to a numpy array? For doubles I have the following:</p> <pre><code>from ctypes import * import numpy as np class cmplx(Structure): _fields_ = [("real", c_double), ("imag", c_double)] class info(Structure): _fields_ = [("name", c_char_p), ("arr_len", c_int), ("real_data", POINTER(c_double)), ("cmplx_data", POINTER(cmplx))] c_func.restype = info ret_val = c_func() data = np.ctypeslib.as_array(ret_val.contents.real_data, shape=(info.contents.arr_len,)) </code></pre> <p>Is there a numpy one liner for complex numbers? I can do this using loops.</p>
0
2016-10-15T19:04:15Z
40,063,208
<p>Define your field as double and make a complex view with numpy:</p> <pre><code>class info(Structure): _fields_ = [("name", c_char_p), ("arr_len", c_int), ("real_data", POINTER(c_double)), ("cmplx_data", POINTER(c_double))] c_func.restype = info ret_val = c_func() data = np.ctypeslib.as_array(ret_val.contents.real_data, shape=(info.contents.arr_len,)) complex_data = np.ctypeslib.as_array(ret_val.contents.cmplx_data, shape=(info.contents.arr_len,2)).view('complex128') </code></pre>
0
2016-10-15T19:15:43Z
[ "python", "arrays", "python-3.x", "numpy", "ctypes" ]
Selenium unable to start Firefox
40,063,088
<p>I'm trying to make a simple scraping program but I am not able to get Selenium working with Firefox. I installed <a href="https://developer.mozilla.org/en-US/docs/Mozilla/QA/Marionette/WebDriver" rel="nofollow">Marionette</a> but that didn't solve anything. When I type this:</p> <pre><code>from selenium import webdriver driver = webdriver.Firefox() </code></pre> <p>I get this error:</p> <blockquote> <p>AttributeError: 'Service' object has no attribute 'process'</p> </blockquote> <p>Also, PyCharm gives this warning:</p> <blockquote> <p>'Firefox' is not callable</p> </blockquote> <p>How can I solve this?</p>
0
2016-10-15T19:04:51Z
40,063,192
<p>Try using the complete path to firefox executable. Maybe it's not listed in you variable environment path..</p> <pre><code>from selenium import webdriver driver = webdriver.Firefox("/path/to/firefox") </code></pre> <p>This should tell your script where to find the firefox executable.</p> <p><strong>Edit:</strong></p> <p>If you're using Windows, try using double slashes. </p> <p>I.e.: <code>'C://Program Files (x86)//Mozilla Firefox//firefox.exe'</code> </p> <p>Or marking it as a raw string:</p> <p>I.e.: <code>r'C:/Program Files (x86)/Mozilla Firefox/firefox.exe'</code></p>
0
2016-10-15T19:14:53Z
[ "python", "selenium", "firefox", "pycharm" ]
Selenium unable to start Firefox
40,063,088
<p>I'm trying to make a simple scraping program but I am not able to get Selenium working with Firefox. I installed <a href="https://developer.mozilla.org/en-US/docs/Mozilla/QA/Marionette/WebDriver" rel="nofollow">Marionette</a> but that didn't solve anything. When I type this:</p> <pre><code>from selenium import webdriver driver = webdriver.Firefox() </code></pre> <p>I get this error:</p> <blockquote> <p>AttributeError: 'Service' object has no attribute 'process'</p> </blockquote> <p>Also, PyCharm gives this warning:</p> <blockquote> <p>'Firefox' is not callable</p> </blockquote> <p>How can I solve this?</p>
0
2016-10-15T19:04:51Z
40,065,022
<p>Try:</p> <pre><code>driver = webdriver.Firefox(executable_path="path to your driver") </code></pre> <p>eg: <code>driver = webdriver.Firefox(executable_path="C:\Python27\wires.exe")</code></p>
0
2016-10-15T22:46:38Z
[ "python", "selenium", "firefox", "pycharm" ]
Python tkinter moving object in def that as been created in another def
40,063,124
<p>I am creating flappy bird style game. And my problem is that i cant move tubes that has been created on another def. My code is</p> <pre><code>from tkinter import * from random import randint window = Tk() c = Canvas(window, width=800, height=800, bg='steelblue') tube11 = randint(600, 650) tube12 = randint(400, 700) def createtubes(): tube1 = c.create_rectangle(800, 800, tube11, tube12, fill='green') tube2 = c.create_rectangle(800, 0, tube11, 200, fill='green') def automovement(): if True: c.move(tube1, -3.5, 0) c.move(tube2, -3.5, 0) window.update_idletasks() window.after(10, automovement) window.after(60, createtubes) window.after(10, automovement) c.pack() window.mainloop() </code></pre>
0
2016-10-15T19:07:55Z
40,063,393
<p>Try creating a class</p> <pre><code>from tkinter import * from random import randint window = Tk() c = Canvas(window, width=800, height=800, bg='steelblue') tube11 = randint(600, 650) tube12 = randint(400, 700) class Tubes: def __init__(self): self.createtubes() def createtubes(self): self.tube1 = c.create_rectangle(800, 800, tube11, tube12, fill='green') self.tube2 = c.create_rectangle(800, 0, tube11, 200, fill='green') def automovement(self): if True: c.move(self.tube1, -3.5, 0) c.move(self.tube2, -3.5, 0) window.update_idletasks() window.after(10, self.automovement) tube = Tubes() window.after(10, tube.automovement) c.pack() window.mainloop() </code></pre>
1
2016-10-15T19:36:01Z
[ "python", "python-3.x", "tkinter" ]
Python tkinter moving object in def that as been created in another def
40,063,124
<p>I am creating flappy bird style game. And my problem is that i cant move tubes that has been created on another def. My code is</p> <pre><code>from tkinter import * from random import randint window = Tk() c = Canvas(window, width=800, height=800, bg='steelblue') tube11 = randint(600, 650) tube12 = randint(400, 700) def createtubes(): tube1 = c.create_rectangle(800, 800, tube11, tube12, fill='green') tube2 = c.create_rectangle(800, 0, tube11, 200, fill='green') def automovement(): if True: c.move(tube1, -3.5, 0) c.move(tube2, -3.5, 0) window.update_idletasks() window.after(10, automovement) window.after(60, createtubes) window.after(10, automovement) c.pack() window.mainloop() </code></pre>
0
2016-10-15T19:07:55Z
40,064,624
<p>You can also use tags option on your rectangles.</p> <pre><code>tube1 = c.create_rectangle(800, 800, tube11, tube12, fill='green', tags='tube') tube2 = c.create_rectangle(800, 0, tube11, 200, fill='green', tags='tube') </code></pre> <p>And in your function only one move :</p> <pre><code>c.move('tube', -3.5, 0) </code></pre>
1
2016-10-15T21:57:28Z
[ "python", "python-3.x", "tkinter" ]
multiple conditions to a if loop python
40,063,156
<p>Hello I'm having some problems with some code I am writing for a school and its not working. It wont run through the whole loop but all the code looks right to me. Does anyone have any ideas?</p> <pre><code> User_Input = input ( "Please enter a message that is no longer than 7 characters." ) User_Input_Length = len ( User_Input ) if { User_Input_Length &gt;= 7 and User_Input_Length == 1 }: print ( "Your message is odd." ) elif { User_Input_Length &gt;= 7 and User_Input_Length == 3 }: print ( "Your message is odd." ) elif { User_Input_Legnth &gt;= 7 and User_Input_Length == 5 }: print ( "Your message is odd." ) elif { User_Input_Length &gt;= 7 and User_Input_Length == 7 }: print ( "Your message is odd" ) elif { User_Input_Length &gt;= 7 and User_Input_Length == 2 }: print ( "Your message is even" ) elif { User_Input_Length &gt;= 7 and User_Input_Length == 4 }: print ( "Your message is even" ) elif { User_Input_Length &gt;= 7 and User_Input_Length == 6 }: print ( "Your string is even" ) else: print ( "The string is too long." ) print ( "Goodbye" ) </code></pre>
-2
2016-10-15T19:10:58Z
40,063,238
<p>You're not testing what you think you are. Your expressions look like:</p> <pre><code>{ User_Input_Length &gt;= 7 and User_Input_Length == 1 } </code></pre> <p>In Python, <code>{}</code> encloses a <code>set</code> or <code>dict</code> (or comprehension of either). This is thus a set containing one <code>bool</code> value. Per <a href="https://docs.python.org/3/library/stdtypes.html#truth-value-testing" rel="nofollow">truth value testing</a>, any set that contains members is regarded as True, so your first test will be the only branch taken. </p> <p>Secondly, the inner (unchecked) condition tests <code>User_Input_Length</code> for simultaneously being 7 or greater <strong>and</strong> some other value; only the one with 7 could ever be true. </p>
3
2016-10-15T19:18:13Z
[ "python" ]
multiple conditions to a if loop python
40,063,156
<p>Hello I'm having some problems with some code I am writing for a school and its not working. It wont run through the whole loop but all the code looks right to me. Does anyone have any ideas?</p> <pre><code> User_Input = input ( "Please enter a message that is no longer than 7 characters." ) User_Input_Length = len ( User_Input ) if { User_Input_Length &gt;= 7 and User_Input_Length == 1 }: print ( "Your message is odd." ) elif { User_Input_Length &gt;= 7 and User_Input_Length == 3 }: print ( "Your message is odd." ) elif { User_Input_Legnth &gt;= 7 and User_Input_Length == 5 }: print ( "Your message is odd." ) elif { User_Input_Length &gt;= 7 and User_Input_Length == 7 }: print ( "Your message is odd" ) elif { User_Input_Length &gt;= 7 and User_Input_Length == 2 }: print ( "Your message is even" ) elif { User_Input_Length &gt;= 7 and User_Input_Length == 4 }: print ( "Your message is even" ) elif { User_Input_Length &gt;= 7 and User_Input_Length == 6 }: print ( "Your string is even" ) else: print ( "The string is too long." ) print ( "Goodbye" ) </code></pre>
-2
2016-10-15T19:10:58Z
40,063,244
<p>Those braces are for defining sets, and a non-empty set always evaluates to true, so your code will always evaluate the first if.</p> <p>Python doesn't requires parenthesis (or braces) around if statements.</p>
1
2016-10-15T19:19:02Z
[ "python" ]
multiple conditions to a if loop python
40,063,156
<p>Hello I'm having some problems with some code I am writing for a school and its not working. It wont run through the whole loop but all the code looks right to me. Does anyone have any ideas?</p> <pre><code> User_Input = input ( "Please enter a message that is no longer than 7 characters." ) User_Input_Length = len ( User_Input ) if { User_Input_Length &gt;= 7 and User_Input_Length == 1 }: print ( "Your message is odd." ) elif { User_Input_Length &gt;= 7 and User_Input_Length == 3 }: print ( "Your message is odd." ) elif { User_Input_Legnth &gt;= 7 and User_Input_Length == 5 }: print ( "Your message is odd." ) elif { User_Input_Length &gt;= 7 and User_Input_Length == 7 }: print ( "Your message is odd" ) elif { User_Input_Length &gt;= 7 and User_Input_Length == 2 }: print ( "Your message is even" ) elif { User_Input_Length &gt;= 7 and User_Input_Length == 4 }: print ( "Your message is even" ) elif { User_Input_Length &gt;= 7 and User_Input_Length == 6 }: print ( "Your string is even" ) else: print ( "The string is too long." ) print ( "Goodbye" ) </code></pre>
-2
2016-10-15T19:10:58Z
40,063,330
<p>you must use parentheses for the parameters of the <code>if</code> condition, and be careful about the placement of your code blocks: unlike C which uses <code>;</code> as a delimiter, python knows your block is over only because it jumps to the next line.</p> <pre><code>if(1 &lt; 2) and (2 &lt; 3): print("true") elif(1 &gt; 2): print("false") </code></pre>
0
2016-10-15T19:27:09Z
[ "python" ]
pdfkit - python : 'str' object has no attribute decode
40,063,205
<p>I am attempting to use pdfkit to convert string html to a pdf file. This is what I am doing</p> <pre><code> try: options = { 'page-size': 'A4', 'margin-top': '0.75in', 'margin-right': '0.75in', 'margin-bottom': '0.75in', 'margin-left': '0.75in', } config = pdfkit.configuration(wkhtmltopdf="/usr/local/bin/wkhtmltopdf") str= "Hello!!" pdfkit.from_string(str,"Somefile.pdf",options=options,configuration=config) return HttpResponse("Works") except Exception as e: return HttpResponse(str(e)) </code></pre> <p>however at <code>from_string</code> I get the exception 'str' object has no attribute decode. Any suggestions on how I can fix this ? I am using Python 3.5.1</p>
0
2016-10-15T19:15:32Z
40,063,760
<p>Try replacing the config line with this - path to the binary is provided as a bytes object:</p> <pre><code>config = pdfkit.configuration(wkhtmltopdf=bytes("/usr/local/bin/wkhtmltopdf", 'utf8')) </code></pre> <p>Reference: <a href="https://github.com/JazzCore/python-pdfkit/issues/32" rel="nofollow">https://github.com/JazzCore/python-pdfkit/issues/32</a></p>
1
2016-10-15T20:14:21Z
[ "python", "pdfkit" ]
Python dataframe sum rows
40,063,242
<p>If I have a dataframe with <code>n</code> rows, is there a way to set the ith row to be sum of <code>row[i]</code> and <code>row[i-1]</code> and do this so that the assignment to earlier rows is reflected in the latter rows? I would really like to avoid loops if possible.</p> <p>Example DF:</p> <pre><code> SPY AAPL GOOG 2011-01-10 0.44 -0.81 1.80 2011-01-11 0.00 0.00 0.00 2011-01-12 -1.11 -2.77 -0.86 2011-01-13 -0.91 -4.02 -0.68 </code></pre> <p>Sample pseudo code of summing two rows:</p> <pre><code>DF[2011-01-11] = DF[2011-01-10] + DF[2011-01-11] DF[2011-01-12] = DF[2011-01-11] + DF[2011-01-12] </code></pre> <p>and so on.</p>
4
2016-10-15T19:18:49Z
40,063,294
<p>based on your question, you are looking for a cumulative sum of each columns. you could use the <code>cumsum()</code> method</p> <pre><code>DF.cumsum() SPY AAPL GOOG 2011-01-10 0.4400 -0.8100 1.8000 2011-01-11 0.4400 -0.8100 1.8000 2011-01-12 -0.6700 -3.5800 0.9400 2011-01-13 -1.5800 -7.6000 0.2600 </code></pre>
2
2016-10-15T19:23:47Z
[ "python", "pandas", "dataframe" ]
Python dataframe sum rows
40,063,242
<p>If I have a dataframe with <code>n</code> rows, is there a way to set the ith row to be sum of <code>row[i]</code> and <code>row[i-1]</code> and do this so that the assignment to earlier rows is reflected in the latter rows? I would really like to avoid loops if possible.</p> <p>Example DF:</p> <pre><code> SPY AAPL GOOG 2011-01-10 0.44 -0.81 1.80 2011-01-11 0.00 0.00 0.00 2011-01-12 -1.11 -2.77 -0.86 2011-01-13 -0.91 -4.02 -0.68 </code></pre> <p>Sample pseudo code of summing two rows:</p> <pre><code>DF[2011-01-11] = DF[2011-01-10] + DF[2011-01-11] DF[2011-01-12] = DF[2011-01-11] + DF[2011-01-12] </code></pre> <p>and so on.</p>
4
2016-10-15T19:18:49Z
40,063,308
<p>Use <code>DF.shift()</code></p> <pre><code>DF + DF.shift() </code></pre>
2
2016-10-15T19:25:09Z
[ "python", "pandas", "dataframe" ]
How can I ensure that a function takes a certain amount of time in Go?
40,063,269
<p>I am implementing EnScrypt for an SQRL client in Go. The function needs to run until it has used a minimum amount of CPU time. My Python code looks like this:</p> <pre><code>def enscrypt_time(salt, password, seconds, n=9, r=256): N = 1 &lt;&lt; n start = time.process_time() end = start + seconds data = acc = scrypt.hash(password, salt, N, r, 1, 32) i = 1 while time.process_time() &lt; end: data = scrypt.hash(password, data, N, r, 1, 32) acc = xor_bytes(acc, data) i += 1 return i, time.process_time() - start, acc </code></pre> <p>Converting this to Go is pretty simple except for the <code>process_time</code> function. I can't use <code>time.Time</code> / <code>Timer</code> because those measure wall-clock time (which is affected by everything else that may be running on the system). I need the CPU time actually used, ideally by the function, or at least by the thread or process it is running in.</p> <p>What is the Go equivalent of <code>process_time</code>?</p> <p><a href="https://docs.python.org/3/library/time.html#time.process_time" rel="nofollow">https://docs.python.org/3/library/time.html#time.process_time</a></p>
5
2016-10-15T19:21:07Z
40,066,992
<p>You may use <a href="https://golang.org/pkg/runtime/#LockOSThread" rel="nofollow"><code>runtime.LockOSThread()</code></a> to wire the calling goroutine to its current OS thread. This will ensure that no other goroutines will be scheduled to this thread, so your goroutine will run and not get interrupted or put on hold. No other goroutines will interfere when thread is locked.</p> <p>After this, you just need a loop until the given seconds have passed. You must call <a href="https://golang.org/pkg/runtime/#UnlockOSThread" rel="nofollow"><code>runtime.UnlockOSThread()</code></a> to "release" the thread and make it available for other goroutines for execution, best done as a <code>defer</code> statement.</p> <p>See this example:</p> <pre><code>func runUntil(end time.Time) { runtime.LockOSThread() defer runtime.UnlockOSThread() for time.Now().Before(end) { } } </code></pre> <p>To make it wait for 2 seconds, it could look like this:</p> <pre><code>start := time.Now() end := start.Add(time.Second * 2) runUntil(end) fmt.Println("Verify:", time.Now().Sub(start)) </code></pre> <p>This prints for example:</p> <pre><code>Verify: 2.0004556s </code></pre> <p>Of course you can specify less than a second too, e.g. to wait for 100 ms:</p> <pre><code>start := time.Now() runUntil(start.Add(time.Millisecond * 100)) fmt.Println("Verify:", time.Now().Sub(start)) </code></pre> <p>Output:</p> <pre><code>Verify: 100.1278ms </code></pre> <p>You may use a different version of this function if that suits you better, one that takes the amount of time to "wait" as a value of <a href="https://golang.org/pkg/time/#Duration" rel="nofollow"><code>time.Duration</code></a>:</p> <pre><code>func wait(d time.Duration) { runtime.LockOSThread() defer runtime.UnlockOSThread() for end := time.Now().Add(d); time.Now().Before(end); { } } </code></pre> <p>Using this:</p> <pre><code>start = time.Now() wait(time.Millisecond * 200) fmt.Println("Verify:", time.Now().Sub(start)) </code></pre> <p>Output:</p> <pre><code>Verify: 200.1546ms </code></pre> <p><strong>Note:</strong> Note that the loops in the above functions will use CPU relentlessly as there is no sleep or blocking IO in them, they will just query the current system time and compare it to the deadline.</p> <p><strong>What if the attacker increases system load by multiple concurrent attempts?</strong></p> <p>The Go runtime limits the system threads that can simultaneously execute goroutines. This is controlled by <a href="https://golang.org/pkg/runtime/#GOMAXPROCS" rel="nofollow"><code>runtime.GOMAXPROCS()</code></a>, so this is already a limitation. It defaults to the number of available CPU cores, and you can change it anytime. This also poses a bottleneck though, as by using <code>runtime.LockOSThread()</code>, if the number of locked threads equals to <code>GOMAXPROCS</code> at any given time, that would block execution of other goroutines until a thread is unlocked.</p> <p>See related questions:</p> <p><a href="http://stackoverflow.com/questions/39245660/number-of-threads-used-by-go-runtime">Number of threads used by Go runtime</a></p> <p><a href="http://stackoverflow.com/questions/28186361/why-does-it-not-create-many-threads-when-many-goroutines-are-blocked-in-writing/28186656#28186656">Why does it not create many threads when many goroutines are blocked in writing file in golang?</a></p>
3
2016-10-16T04:54:42Z
[ "python", "go", "time", "sqrl" ]
Python - How can i print a certain dictionary field from many dictionaries within a list?
40,063,316
<p>I am currently working on a Guess Who like game for school work and I cannot seem to get this to work. What I am trying to do is get the field "Name" printed from all the dictionaries below within a list.</p> <pre><code> Greg = {"Name":"Greg", "HairLength":"Short", "HairColour":"Brown", "FacialHair":"Yes", "Jewellery":"Yes", "Hat":"No", "Lipstick":"No", "Gender":"Male"} Chris = {"Name":"Chris", "HairLength":"Long", "HairColour":"Blonde", "FacialHair":"No", "Jewellery":"No","Hat":"Yes", "Lipstick":"Yes", "Gender":"Male"} Jason = {"Name":"Jason", "HairLength":"Short", "HairColour":"Brown", "FacialHair":"Yes", "Jewellery":"No","Hat":"Yes", "Lipstick":"No", "Gender":"Male"} Clancy = {"Name":"Clancy", "HairLength":"Bald", "HairColour":"Red", "FacialHair":"Yes", "Jewellery":"No", "Hat":"No","Lipstick":"No", "Gender":"Male"} Betty = {"Name":"Betty", "HairLength":"Short", "HairColour":"Blonde", "FacialHair":"No", "Jewellery":"Yes","Hat":"Yes", "Lipstick":"Yes", "Gender":"Female"} Helen = {"Name":"Helen", "HairLength":"Short", "HairColour":"Brown", "FacialHair":"No", "Jewellery":"No", "Hat":"No","Lipstick":"Yes", "Gender":"Female"} Selena = {"Name":"Selena", "HairLength":"Long", "HairColour":"Brown", "FacialHair":"No", "Jewellery":"Yes","Hat":"No", "Lipstick":"No", "Gender":"Female"} Jacqueline = {"Name":"Jacqueline", "HairLength":"Long", "HairColour":"Red", "FacialHair":"Yes", "Jewellery":"Yes", "Hat":"No","Lipstick":"No", "Gender":"Female"} AISuspects = ([Greg, Chris, Jason, Clancy, Betty, Selena, Helen, Jacqueline]) UserSuspects = ([Greg, Chris, Jason, Clancy, Betty, Selena, Helen, Jacqueline]) print("AISuspects:") #Here i want it to print the field "Name" in every dictionary within the list AISuspects print("UserSuspects:") #Here i want it to print the field "Name" in every dictionary within the list UserSuspects </code></pre> <p>Expected output and current output after the solution:</p> <p>AI Suspects: ['Greg', 'Chris', 'Jason', 'Clancy', 'Betty', 'Selena', 'Helen', 'Jacqueline']</p> <p>User Suspects: ['Greg', 'Chris', 'Jason', 'Clancy', 'Betty', 'Selena', 'Helen', 'Jacqueline']</p>
0
2016-10-15T19:26:07Z
40,063,352
<p>You can use a list comprehension to get a list of all the suspects' names</p> <pre><code>suspects_names = [suspect['Name'] for suspect in AISuspects] </code></pre> <p>Then you can use <code>print(' '.join(suspect_names))</code></p> <p>If you don't mind printing each name in a new line, just use a for loop:</p> <pre><code>for suspect in AISuspects: print(suspect['Name']) </code></pre> <p>Take care of those parenthesis around the lists definitions, you don't need them and they're usually used to define tuples, so I'd get rid of them</p>
5
2016-10-15T19:30:20Z
[ "python", "list", "dictionary", "printing", "output" ]
Python - How can i print a certain dictionary field from many dictionaries within a list?
40,063,316
<p>I am currently working on a Guess Who like game for school work and I cannot seem to get this to work. What I am trying to do is get the field "Name" printed from all the dictionaries below within a list.</p> <pre><code> Greg = {"Name":"Greg", "HairLength":"Short", "HairColour":"Brown", "FacialHair":"Yes", "Jewellery":"Yes", "Hat":"No", "Lipstick":"No", "Gender":"Male"} Chris = {"Name":"Chris", "HairLength":"Long", "HairColour":"Blonde", "FacialHair":"No", "Jewellery":"No","Hat":"Yes", "Lipstick":"Yes", "Gender":"Male"} Jason = {"Name":"Jason", "HairLength":"Short", "HairColour":"Brown", "FacialHair":"Yes", "Jewellery":"No","Hat":"Yes", "Lipstick":"No", "Gender":"Male"} Clancy = {"Name":"Clancy", "HairLength":"Bald", "HairColour":"Red", "FacialHair":"Yes", "Jewellery":"No", "Hat":"No","Lipstick":"No", "Gender":"Male"} Betty = {"Name":"Betty", "HairLength":"Short", "HairColour":"Blonde", "FacialHair":"No", "Jewellery":"Yes","Hat":"Yes", "Lipstick":"Yes", "Gender":"Female"} Helen = {"Name":"Helen", "HairLength":"Short", "HairColour":"Brown", "FacialHair":"No", "Jewellery":"No", "Hat":"No","Lipstick":"Yes", "Gender":"Female"} Selena = {"Name":"Selena", "HairLength":"Long", "HairColour":"Brown", "FacialHair":"No", "Jewellery":"Yes","Hat":"No", "Lipstick":"No", "Gender":"Female"} Jacqueline = {"Name":"Jacqueline", "HairLength":"Long", "HairColour":"Red", "FacialHair":"Yes", "Jewellery":"Yes", "Hat":"No","Lipstick":"No", "Gender":"Female"} AISuspects = ([Greg, Chris, Jason, Clancy, Betty, Selena, Helen, Jacqueline]) UserSuspects = ([Greg, Chris, Jason, Clancy, Betty, Selena, Helen, Jacqueline]) print("AISuspects:") #Here i want it to print the field "Name" in every dictionary within the list AISuspects print("UserSuspects:") #Here i want it to print the field "Name" in every dictionary within the list UserSuspects </code></pre> <p>Expected output and current output after the solution:</p> <p>AI Suspects: ['Greg', 'Chris', 'Jason', 'Clancy', 'Betty', 'Selena', 'Helen', 'Jacqueline']</p> <p>User Suspects: ['Greg', 'Chris', 'Jason', 'Clancy', 'Betty', 'Selena', 'Helen', 'Jacqueline']</p>
0
2016-10-15T19:26:07Z
40,063,473
<pre><code>UserSuspects = [Greg['Name'], Chris['Name'],Jason['Name'], Clancy['Name'], Betty['Name'], Selena['Name'], Helen['Name'], Jacqueline['Name']] print UserSuspects </code></pre>
-1
2016-10-15T19:44:51Z
[ "python", "list", "dictionary", "printing", "output" ]
Python Plotting Data Using the Row referring to rows to columns from CSV file
40,063,339
<p>Below is the data from CSV file : Each Value Separated by "COMMA"</p> <pre><code>SName,Sub1,Sub2,Sub3, ... ,Sub10 0 A,40,50,33, ... ,78 1 B,55,55,33, ... ,66 2 C,99,100,34, ... ,44 </code></pre> <p>I want to Plot only the Row 0 - that is Student Name: A's subject marks from Sub1 till Sub 10 . The Graph should consist of "BAR" , Bar with different Colours !! depending upon the marks the colours should vary for the Student.</p> <p>If the a subject has got minimum colour then it show in RED... If a subject has highest marks it should show in another colour. Average marks for other subjects in different colours ? </p> <p>What should I do?</p>
-2
2016-10-15T19:28:38Z
40,064,161
<p>Possibly the easiest way of many plots is to begin with one of the samples available at the <a href="http://matplotlib.org/gallery.html" rel="nofollow">matplotlib gallery</a>. In this case, I reminded myself about details using two of the samples since I don't use matplotlib often. This code represents part of a solution inasmuch as it does not read values from the csv.</p> <pre><code>import matplotlib.pyplot as plt plt.rcdefaults() import numpy as np import matplotlib.pyplot as plt # Example data subjects = ['Sub%s'%_ for _ in range(1,11)] marks = [51,43,55,60,65,43,78,67,88,44] minMark=min(marks) maxMark=max(marks) colors=['green']*len(marks) for _ in range(len(colors)): if marks[_]==minMark: colors[_]='red' if marks[_]==maxMark: colors[_]='yellow' y_pos = np.arange(len(subjects)) plt.barh(y_pos, marks, align='center',color=colors) plt.yticks(y_pos, subjects) plt.xlabel('marks') plt.title('Subject Marks for Student A') plt.show() </code></pre> <p>With csv filecontents like this:</p> <pre><code>SName,Sub1,Sub2,Sub3,Sub10 0,A,40,50,33,78 1,B,55,55,33,66 2,C,99,100,34,44 </code></pre> <p>you can recover the first line of marks using code like this:</p> <pre><code>import csv first = True with open('temp2.csv') as csvfile: reader = csv.reader(csvfile) for line in reader: if first: first=False continue marks=line break print (marks) </code></pre>
1
2016-10-15T21:01:00Z
[ "python", "python-2.7", "pandas", "numpy", "matplotlib" ]
Python - converting to list
40,063,378
<pre><code>import requests from bs4 import BeautifulSoup webpage = requests.get("http://www.nytimes.com/") soup = BeautifulSoup(requests.get("http://www.nytimes.com/").text, "html.parser") for story_heading in soup.find_all(class_="story-heading"): articles = story_heading.text.replace('\n', '').replace(' ', '') print (articles) </code></pre> <p>There is my code, it prints out a list of all the article titles on the website. I get strings: </p> <blockquote> <p>Looking Back: 1980 | Funny, but Not Fit to Print</p> <p>Brooklyn Studio With Room for Family and a Dog</p> <p>Search for Homes for Sale or Rent</p> <p>Sell Your Home</p> </blockquote> <p>So, I want to convert this to a list = ['Search for Homes for Sale or Rent', 'Sell Your Home', ...], witch will allow me to make some other manipulations like random.choice etc.<br> I tried:</p> <pre><code>alist = articles.split("\n") print (alist) </code></pre> <blockquote> <p>['Looking Back: 1980 | Funny, but Not Fit to Print'] </p> <p>['Brooklyn Studio With Room for Family and a Dog']</p> <p>['Search for Homes for Sale or Rent']</p> <p>['Sell Your Home']</p> </blockquote> <p>It is not a list that I need. I'm stuck. Can you please help me with this part of code. </p>
0
2016-10-15T19:34:13Z
40,063,409
<p>You are constantly overwriting <code>articles</code> with the next value in your list. What you want to do instead is make <code>articles</code> a list, and just <code>append</code> in each iteration: </p> <pre><code>import requests from bs4 import BeautifulSoup webpage = requests.get("http://www.nytimes.com/") soup = BeautifulSoup(requests.get("http://www.nytimes.com/").text, "html.parser") articles = [] for story_heading in soup.find_all(class_="story-heading"): articles.append(story_heading.text.replace('\n', '').replace(' ', '')) print (articles) </code></pre> <p>The output is huge, so this is a small sample of what it looks like:</p> <pre><code>['Global Deal Reached to Curb Chemical That Warms Planet', 'Accord Could Push A/C Out of Sweltering India’s Reach ',....] </code></pre> <p>Furthermore, you only need to strip spaces in each iteration. You don't need to do those replacements. So, you can do this with your <code>story_heading.text</code> instead:</p> <pre><code>articles.append(story_heading.text.strip()) </code></pre> <p>Which, can now give you a final solution looking like this: </p> <pre><code>import requests from bs4 import BeautifulSoup webpage = requests.get("http://www.nytimes.com/") soup = BeautifulSoup(requests.get("http://www.nytimes.com/").text, "html.parser") articles = [story_heading.text.strip() for story_heading in soup.find_all(class_="story-heading")] print (articles) </code></pre>
2
2016-10-15T19:37:18Z
[ "python", "string", "list", "split" ]
Python - Reversing data generated with particular loop order
40,063,401
<h1>Question: How could I peform the following task more efficiently?</h1> <p>My problem is as follows. I have a (large) 3D data set of points in real physical space (x,y,z). It has been generated by a nested for loop that looks like this:</p> <pre><code># Generate given dat with its ordering x_samples = 2 y_samples = 3 z_samples = 4 given_dat = np.zeros(((x_samples*y_samples*z_samples),3)) row_ind = 0 for z in range(z_samples): for y in range(y_samples): for x in range(x_samples): row = [x+.1,y+.2,z+.3] given_dat[row_ind,:] = row row_ind += 1 for row in given_dat: print(row)` </code></pre> <p>For the sake of comparing it to another set of data, I want to reorder the given data into my desired order as follows (unorthodox, I know):</p> <pre><code># Generate data with desired ordering x_samples = 2 y_samples = 3 z_samples = 4 desired_dat = np.zeros(((x_samples*y_samples*z_samples),3)) row_ind = 0 for z in range(z_samples): for x in range(x_samples): for y in range(y_samples): row = [x+.1,y+.2,z+.3] desired_dat[row_ind,:] = row row_ind += 1 for row in desired_dat: print(row) </code></pre> <p>I have written a function that does what I want, but it is horribly slow and inefficient: </p> <pre><code>def bad_method(x_samp,y_samp,z_samp,data): zs = np.unique(data[:,2]) xs = np.unique(data[:,0]) rowlist = [] for z in zs: for x in xs: for row in data: if row[0] == x and row[2] == z: rowlist.append(row) new_data = np.vstack(rowlist) return new_data # Shows that my function does with I want fix = bad_method(x_samples,y_samples,z_samples,given_dat) print('Unreversed data') print(given_dat) print('Reversed Data') print(fix) # If it didn't work this will throw an exception assert(np.array_equal(desired_dat,fix)) </code></pre> <p>How could I improve my function so it is faster? My data sets usually have roughly 2 million rows. It must be possible to do this with some clever slicing/indexing which I'm sure will be faster but I'm having a hard time figuring out how. Thanks for any help!</p>
0
2016-10-15T19:36:43Z
40,063,949
<p>You could reshape your array, swap the axes as necessary and reshape back again:</p> <pre><code># (No need to copy if you don't want to keep the given_dat ordering) data = np.copy(given_dat).reshape(( z_samples, y_samples, x_samples, 3)) # swap the "y" and "x" axes data = np.swapaxes(data, 1,2) # back to 2-D array data = data.reshape((x_samples*y_samples*z_samples,3)) assert(np.array_equal(desired_dat,data)) </code></pre>
2
2016-10-15T20:35:38Z
[ "python", "numpy" ]
How to find and print out of a specific value from a list (at least i think thats what i want to do?)
40,063,567
<p>Here is my code: </p> <pre><code>n = 1 inputs = [] quantities = [] while n == 1: w = input('Enter the product code: ') inputs.append(w) with open('items.txt') as f: found = False for line in f: if w in line: price1 = line[21:25] desc1 = line[9:17] quantity1 = line[18:20] print(desc1) print('Price = ' +str(price1)) print('Available Quantity = ' +str(quantity1)) if n == 0: print('And your products are: ') for i in inputs: with open('items.txt') as f: for line in f: if i in line: desc1 = line[9:17] price1 = line[21:25] print(str(desc1) + ' ' +str(price1) + ' ' + str(quantities)) </code></pre> <p>There is no error when running the code. When run, it outputs: </p> <pre><code>Our available products are: 15372185 ChocBisc 13281038 AppJuice 26419633 TomaSoup 74283187 SprRolls Enter the product code: 74283187 SprRolls Price = 0.90 Available Quantity = 86 Is this what you want? (Y/N) y How much would you like? 34 Would you like to continue? (Y/N) y Continuing! Enter the product code: 15372185 ChocBisc Price = 1.20 Available Quantity = 50 Is this what you want? (Y/N) y How much would you like? 45 Would you like to continue? (Y/N) n System Closing! And your products are: SprRolls 0.90 [34, 45] ChocBisc 1.20 [34, 45] </code></pre> <p>As you can see, right at the bottom, it prints both quantities entered. I knew it was going to do this but i dont know how to rectify it. What i need it to do is to print only the quantity entered for that product code. Any help as always would be greatly appreciated. Thank you!!</p> <p>Also i removed most of the script under while n == 1 since this is my coursework, and i would rather it didn't get copied or anything like that. Hopefully this still shows the relevant section of the code to the question.</p>
0
2016-10-15T19:54:17Z
40,063,657
<p>You can use <a href="https://docs.python.org/2/library/functions.html#enumerate" rel="nofollow"><code>enumerate</code></a>. For example:</p> <pre><code>for index, i in enumerate(inputs): print(index, i) </code></pre> <p>That should print out </p> <pre><code>0, 74283187 1, 15372185 </code></pre> <p>Getting the quantities is trivial: <code>quantities[index]</code></p>
0
2016-10-15T20:02:52Z
[ "python" ]
How to find and print out of a specific value from a list (at least i think thats what i want to do?)
40,063,567
<p>Here is my code: </p> <pre><code>n = 1 inputs = [] quantities = [] while n == 1: w = input('Enter the product code: ') inputs.append(w) with open('items.txt') as f: found = False for line in f: if w in line: price1 = line[21:25] desc1 = line[9:17] quantity1 = line[18:20] print(desc1) print('Price = ' +str(price1)) print('Available Quantity = ' +str(quantity1)) if n == 0: print('And your products are: ') for i in inputs: with open('items.txt') as f: for line in f: if i in line: desc1 = line[9:17] price1 = line[21:25] print(str(desc1) + ' ' +str(price1) + ' ' + str(quantities)) </code></pre> <p>There is no error when running the code. When run, it outputs: </p> <pre><code>Our available products are: 15372185 ChocBisc 13281038 AppJuice 26419633 TomaSoup 74283187 SprRolls Enter the product code: 74283187 SprRolls Price = 0.90 Available Quantity = 86 Is this what you want? (Y/N) y How much would you like? 34 Would you like to continue? (Y/N) y Continuing! Enter the product code: 15372185 ChocBisc Price = 1.20 Available Quantity = 50 Is this what you want? (Y/N) y How much would you like? 45 Would you like to continue? (Y/N) n System Closing! And your products are: SprRolls 0.90 [34, 45] ChocBisc 1.20 [34, 45] </code></pre> <p>As you can see, right at the bottom, it prints both quantities entered. I knew it was going to do this but i dont know how to rectify it. What i need it to do is to print only the quantity entered for that product code. Any help as always would be greatly appreciated. Thank you!!</p> <p>Also i removed most of the script under while n == 1 since this is my coursework, and i would rather it didn't get copied or anything like that. Hopefully this still shows the relevant section of the code to the question.</p>
0
2016-10-15T19:54:17Z
40,063,658
<p>I would re-write the latter part of your code to iterate through the <em><a href="https://docs.python.org/2/library/functions.html#range" rel="nofollow">range</a></em> of values in <code>inputs</code>, rather than the values themselves. Then, you can call the index of the element you want to print from <code>quantities</code>. </p> <p>As a caveat, this works in your case because the user send inputs to <code>inputs</code> one at a time (so, the indices of <code>inputs</code> correspond with the indices of <code>quantities</code>). You might consider a different data structure to use within this code, like a <em><a href="https://docs.python.org/2/tutorial/datastructures.html#dictionaries" rel="nofollow">dictionary</a></em>, which could store product codes and quantities as key/value pairs. Then, you can simply refer to the key of the dictionary when printing.</p> <p>Here is how I would suggest changing your code:</p> <pre><code>if n == 0: print('And your products are: ') for i in range(len(inputs)): with open('items.txt') as f: for line in f: if inputs[i] in line: desc1 = line[9:17] price1 = line[21:25] print(str(desc1) + ' ' +str(price1) + ' ' + str(quantities[i])) </code></pre>
1
2016-10-15T20:03:19Z
[ "python" ]
How to find and print out of a specific value from a list (at least i think thats what i want to do?)
40,063,567
<p>Here is my code: </p> <pre><code>n = 1 inputs = [] quantities = [] while n == 1: w = input('Enter the product code: ') inputs.append(w) with open('items.txt') as f: found = False for line in f: if w in line: price1 = line[21:25] desc1 = line[9:17] quantity1 = line[18:20] print(desc1) print('Price = ' +str(price1)) print('Available Quantity = ' +str(quantity1)) if n == 0: print('And your products are: ') for i in inputs: with open('items.txt') as f: for line in f: if i in line: desc1 = line[9:17] price1 = line[21:25] print(str(desc1) + ' ' +str(price1) + ' ' + str(quantities)) </code></pre> <p>There is no error when running the code. When run, it outputs: </p> <pre><code>Our available products are: 15372185 ChocBisc 13281038 AppJuice 26419633 TomaSoup 74283187 SprRolls Enter the product code: 74283187 SprRolls Price = 0.90 Available Quantity = 86 Is this what you want? (Y/N) y How much would you like? 34 Would you like to continue? (Y/N) y Continuing! Enter the product code: 15372185 ChocBisc Price = 1.20 Available Quantity = 50 Is this what you want? (Y/N) y How much would you like? 45 Would you like to continue? (Y/N) n System Closing! And your products are: SprRolls 0.90 [34, 45] ChocBisc 1.20 [34, 45] </code></pre> <p>As you can see, right at the bottom, it prints both quantities entered. I knew it was going to do this but i dont know how to rectify it. What i need it to do is to print only the quantity entered for that product code. Any help as always would be greatly appreciated. Thank you!!</p> <p>Also i removed most of the script under while n == 1 since this is my coursework, and i would rather it didn't get copied or anything like that. Hopefully this still shows the relevant section of the code to the question.</p>
0
2016-10-15T19:54:17Z
40,063,703
<p>You're creating a new list for the quantities so at the end where you print out this list you can append it to print out only the product code of that item. Understand? I'll post the code in a little bit if I can.</p>
0
2016-10-15T20:08:28Z
[ "python" ]
Pandas flatten hierarchical index on non overlapping columns
40,063,580
<p>I have a dataframe, and I set the index to a column of the dataframe. This creates a hierarchical column index. I want to flatten the columns to a single level. Similar to this question - <a href="http://stackoverflow.com/questions/14507794/python-pandas-how-to-flatten-a-hierarchical-index-in-columns">Python Pandas - How to flatten a hierarchical index in columns</a>, however, the columns do not overlap (i.e. 'id' is not at level 0 of the hierarchical index, and other columns are at level 1 of the index).</p> <pre><code>df = pd.DataFrame([(101,3,'x'), (102,5,'y')], columns=['id', 'A', 'B']) df.set_index('id', inplace=True) A B id 101 3 x 102 5 y </code></pre> <p>Desired output is flattened columns, like this:</p> <pre><code>id A B 101 3 x 102 5 y </code></pre>
3
2016-10-15T19:55:17Z
40,063,647
<p>there will always be an index in your dataframes. if you don't set 'id' as index, it will be at the same level as other columns and pandas will populate an increasing integer for your index starting from 0.</p> <pre><code>df = pd.DataFrame([(101,3,'x'), (102,5,'y')], columns=['id', 'A', 'B']) In[52]: df Out[52]: id A B 0 101 3 x 1 102 5 y </code></pre> <p>the index is there so you can slice the original dataframe. such has</p> <pre><code>df.iloc[0] Out[53]: id 101 A 3 B x Name: 0, dtype: object </code></pre> <p>so let says you want ID as index and ID as a column, which is very redundant, you could do:</p> <pre><code>df = pd.DataFrame([(101,3,'x'), (102,5,'y')], columns=['id', 'A', 'B']) df.set_index('id', inplace=True) df['id'] = df.index df Out[55]: A B id id 101 3 x 101 102 5 y 102 </code></pre> <p>with this you can slice by 'id' such has:</p> <pre><code>df.loc[101] Out[57]: A 3 B x id 101 Name: 101, dtype: object </code></pre> <p>but it would the same info has :</p> <pre><code>df = pd.DataFrame([(101,3,'x'), (102,5,'y')], columns=['id', 'A', 'B']) df.set_index('id', inplace=True) df.loc[101] Out[58]: A 3 B x Name: 101, dtype: object </code></pre>
1
2016-10-15T20:01:27Z
[ "python", "pandas" ]
Pandas flatten hierarchical index on non overlapping columns
40,063,580
<p>I have a dataframe, and I set the index to a column of the dataframe. This creates a hierarchical column index. I want to flatten the columns to a single level. Similar to this question - <a href="http://stackoverflow.com/questions/14507794/python-pandas-how-to-flatten-a-hierarchical-index-in-columns">Python Pandas - How to flatten a hierarchical index in columns</a>, however, the columns do not overlap (i.e. 'id' is not at level 0 of the hierarchical index, and other columns are at level 1 of the index).</p> <pre><code>df = pd.DataFrame([(101,3,'x'), (102,5,'y')], columns=['id', 'A', 'B']) df.set_index('id', inplace=True) A B id 101 3 x 102 5 y </code></pre> <p>Desired output is flattened columns, like this:</p> <pre><code>id A B 101 3 x 102 5 y </code></pre>
3
2016-10-15T19:55:17Z
40,063,868
<p>Given:</p> <pre><code>&gt;&gt;&gt; df2=pd.DataFrame([(101,3,'x'), (102,5,'y')], columns=['id', 'A', 'B']) &gt;&gt;&gt; df2.set_index('id', inplace=True) &gt;&gt;&gt; df2 A B id 101 3 x 102 5 y </code></pre> <p>For printing purdy, you can produce a copy of the DataFrame with a reset the index and use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_string.html" rel="nofollow">.to_string</a>:</p> <pre><code>&gt;&gt;&gt; print df2.reset_index().to_string(index=False) id A B 101 3 x 102 5 y </code></pre> <p>Then play around with the formatting options so that the output suites your needs:</p> <pre><code>&gt;&gt;&gt; fmts=[lambda s: u"{:^5}".format(str(s).strip())]*3 &gt;&gt;&gt; print df2.reset_index().to_string(index=False, formatters=fmts) id A B 101 3 x 102 5 y </code></pre>
1
2016-10-15T20:27:43Z
[ "python", "pandas" ]
Pandas flatten hierarchical index on non overlapping columns
40,063,580
<p>I have a dataframe, and I set the index to a column of the dataframe. This creates a hierarchical column index. I want to flatten the columns to a single level. Similar to this question - <a href="http://stackoverflow.com/questions/14507794/python-pandas-how-to-flatten-a-hierarchical-index-in-columns">Python Pandas - How to flatten a hierarchical index in columns</a>, however, the columns do not overlap (i.e. 'id' is not at level 0 of the hierarchical index, and other columns are at level 1 of the index).</p> <pre><code>df = pd.DataFrame([(101,3,'x'), (102,5,'y')], columns=['id', 'A', 'B']) df.set_index('id', inplace=True) A B id 101 3 x 102 5 y </code></pre> <p>Desired output is flattened columns, like this:</p> <pre><code>id A B 101 3 x 102 5 y </code></pre>
3
2016-10-15T19:55:17Z
40,065,612
<p>You are misinterpreting what you are seeing.</p> <pre><code> A B id 101 3 x 102 5 y </code></pre> <p>Is not showing you a hierarchical column index. <code>id</code> is the name of the row index. In order to show you the name of the index, pandas is putting that space there for you.</p> <p>The answer to your question depends on what you really want or need.</p> <p>As the <code>df</code> is, you can dump it to a <code>csv</code> just the way you want:</p> <pre><code>print(df.to_csv(sep='\t')) id A B 101 3 x 102 5 y </code></pre> <hr> <pre><code>print(df.to_csv()) id,A,B 101,3,x 102,5,y </code></pre> <hr> <p>Or you can alter the <code>df</code> so that it displays the way you'd like</p> <pre><code>print(df.rename_axis(None)) A B 101 3 x 102 5 y </code></pre> <hr> <p><strong><em>please do not do this!!!!</em></strong><br> I'm putting it to demonstrate how to manipulate</p> <p>I could also keep the index as it is but manipulate both column and row index names to print how you would like.</p> <pre><code>print(df.rename_axis(None).rename_axis('id', 1)) id A B 101 3 x 102 5 y </code></pre> <p>But this has named the columns' index <code>id</code> which makes no sense.</p>
2
2016-10-16T00:29:01Z
[ "python", "pandas" ]
Why won't this APScheduler code work?
40,063,734
<p>been looking for quite a while for an answer so I turned to here! It gives me the error, "Invalid Index" for the sched.start()!</p> <pre><code>import random import datetime from apscheduler.schedulers.blocking import BlockingScheduler import smtplib import email def randEmail(): #Gets randLine file_object = open("lyrics.txt", "r") randLine = random.randint(1, 10) for i, line in enumerate(file_object): if i == randLine: break #line = randomly generated line file_object.close() #Email emails = [ 'emails'] server = smtplib.SMTP('smtp.gmail.com', 587) server.starttls() server.login('login', 'password') server.sendmail('login',emails, line) server.quit() #Prints to notepad saying completed Date = datetime.datetime.now() with open("Server_Quit.txt", "r+") as ServerQuit: ServerQuit.write("Server has quit at " + str(Date)) ServerQuit.close() #Unsure whether working #sched.Scheduler() #sched.start() #sched.add_interval_job(randEmail, hours=24, start_date='2016-10-10 18:30') sched = BlockingScheduler() @sched.randEmail('cron', day_of_week='mon-fri', hour=18, minutes=30) sched.start() </code></pre> <p>I appreciate any help! I've tried my best to get this working on my own and have ironed through all the other problems myself, but can't get this working. Also, if I want this to run on my PC and do this everyday, can I just add it to startup processes, and when I start my PC the scheduler will start? </p>
0
2016-10-15T20:11:35Z
40,065,143
<p>You can add a job to a scheduler by decorating a function with the <code>scheduled_job</code> decorator:</p> <pre><code>from apscheduler.schedulers.blocking import BlockingScheduler sched = BlockingScheduler() # minute=30 not minutes=30 @sched.scheduled_job('cron', day_of_week='mon-fri', hour=18, minute=30) def randEmail(): #Gets randLine with open("lyrics.txt", "r") as file_object: randLine = random.randint(1, 10) for i, line in enumerate(file_object): if i == randLine: break #line = randomly generated line #Email emails = [ 'emails'] server = smtplib.SMTP('smtp.gmail.com', 587) server.starttls() server.login('login', 'password') server.sendmail('login', emails, line) server.quit() #Prints to notepad saying completed Date = datetime.datetime.now() # You don't have to close the file if you use the with statement with open("Server_Quit.txt", "r+") as ServerQuit: ServerQuit.write("Server has quit at " + str(Date)) sched.start() </code></pre> <p>You can also use the <code>add_job</code> method:</p> <pre><code>sched.add_job(randEmail, 'cron', day_of_week='mon-fri', hour=18, minute=30) sched.start() </code></pre> <p>I can't see any reason why it would not work as a startup process.</p>
0
2016-10-15T23:07:11Z
[ "python", "apscheduler" ]
Can someone help me make the transition to a new window using Tkinter in Python?
40,063,782
<p>Im very new and am interested in working with windows and Tkinter. please be gentle.</p> <p>here is my code that is supposed to go to a new window then open an image in that new window. However, instead of putting the image in the new window it puts it in the first window.</p> <p>I think this has something to do with toplevel but i cant seem to make that work right. </p> <pre><code>import os from PIL import Image from PIL import ImageTk from Tkinter import Tk import os class Application(Frame): """ A GUI application with three buttons. """ def __init__(self, master): """ Initialize the frame""" Frame.__init__(self,master) self.grid() self.create_widgets() def create_widgets(self): """ Create button, text and entry widgets""" self.instruction = Label(self, text = "First off what is your name?") self.instruction.grid(row=0, column =0, columnspan=2, sticky=W) #self.first = first self.name = Entry(self) self.name.grid(row=1, column =1, sticky=W) self.submit_button = Button(self, text ="Submitsss", command = self.reveal) self.submit_button.grid(row = 2, column = 0, sticky =W) self.text = Text(self, width =35, height = 5, wrap = WORD) self.text.grid(row=3, column = 0, columnspan =2, sticky = W) self.ok_button = Button(self, text = "Next", command = self.go_to_2) self.ok_button.grid(row = 2, column = 0, sticky = E) def reveal(self): """Display message based on the name typed in""" content = self.name.get() message = "Hello %s" %(content) self.text.insert(0.0, message) def go_to_2(self): self.destroy() #root = Tk() #self.newApplication = tk.Toplevel(self.master) #self.app3 = Application2(self.newApplication) root.title("game") root.geometry("600x480") #root = Tk() #app2=Application2(root) self.newWindow = Tk.Toplevel() self.app = Application2(self.newWindow) class Application2(Frame): """ A GUI application with three buttons. """ def __init__(self, master): """ Initialize the frame""" Frame.__init__(self,master) self.grid() self.create_widgets() #master.panel() master.title("a") #self.root.mainloop() master.img = ImageTk.PhotoImage(Image.open("C:\Users\david\Pictures\sdf.jpg")) master.panel = Label(root, image = master.img) master.panel.pack() def create_widgets(self): self.submit_button = Button(self, text ="Submit") self.submit_button.grid(row = 2, column = 0, sticky =W) self.name = Entry(self) self.name.grid(row=1, column =1, sticky=W) self.ok_button = Button(self, text = "Next", command = self.go_to_3) self.ok_button.grid(row = 2, column = 0, sticky = E) def go_to_3(self): root = Tk() app2=Application3(root) #def create_picture(self): class Application3(Frame): """ A GUI application with three buttons. """ def __init__(self, master): """ Initialize the frame""" Frame.__init__(self,master) self.grid() self.create_widgets() def create_widgets(self): self.button = Button(self, text = "ass") root.mainloop() root = Tk() root.title("game") root.geometry("600x480") app = Application(root) root.mainloop() #app2= Application2(root) #if __name__ == '__main__': # main() </code></pre>
0
2016-10-15T20:16:35Z
40,064,148
<p>Try this code:</p> <pre><code>import tkinter as tk class MainWindow(tk.Frame): counter = 0 def __init__(self, *args, **kwargs): tk.Frame.__init__(self, *args, **kwargs) self.button = tk.Button(self, text="Create new window", command=self.create_window) self.button.pack(side="top") def create_window(self): self.counter += 1 t = tk.Toplevel(self) t.wm_title("Window #%s" % self.counter) l = tk.Label(t, text="This is window #%s" % self.counter) l.pack(side="top", fill="both", expand=True, padx=100, pady=100) if __name__ == "__main__": root = tk.Tk() main = MainWindow(root) main.pack(side="top", fill="both", expand=True) root.mainloop() </code></pre> <p>This will make a window and you can push a button to pop up a new window. There is already a label on that window as an example.</p>
0
2016-10-15T20:59:47Z
[ "python", "windows", "tkinter" ]
Can someone help me make the transition to a new window using Tkinter in Python?
40,063,782
<p>Im very new and am interested in working with windows and Tkinter. please be gentle.</p> <p>here is my code that is supposed to go to a new window then open an image in that new window. However, instead of putting the image in the new window it puts it in the first window.</p> <p>I think this has something to do with toplevel but i cant seem to make that work right. </p> <pre><code>import os from PIL import Image from PIL import ImageTk from Tkinter import Tk import os class Application(Frame): """ A GUI application with three buttons. """ def __init__(self, master): """ Initialize the frame""" Frame.__init__(self,master) self.grid() self.create_widgets() def create_widgets(self): """ Create button, text and entry widgets""" self.instruction = Label(self, text = "First off what is your name?") self.instruction.grid(row=0, column =0, columnspan=2, sticky=W) #self.first = first self.name = Entry(self) self.name.grid(row=1, column =1, sticky=W) self.submit_button = Button(self, text ="Submitsss", command = self.reveal) self.submit_button.grid(row = 2, column = 0, sticky =W) self.text = Text(self, width =35, height = 5, wrap = WORD) self.text.grid(row=3, column = 0, columnspan =2, sticky = W) self.ok_button = Button(self, text = "Next", command = self.go_to_2) self.ok_button.grid(row = 2, column = 0, sticky = E) def reveal(self): """Display message based on the name typed in""" content = self.name.get() message = "Hello %s" %(content) self.text.insert(0.0, message) def go_to_2(self): self.destroy() #root = Tk() #self.newApplication = tk.Toplevel(self.master) #self.app3 = Application2(self.newApplication) root.title("game") root.geometry("600x480") #root = Tk() #app2=Application2(root) self.newWindow = Tk.Toplevel() self.app = Application2(self.newWindow) class Application2(Frame): """ A GUI application with three buttons. """ def __init__(self, master): """ Initialize the frame""" Frame.__init__(self,master) self.grid() self.create_widgets() #master.panel() master.title("a") #self.root.mainloop() master.img = ImageTk.PhotoImage(Image.open("C:\Users\david\Pictures\sdf.jpg")) master.panel = Label(root, image = master.img) master.panel.pack() def create_widgets(self): self.submit_button = Button(self, text ="Submit") self.submit_button.grid(row = 2, column = 0, sticky =W) self.name = Entry(self) self.name.grid(row=1, column =1, sticky=W) self.ok_button = Button(self, text = "Next", command = self.go_to_3) self.ok_button.grid(row = 2, column = 0, sticky = E) def go_to_3(self): root = Tk() app2=Application3(root) #def create_picture(self): class Application3(Frame): """ A GUI application with three buttons. """ def __init__(self, master): """ Initialize the frame""" Frame.__init__(self,master) self.grid() self.create_widgets() def create_widgets(self): self.button = Button(self, text = "ass") root.mainloop() root = Tk() root.title("game") root.geometry("600x480") app = Application(root) root.mainloop() #app2= Application2(root) #if __name__ == '__main__': # main() </code></pre>
0
2016-10-15T20:16:35Z
40,064,158
<p>To create another toplevel widget, use the <code>Toplevel</code> command. Don't try calling <code>Tk()</code> again.</p> <p>For instance the following produces two toplevel Tk windows on screen:</p> <pre><code>import tkinter as tk root = tk.Tk() dlg = tk.Toplevel(root) </code></pre> <p>One significant difference between the top toplevels is if you destroy <code>root</code> then you unload Tk and destroy all Tk windows. However, a <code>Toplevel</code> widget can be destroyed without affecting the rest of the application so is suitable for use as a dialog or other separate window.</p>
1
2016-10-15T21:00:42Z
[ "python", "windows", "tkinter" ]
Explanation for re.split() error?
40,063,797
<p>I'm sure you see this a lot but just wanted to warn you that I'm still very new to coding in general and have a lot to learn. I've been attempting teaching myself by working on a personal project and youtube whenever I have the time. </p> <p>Long version: I always get an error when I use the split function, but I still get a value. Essentially what my function is supposed to do is take an angle or bearing that is in degrees°minutes'seconds" or for example "N 38°43'23\" E" to a decimal number. I took advantage of bearings being less than 90 degrees to use indexing to find the numbers in the string to convert the angle. However, if the angle wasn't a bearing, I couldn't think of a way to figure out how many tens places the degrees to pull the number out so I tried splitting it at the degree symbol. When it does this, though, it returns an error saying split() requires a non-empty pattern match. What does this mean? The code still works, but always returns this error with it.</p> <p>Short version: Here's my code:</p> <pre><code>def decimal(x): # converts degrees-minutes-seconds to decimal dms = list(x) if dms[0] == 'N' or dms[0] == 'S': degrees = ((int(dms[2]) * 10) + int(dms[3])) minutes = ((int(dms[-8]) * 10) + int(dms[-7])) / 60 seconds = ((int(dms[-5]) * 10) + int(dms[-4])) / 3600 else: placeholder = re.split(r'\u00b0*', x) degrees = int(placeholder[0]) minutes = ((int(dms[-6]) * 10) + int(dms[-5])) / 60 seconds = ((int(dms[-3]) * 10) + int(dms[-2])) / 3600 return degrees + minutes + seconds </code></pre> <p>When I run it, I get the decimal number, but I also get:</p> <pre><code>FutureWarning: split() requires a non-empty pattern match. return _compile(pattern, flags).split(string, maxsplit) </code></pre> <p>I've looked at other questions posted about this error, but there were no answers that explained what to do to avoid this, or what the error really means. Thank you for any help. Also any advice or corrections you see would be greatly appreciated!</p>
0
2016-10-15T20:17:50Z
40,063,847
<p>What you have is not an error, it's a warning.</p> <p>For one, I think you should not use a raw string, you need <code>'\u00b0'</code>, the character. And <code>'c*'</code> will match 0 or more of <code>c</code>, so it matches the empty string. I believe this is what the warning is about. I suggest that you use</p> <pre><code>re.split('\u00b0', x) </code></pre> <p>Or even better, just</p> <pre><code> x.split('\u00b0') </code></pre>
2
2016-10-15T20:24:47Z
[ "python", "split" ]
Explanation for re.split() error?
40,063,797
<p>I'm sure you see this a lot but just wanted to warn you that I'm still very new to coding in general and have a lot to learn. I've been attempting teaching myself by working on a personal project and youtube whenever I have the time. </p> <p>Long version: I always get an error when I use the split function, but I still get a value. Essentially what my function is supposed to do is take an angle or bearing that is in degrees°minutes'seconds" or for example "N 38°43'23\" E" to a decimal number. I took advantage of bearings being less than 90 degrees to use indexing to find the numbers in the string to convert the angle. However, if the angle wasn't a bearing, I couldn't think of a way to figure out how many tens places the degrees to pull the number out so I tried splitting it at the degree symbol. When it does this, though, it returns an error saying split() requires a non-empty pattern match. What does this mean? The code still works, but always returns this error with it.</p> <p>Short version: Here's my code:</p> <pre><code>def decimal(x): # converts degrees-minutes-seconds to decimal dms = list(x) if dms[0] == 'N' or dms[0] == 'S': degrees = ((int(dms[2]) * 10) + int(dms[3])) minutes = ((int(dms[-8]) * 10) + int(dms[-7])) / 60 seconds = ((int(dms[-5]) * 10) + int(dms[-4])) / 3600 else: placeholder = re.split(r'\u00b0*', x) degrees = int(placeholder[0]) minutes = ((int(dms[-6]) * 10) + int(dms[-5])) / 60 seconds = ((int(dms[-3]) * 10) + int(dms[-2])) / 3600 return degrees + minutes + seconds </code></pre> <p>When I run it, I get the decimal number, but I also get:</p> <pre><code>FutureWarning: split() requires a non-empty pattern match. return _compile(pattern, flags).split(string, maxsplit) </code></pre> <p>I've looked at other questions posted about this error, but there were no answers that explained what to do to avoid this, or what the error really means. Thank you for any help. Also any advice or corrections you see would be greatly appreciated!</p>
0
2016-10-15T20:17:50Z
40,063,961
<p>Since you are using regular expressions, you could parse the entire string with a single regex, and take advantage of grouping:</p> <pre><code>import re def decimal_alt(x): REGEX = re.compile( u"([NS])\\s(\\d+)\u00B0(\\d+)\'(\\d+)\"") rm = REGEX.match(x) if rm is not None: sign = -1 if rm.group(1) == 'S' else +1 d = float(rm.group(2)) m = float(rm.group(3)) / 60.0 s = float(rm.group(4)) / 3600.0 return sign * ( d + m + s ) </code></pre> <p>When used with</p> <pre><code>print decimal_alt(u"N 38\u00B040'20\"") </code></pre> <p>it prints</p> <pre><code>38.6722222222 </code></pre>
1
2016-10-15T20:36:42Z
[ "python", "split" ]
How call arguments stack works in Python?
40,063,929
<p>I am learning python and trying to get idea how stack works in python. I have some doubts. I know how stack work and i have read many articles and tutorials about it. I have read many threads on stackoverflow they are all good, still I have some doubts.</p> <p>As far I have read stack stores and return values of function. It work by LIFO principal.</p> <p>Only first value of the stack will return and store at top.</p> <p>So my question is - suppose there are four variables:</p> <pre><code>a = 9 b = 2 c = 13 d = 4 </code></pre> <p>They are stored in stack in order in which function call the value, for example:</p> <pre><code>sum = a + d sum = b + c a = 9 d = 4 b = 2 c = 13 </code></pre> <p>and they will return from top to bottom. Now my confusion is - if any operation requires to use <code>d</code> and <code>c</code>, while stack return values from the top, how stack will get the values <code>d</code> and <code>c</code>, as long as they are in middle of stack. Will stack first return a and then return d ??</p> <p>That's the confusion.</p>
-1
2016-10-15T20:33:17Z
40,064,190
<p>If you're interested how python works under the hood, there is a standard CPython library <a href="https://docs.python.org/2/library/dis.html" rel="nofollow">dis</a>. Here is the output for your test code:</p> <pre><code>&gt;&gt;&gt; import dis &gt;&gt;&gt; def test(): ... a = 9 ... b = 2 ... c = 13 ... d = 14 ... sum1 = a + d ... sum2 = b + c ... &gt;&gt;&gt; dis.dis(test) 2 0 LOAD_CONST 1 (9) 3 STORE_FAST 0 (a) 3 6 LOAD_CONST 2 (2) 9 STORE_FAST 1 (b) 4 12 LOAD_CONST 3 (13) 15 STORE_FAST 2 (c) 5 18 LOAD_CONST 4 (14) 21 STORE_FAST 3 (d) 6 24 LOAD_FAST 0 (a) 27 LOAD_FAST 3 (d) 30 BINARY_ADD 31 STORE_FAST 4 (sum1) 7 34 LOAD_FAST 1 (b) 37 LOAD_FAST 2 (c) 40 BINARY_ADD 41 STORE_FAST 5 (sum2) 44 LOAD_CONST 0 (None) 47 RETURN_VALUE </code></pre> <p>and it has nothing to do with stack as you can see. It won't do even with adjusted code, like</p> <pre><code>&gt;&gt;&gt; def test2(a,b,c,d): ... sum1 = a + d ... sum2 = b + c ... &gt;&gt;&gt; dis.dis(test2) 2 0 LOAD_FAST 0 (a) 3 LOAD_FAST 3 (d) 6 BINARY_ADD 7 STORE_FAST 4 (sum1) 3 10 LOAD_FAST 1 (b) 13 LOAD_FAST 2 (c) 16 BINARY_ADD 17 STORE_FAST 5 (sum2) 20 LOAD_CONST 0 (None) 23 RETURN_VALUE </code></pre> <p>If you're interested in stack concept in general in computing, you should switch to some low-level (2.5 generation languages, like C), or go even deeper to assembly languages.</p> <p>Reading about various calling conventions may be another good start point as well ( <a href="https://en.wikipedia.org/wiki/X86_calling_conventions" rel="nofollow">x86 calling conventions</a> for example )</p>
0
2016-10-15T21:04:21Z
[ "python", "stack", "callstack" ]
How call arguments stack works in Python?
40,063,929
<p>I am learning python and trying to get idea how stack works in python. I have some doubts. I know how stack work and i have read many articles and tutorials about it. I have read many threads on stackoverflow they are all good, still I have some doubts.</p> <p>As far I have read stack stores and return values of function. It work by LIFO principal.</p> <p>Only first value of the stack will return and store at top.</p> <p>So my question is - suppose there are four variables:</p> <pre><code>a = 9 b = 2 c = 13 d = 4 </code></pre> <p>They are stored in stack in order in which function call the value, for example:</p> <pre><code>sum = a + d sum = b + c a = 9 d = 4 b = 2 c = 13 </code></pre> <p>and they will return from top to bottom. Now my confusion is - if any operation requires to use <code>d</code> and <code>c</code>, while stack return values from the top, how stack will get the values <code>d</code> and <code>c</code>, as long as they are in middle of stack. Will stack first return a and then return d ??</p> <p>That's the confusion.</p>
-1
2016-10-15T20:33:17Z
40,064,483
<p>Although stacks work as a LIFO, you have to be careful about exactly which data structures are being stacked. For instance, many programming languages use a stack to store parameters and local variables when calling a function. But the thing that is being stacked is the entire call frame, not the individual variables in the frame. </p> <p>In C, for instance, I may have local variables a, b, c, d "on the stack" but that means that they are stored at a known fixed offset from the start of the frame. The variables can be accessed in any order and they don't move around (apart from optimizations the compiler may be doing). </p> <p>Python makes it a bit more complicated. In CPython at least, there is a stack frame under the covers, but the local variables you see are actually stored in an an array (see shadowranger's note below) on a function instance object which makes up the function's local namespace. All variables can be accessed through the dict at any time.</p> <p>In these cases, the local variables are not themselves a LIFO and can be accessed arbitrarily as long as you know their offset or name in the namespace dict.</p>
0
2016-10-15T21:38:11Z
[ "python", "stack", "callstack" ]
Make python read 12 from file as 12 not 1 and 2
40,063,930
<p>Trying to make a program that provides the price to different numbers of stages. In "tripss.txt",third line is the number 12, python interprets it as 1 and 2 instead and gives the price for each rather than the number as a whole, any way to fix it to that it's read as 12?.</p> <pre><code>infile = open("tripss.txt","r") customer_one= infile.readline().strip("\n") customer_two= infile.readline().strip("\n") customer_three= infile.readline().strip("\n") one_to_three_stages="euro 1.55" four_to_seven_stages="euro 1.85" seven_to_eleven_stages="euro 2.45" more_than_eleven_stages="euro 2.85" cheapest = ["1","2","3"] cheap = ["4","5","6","7"] expensive = ["7","8","9","10","11"] for number in customer_three: if number in cheapest: print one_to_three_stages elif number in cheap: print four_to_seven_stages elif number in expensive: print seven_to_eleven_stages else: print more_than_eleven_stages </code></pre>
-2
2016-10-15T20:33:30Z
40,064,065
<p>In your code it seems that you want to consider customer_three as a list of strings. However in your code it is a string, not a list of strings, and so the for loop iterates on the characters of the string ("1" and "2").<br> So I suggest you to replace: </p> <pre><code>customer_three= infile.readline().strip("\n") </code></pre> <p>with: </p> <pre><code>customer_three= infile.readline().strip("\n").split() </code></pre>
0
2016-10-15T20:48:17Z
[ "python", "file", "for-loop", "numbers", "readlines" ]
Make python read 12 from file as 12 not 1 and 2
40,063,930
<p>Trying to make a program that provides the price to different numbers of stages. In "tripss.txt",third line is the number 12, python interprets it as 1 and 2 instead and gives the price for each rather than the number as a whole, any way to fix it to that it's read as 12?.</p> <pre><code>infile = open("tripss.txt","r") customer_one= infile.readline().strip("\n") customer_two= infile.readline().strip("\n") customer_three= infile.readline().strip("\n") one_to_three_stages="euro 1.55" four_to_seven_stages="euro 1.85" seven_to_eleven_stages="euro 2.45" more_than_eleven_stages="euro 2.85" cheapest = ["1","2","3"] cheap = ["4","5","6","7"] expensive = ["7","8","9","10","11"] for number in customer_three: if number in cheapest: print one_to_three_stages elif number in cheap: print four_to_seven_stages elif number in expensive: print seven_to_eleven_stages else: print more_than_eleven_stages </code></pre>
-2
2016-10-15T20:33:30Z
40,064,328
<p>You say <em>third line is the number 12</em> so after <code>customer_three= infile.readline().strip("\n")</code>, <code>customer_three</code> will be the string <code>"12"</code>. If you then start the for loop <code>for number in customer_three:</code>, <code>number</code> will be assigned each element of the string - first <code>"1"</code>, and then <code>"2"</code>.</p> <p>The solution is simple. <code>customer_three</code> already has the string you want. Remove the <code>for</code> loop completely.</p>
0
2016-10-15T21:18:58Z
[ "python", "file", "for-loop", "numbers", "readlines" ]
Convert QueryDict into list of arguments
40,064,010
<p>I'm receiving via POST request the next payload through the view below:</p> <pre><code>class CustomView(APIView): """ POST data """ def post(self, request): extr= externalAPI() return Response(extr.addData(request.data)) </code></pre> <p>And in the <code>externalAPI</code> class I have the <code>addData()</code> function where I want to convert <em>QueryDict</em> to a simple list of arguments:</p> <pre><code>def addData(self, params): return self.addToOtherPlace(**params) </code></pre> <p>In other words, what I get in params is somethin like:</p> <pre><code>&lt;QueryDict: {u'data': [u'{"object":"a","reg":"1"}'], u'record': [u'DAFASDH']}&gt; </code></pre> <p>And I need to pass it to the addToOtherPlace() function like:</p> <pre><code>addToOtherPlace(data={'object':'a', 'reg': 1}, record='DAFASDH') </code></pre> <p>I have tried with different approaches but I have to say I'm not very familiar with dictionaries in python.</p> <p>Any help would be really appreciated.</p> <p>Thanks!</p>
0
2016-10-15T20:42:53Z
40,064,117
<p>You can write a helper function that walks through the <em>QueryDict</em> object and converts valid <em>JSON</em> objects to Python objects, string objects that are digits to integers and returns the first item of lists from lists:</p> <pre><code>import json def restruct(d): for k in d: # convert value if it's valid json if isinstance(d[k], list): v = d[k] try: d[k] = json.loads(v[0]) except ValueError: d[k] = v[0] # step into dictionary objects to convert string digits to integer if isinstance(d[k], dict): restruct(d[k]) elif d[k].isdigit(): d[k] = int(d[k]) params = {u'data': [u'{"object":"a","reg":"1"}'], u'record': [u'DAFASDH']} restruct(params) print(params) # {'record': 'DAFASDH', 'data': {'object': 'a', 'reg': 1}} </code></pre> <p>Note that this approach modifies the initial object <em>in-place</em>. You can make a <code>deepcopy</code>, and modify the copy instead if you're going to keep the original object intact:</p> <pre><code>import copy def addData(self, params): params_copy = copy.deepcopy(params) restruct(params_copy) return self.addToOtherPlace(**params_copy) </code></pre>
1
2016-10-15T20:54:22Z
[ "python", "json", "django", "dictionary" ]
Why is Python 3.5 crashing on a MySQL connection with correct credentials?
40,064,012
<p>I'm using Python 3.5.1, mysqlclient 1.3.9 (fork of MySQLdb that supports Python 3), and MariaDB 10.1 on Windows 10 (64-bit).</p> <p>When I run</p> <pre><code>import MySQLdb con = MySQLdb.connect(user=my_user, passwd=my_pass, db=my_db) </code></pre> <p>Python crashes.</p> <p>In pycharm, I am also presented with the message</p> <pre><code>Process finished with exit code -1073741819 (0xC0000005) </code></pre> <p>I don't get any other errors. This is different to what happens when I run the same statements with incorrect credentials:</p> <pre><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "C:\Program Files\Python35\lib\site-packages\MySQLdb\__init__.py", line 81, in Connect return Connection(*args, **kwargs) File "C:\Program Files\Python35\lib\site-packages\MySQLdb\connections.py", line 191, in __init__ super(Connection, self).__init__(*args, **kwargs2) _mysql_exceptions.OperationalError: (1045, "Access denied for user 'root'@'localhost' (using password: YES)") </code></pre> <p>This error does not occur on my CentOS server, which runs Python 3.4, mysqlclient 1.3.9, and MariaDB 10.1.</p> <p>I've tried using older versions of MariaDB as suggested by <a href="http://stackoverflow.com/questions/35572662/django-runserver-stuck-on-performing-system-checks">this question</a>, to no avail.</p> <p>What could be causing this crash and the mysterious lack of error reporting, and how can I fix it?</p> <p>Edit: In my system logs, I found this entry:</p> <p>General:</p> <pre><code>Faulting application name: python.exe, version: 3.5.1150.1013, time stamp: 0x56639598 Faulting module name: python35.dll, version: 3.5.1150.1013, time stamp: 0x56639583 Exception code: 0xc0000005 Fault offset: 0x00000000000e571c Faulting process id: 0x4a4 Faulting application start time: 0x01d2272a22ae1a1a Faulting application path: C:\Program Files\Python35\python.exe Faulting module path: C:\Program Files\Python35\python35.dll Report Id: 6dd874e6-5ea5-4919-af8b-4880a2c7ac5e Faulting package full name: Faulting package-relative application ID: </code></pre> <p>Details: </p> <pre><code>- System - Provider [ Name] Application Error - EventID 1000 [ Qualifiers] 0 Level 2 Task 100 Keywords 0x80000000000000 - TimeCreated [ SystemTime] 2016-10-15T21:21:48.041795500Z EventRecordID 7615 Channel Application Computer PETER-LENOVO Security - EventData python.exe 3.5.1150.1013 56639598 python35.dll 3.5.1150.1013 56639583 c0000005 00000000000e571c 4a4 01d2272a22ae1a1a C:\Program Files\Python35\python.exe C:\Program Files\Python35\python35.dll 6dd874e6-5ea5-4919-af8b-4880a2c7ac5e </code></pre>
0
2016-10-15T20:42:59Z
40,082,843
<p>I'm not familiar with <code>pycharm</code> but I think your problem is as @nemanjap suggests, with your <code>MySQLdb</code> installation. I just went through a similar nightmare (with Python 3.5), so I hope I can help. Here are my suggestions:</p> <ul> <li>If you haven't already, install <code>pip</code></li> <li>Install Visual Studio Community 2015 from <a href="https://www.visualstudio.com/downloads" rel="nofollow">https://www.visualstudio.com/downloads</a> (you only need the Python compilation tools)</li> <li>Install wheel: <code>pip install wheel</code></li> <li>Download the MySQLdb windows binary from <a href="http://www.lfd.uci.edu/~gohlke/pythonlibs/#mysql-python" rel="nofollow">http://www.lfd.uci.edu/~gohlke/pythonlibs/#mysql-python</a>, specifically <code>mysqlclient-1.3.8-cp35-cp35m-win32.whl</code> (I'm 64-bit too, but I was being cautious)</li> <li>Delete the MySQLdb folder from site-packages if it exists, just in case.</li> <li>Assuming you're in the same folder as the binary download, run <code>pip install mysqlclient-1.3.8-cp35-cp35m-win32.whl</code></li> </ul> <p>With a bit of luck, you should be able to connect.</p> <hr> <p><strong>Notes</strong></p> <p>On my machine, I was getting instantly aborted connections (<code>Got an error reading communication packets</code> in my <code>error.log</code>), even though my credentials were 100% correct. On the windows side, similar to OP, Python just "crashed", meaning I got a shell restart and never reaching past the <code>MySQLdb.connect</code> line. Even a <code>try</code> block didn't allow further execution (so actually a crash, as opposed to an exception or error). Thinking a compatibility issue (UNIX working totally fine), I tried to debug the <code>MySQLdb</code> in Windows, all the way to <code>import _mysql</code>, which is when I realized it was a C (compilation) issue.</p> <p>Having thought all was installed well, when I executed <code>pip install MySQLdb-python</code>, I got the following:</p> <pre><code>error: Unable to find vcvarsall.bat </code></pre> <p>Which meant I needed to install the compilation tools for my version of Python (3.5), which is included in the VSC2015 installation. I re-ran, and then got the following:</p> <pre><code>Cannot open include file: 'config-win.h' </code></pre> <p>Which meant I needed some required headers, from here: <a href="http://dev.mysql.com/downloads/connector/c/6.0.html#downloads" rel="nofollow">http://dev.mysql.com/downloads/connector/c/6.0.html#downloads</a> (again, 32-bit, just to play it safe for now). Then I got a bunch of <code>unresolved external symbol</code> errors, and realized how much I hate Windows, and installed the pre-compiled version instead. Worked wonders.</p> <p>Oh, and before someone suggests a different module or method to connect, like <code>mysql-connector</code>, apart from not solving the problem, there is usually the constraint that the same code (thus, the same imported modules) should work on both Windows and UNIX machines. Plus this: <a href="http://charlesnagy.info/it/python/python-mysqldb-vs-mysql-connector-query-performance" rel="nofollow">http://charlesnagy.info/it/python/python-mysqldb-vs-mysql-connector-query-performance</a></p> <p>Sorry for the long post. I needed to vent! Good luck!</p>
1
2016-10-17T09:30:23Z
[ "python", "mysql", "python-3.x", "mariadb" ]
XOR very big List with its rotation
40,064,067
<p>Efficient way to XOR on list such that,</p> <p>eg:</p> <pre><code>#here a,b,c,d are integers L = [a,b,c,d] N = [b,c,d,a] #right rotation of list L Newlist = enter code here[a^b, b^c, c ^d ,d^a] </code></pre> <p>as size of list is very large, is there any efficient way to solve.</p> <p>this is so far what i have done.</p> <pre><code>#right rotation of list def shift(seq, n): n = n % len(seq) return seq[n:] + seq[:n] L = [6,7,1,3] N = shift(L,1) new = [] for i,j in zip(L,N): new.append(i^j) print(new) </code></pre>
0
2016-10-15T20:48:23Z
40,064,123
<p>You can try to check this:</p> <pre><code>from collections import deque L = [6, 7, 1, 3] L2 = deque(L) L2.rotate(-1) # rotate to left result = [i ^ j for i, j in zip(L, L2)] </code></pre> <p>This might be at least slightly faster.</p> <p>Other solution would be to check this possibility:</p> <pre><code>from itertools import islice L = [6, 7, 1, 3] # This will add all the XoRs except for the last pair (6, 3) result = [i ^ j for i, j in zip(L, islice(L, 1, len(L))] # adding the last XOR result.append(L[0] ^ [L-1]) print(result) [1, 6, 2, 5] </code></pre>
3
2016-10-15T20:54:59Z
[ "python", "xor" ]
XOR very big List with its rotation
40,064,067
<p>Efficient way to XOR on list such that,</p> <p>eg:</p> <pre><code>#here a,b,c,d are integers L = [a,b,c,d] N = [b,c,d,a] #right rotation of list L Newlist = enter code here[a^b, b^c, c ^d ,d^a] </code></pre> <p>as size of list is very large, is there any efficient way to solve.</p> <p>this is so far what i have done.</p> <pre><code>#right rotation of list def shift(seq, n): n = n % len(seq) return seq[n:] + seq[:n] L = [6,7,1,3] N = shift(L,1) new = [] for i,j in zip(L,N): new.append(i^j) print(new) </code></pre>
0
2016-10-15T20:48:23Z
40,064,299
<p>Here is another approach. The generator I've written could probably be improved, but it gives you the idea. This is space efficient, because you are not building a new list:</p> <pre><code>&gt;&gt;&gt; def rotation(lst,n): ... for i in range(len(lst)): ... yield lst[(i + n) % len(lst)] ... &gt;&gt;&gt; L = [1,2,3,4,5] &gt;&gt;&gt; list(rotation(L,1)) [2, 3, 4, 5, 1] &gt;&gt;&gt; [a ^ b for a,b in zip(L,rotation(L,1))] [3, 1, 7, 1, 4] </code></pre> <p>An alternative way to define <code>rotation</code> would be:</p> <pre><code>&gt;&gt;&gt; def rotation(lst,n): ... yield from (lst[(i + n) % len(lst)] for i in range(len(lst))) ... &gt;&gt;&gt; L = ['a','b','c','d'] &gt;&gt;&gt; ["{}^{}".format(i,j) for i,j in zip(L,rotation(L,1))] ['a^b', 'b^c', 'c^d', 'd^a'] </code></pre>
0
2016-10-15T21:15:19Z
[ "python", "xor" ]
XOR very big List with its rotation
40,064,067
<p>Efficient way to XOR on list such that,</p> <p>eg:</p> <pre><code>#here a,b,c,d are integers L = [a,b,c,d] N = [b,c,d,a] #right rotation of list L Newlist = enter code here[a^b, b^c, c ^d ,d^a] </code></pre> <p>as size of list is very large, is there any efficient way to solve.</p> <p>this is so far what i have done.</p> <pre><code>#right rotation of list def shift(seq, n): n = n % len(seq) return seq[n:] + seq[:n] L = [6,7,1,3] N = shift(L,1) new = [] for i,j in zip(L,N): new.append(i^j) print(new) </code></pre>
0
2016-10-15T20:48:23Z
40,064,389
<p>Here's another method!</p> <p>I define a function that, given an index, returns the number at that index and its next neighbor on the "right" as a pair <code>(a, b)</code>, and then XOR those. It is also safe to give it indices outside the range of the list. So:</p> <pre><code>def rotate_and_xor(l): def get_pair_xor(i): i %= len(l) j = (i + 1) % len(l) return l[i] ^ l[j] return list(map(get_pair_xor, range(len(l)))) </code></pre> <p>I don't propose that this is necessarily the best solution; I just wanted to solve it a different way. Using list comprehensions like the others suggest is probably more Pythonic, but I like using <code>map</code>.</p>
0
2016-10-15T21:26:34Z
[ "python", "xor" ]
Python: importing a sub-package module from both the sub-package and the main package
40,064,202
<p>Here we go with my first ever stackoverflow quesion. I did search for an answer, but couldn't find a clear one. Here's the situation. I've got a structure like this:</p> <pre><code>myapp package/ __init.py__ main.py mod1.py mod2.py </code></pre> <p>Now, in this scenario, from main.py I am importing mod1.py, which also needs to be imported by mod2.py. Everything works fine, my imports look like this:</p> <p>main.py:</p> <pre><code>from mod1 import Class1 </code></pre> <p>mod2.py:</p> <pre><code>from mod1 import Class1 </code></pre> <p>However, I need to move my main.py to the main folder structure, like this:</p> <pre><code>myapp main.py package/ __init.py__ mod1.py mod2.py </code></pre> <p>And now what happens is that of course I need to change the way I import mod1 inside main.py:</p> <pre><code>from package.mod1 import Class1 </code></pre> <p>However, what also happens is that in order not to get an "ImportError: No module named 'mod1'", I have make the same type of change inside mod2.py:</p> <pre><code>from package.mod1 import Class1 </code></pre> <p>Why is that? mod2 is in the same folder/pakcage as mod1, so why - upon modifying main.py - am I expected to modify my import inside mod2?</p>
2
2016-10-15T21:06:00Z
40,064,571
<p>The reason this is happening is because how python looks for modules and packages when you run a python script as the <code>__main__</code> script.</p> <p>When you run <code>python main.py</code>, python will add the parent directory of <code>main.py</code> to the pythonpath, meaning packages and modules within the directory will be importable. When you moved main.py, you changed the directory that was added to the pythonpath.</p> <p>Generally, you don't want to rely on this mechanism for importing your modules, because it doesn't allow you to move your script and your package and modules are <em>only</em> importable when running that main script. What you should do is make sure your <code>package</code> is installed into a directory that is already in the pythonpath. There are several ways of doing this, but the most common is to create a <code>setup.py</code> script and actually <a href="https://packaging.python.org/distributing/" rel="nofollow">install your python package</a> for the python installation on your computer.</p>
1
2016-10-15T21:51:27Z
[ "python", "import" ]
Wait for threads to finish before running them again
40,064,337
<p>I am making a program that controls 2 motors through a raspberry Pi. I am running python code and I am wondering how to achieve the following :</p> <ul> <li>Run motor1</li> <li>Run motor2 simultaneously</li> <li>Wait for both motors to finish</li> <li>Run motor1</li> <li>Run motor2 simultaneously</li> <li><p>etc.</p> <p>What I have done so far is creating a Thread and using a queue.</p> <pre><code>class Stepper(Thread): def __init__(self, stepper): Thread.__init__(self) self.stepper = stepper self.q = Queue(maxsize=0) def setPosition(self, pos): self.q.put(pos) def run(self): while not self.q.empty(): item = self.q.get() // run motor and do some stuff thread_1 = Stepper(myStepper1) thread_2 = Stepper(myStepper2) thread_1.start() thread_2.start() loop = 10 while(loop): thread_1.setPosition(10) thread_2.setPosition(30) # I want to wait here thread_1.setPosition(10) thread_2.setPosition(30) loop = loop - 1 thread_1.join() thread_2.join() </code></pre></li> </ul> <p>Both thread_1 and thread_2 won't finish at the same time depending of the numbers of steps the motor need to process. I have tried to use the Lock() functionality but I am not sure how to correctly implement it. I also thought about re-creating the Threads but not sure if this is the correct solution. </p>
1
2016-10-15T21:19:51Z
40,064,713
<p>You can use <a href="https://docs.python.org/2/library/threading.html#threading.Semaphore" rel="nofollow"><code>Semaphore</code></a> actually:</p> <pre><code>from threading import Semaphore class Stepper(Thread): def __init__(self, stepper, semaphore): Thread.__init__(self) self.stepper = stepper self.semaphore = semaphore def setPosition(self, pos): self.q.put(pos) def run(self): while not self.q.empty(): try: # run motor and do some stuff finally: self.semaphore.release() # release semaphore when finished one cycle semaphore = Semaphore(2) thread_1 = Stepper(myStepper1, semaphore) thread_2 = Stepper(myStepper2, semaphore) thread_1.start() thread_2.start() loop = 10 for i in range(loop): semaphore.acquire() semaphore.acquire() thread_1.setPosition(10) thread_2.setPosition(30) semaphore.acquire() semaphore.acquire() # wait until the 2 threads both released the semaphore thread_1.setPosition(10) thread_2.setPosition(30) </code></pre>
1
2016-10-15T22:05:55Z
[ "python", "multithreading", "raspberry-pi", "python-multithreading" ]
Wait for threads to finish before running them again
40,064,337
<p>I am making a program that controls 2 motors through a raspberry Pi. I am running python code and I am wondering how to achieve the following :</p> <ul> <li>Run motor1</li> <li>Run motor2 simultaneously</li> <li>Wait for both motors to finish</li> <li>Run motor1</li> <li>Run motor2 simultaneously</li> <li><p>etc.</p> <p>What I have done so far is creating a Thread and using a queue.</p> <pre><code>class Stepper(Thread): def __init__(self, stepper): Thread.__init__(self) self.stepper = stepper self.q = Queue(maxsize=0) def setPosition(self, pos): self.q.put(pos) def run(self): while not self.q.empty(): item = self.q.get() // run motor and do some stuff thread_1 = Stepper(myStepper1) thread_2 = Stepper(myStepper2) thread_1.start() thread_2.start() loop = 10 while(loop): thread_1.setPosition(10) thread_2.setPosition(30) # I want to wait here thread_1.setPosition(10) thread_2.setPosition(30) loop = loop - 1 thread_1.join() thread_2.join() </code></pre></li> </ul> <p>Both thread_1 and thread_2 won't finish at the same time depending of the numbers of steps the motor need to process. I have tried to use the Lock() functionality but I am not sure how to correctly implement it. I also thought about re-creating the Threads but not sure if this is the correct solution. </p>
1
2016-10-15T21:19:51Z
40,064,754
<p>You can use the thread's <code>join</code> method like so:</p> <pre><code>thread_1.join() # Wait for thread_1 to finish thread_2.join() # Same for thread_2 </code></pre> <p>As per the documentation at <a href="https://docs.python.org/3/library/threading.html#threading.Thread.join" rel="nofollow">https://docs.python.org/3/library/threading.html#threading.Thread.join</a>:</p> <blockquote> <p>A thread can be <code>join()</code>ed many times.</p> </blockquote> <p>To run threads repeatedly, you will need to reinitialize the <code>Thread</code> object after each run.</p>
0
2016-10-15T22:10:04Z
[ "python", "multithreading", "raspberry-pi", "python-multithreading" ]
Multiplying spaces with length of input
40,064,369
<p>python newbie here. I'm trying to print a 5 line pyramid of text based off the user's input if the string is even. I'm having trouble making the pyramid centre without hardcoding the spaces in. In line 2 I'm getting "TypeError: unsupported operand type(s) for -: 'str' and 'int' If len is returning the length and int and I'm multiply the space by that number how is this an error? Thank you :)</p> <pre><code>userString = input( "Please enter a string with a value of 7 or less characters: " ) space = ' ' * int( len( userString ) ) - 1 left_side = userString[:len( userString ) // 2] right_side = userString[len( userString ) // 2:] def pyramid( left, right ): print( space + left_side + right_side ) print( space + left_side * 2 + right_side * 2 ) print( space + left_side * 3 + right_side * 3 ) print( space + left_side * 4 + right_side * 4 ) print( space + left_side * 5 + right_side * 5 ) </code></pre>
0
2016-10-15T21:23:29Z
40,064,386
<p><code>*</code> has higher precendence than <code>-</code>, so you must wrap them in parenthesis</p> <pre><code>space = ' ' * (len(userString) - 1) </code></pre>
0
2016-10-15T21:25:53Z
[ "python" ]
Most Pythonic way to find/check items in a list with O(1) complexity?
40,064,377
<p>The problem I'm facing is finding/checking items in a list with O(1) complexity. The following has a complexity of O(n):</p> <pre><code>'foo' in list_bar </code></pre> <p>This has a complexity of O(n) because you are using the <code>in</code> keyword on a <code>list</code>. (Refer to <a href="https://wiki.python.org/moin/TimeComplexity" rel="nofollow">Python Time Complexity</a>)</p> <p>However, if you use the <code>in</code> keyword on a <code>set</code>, it has a complexity of O(1).</p> <p>The reason why I need to figure out O(1) complexity for a list, and not a set, is largely due to the need to account for duplicate items within the list. Sets do not allow for duplicates. A decent example would be :</p> <pre><code>chars_available = ['h', 'e', 'l', 'o', 'o', 'z'] chars_needed = ['h', 'e', 'l', 'l', 'o'] def foo(chars_available, chars_needed): cpy_needed = list(chars_needed) for char in cpy_needed: if char in chars_available: chars_available.remove(char) chars_needed.remove(char) if not chars_needed: return True # if chars_needed == [] return False foo(chars_available, chars_needed) </code></pre> <p>The example is not the focus here, so please try not to get sidetracked by it. The focus is still trying to get O(1) complexity for finding items in a list. How would I accomplish that pythonically?</p> <p>(As extra credit, if you did want to show a better way of performing that operation in Python, pseudocode, or another language, I'd be happy to read it).</p> <p>Thank you!</p> <p><strong>Edit:</strong></p> <p>In response to Ami Tavory's answer, I learned you can't make lists faster than O(n), but the suggestion for <code>collections.Counter()</code> helped solve the application I was working on. I'm uploading my faster solution for Stack Overflow, the performance was phenomenal! If I'm not mistaken (correct me if I'm wrong), it should be O(1) since it involves only hashable values and no loop iteration.</p> <pre><code>from collections import Counter chars_available = ['h', 'e', 'l', 'o', 'o', 'z'] chars_needed = ['h', 'e', 'l', 'l', 'o'] def foo(chars_available, chars_needed): counter_available = Counter(chars_available) counter_needed = Counter(chars_needed) out = counter_needed - counter_available if not list(out.elements()): return True else: return False foo(chars_available, chars_needed) </code></pre> <p>Very fast, very pythonic! Thanks!</p>
3
2016-10-15T21:24:43Z
40,064,454
<p>In general, it's impossible to find elements in a <code>list</code> in constant time. You could hypothetically maintain both a <code>list</code> and a <code>set</code>, but updating operations will take linear time.</p> <p>You mention that your motivation is</p> <blockquote> <p>a list, and not a set, is largely due to the need to account for duplicate items within the list. Sets do not allow for duplicates.</p> </blockquote> <p>and ask not to focus on the example. If this is your motivation, you might want to use instead of a <code>set</code>, a <code>dict</code> mapping each element to the number of its occurrences. </p> <p>You might find <a href="https://docs.python.org/2/library/collections.html#collections.Counter"><code>collections.Counter</code></a> useful in particular:</p> <pre><code>In [1]: from collections import Counter In [2]: Counter(['h', 'e', 'l', 'o', 'o', 'z']) Out[2]: Counter({'e': 1, 'h': 1, 'l': 1, 'o': 2, 'z': 1}) </code></pre>
7
2016-10-15T21:33:53Z
[ "python", "algorithm", "performance", "python-3.x", "time-complexity" ]
urls.py entry for django v1.10 mysite.com:8000/index.html
40,064,411
<p>I'm having trouble getting the url entry in my app's urls.py file how I want it. When a person enters <code>mysite.com:8000/</code>, I want it to use the same view as <code>mysite.com:8000/index.html</code> I can use <code>url(r'^index.html$', views.index, name='index'),</code> and the view is properly displayed when I type <code>mysite.com:8000/index.html</code> into the chrome address bar, or I can trim the <code>.html</code>off both the urls.py entry and the address bar and it's ok, but I figured with regex, I could get this to display for <code>/</code> or for <code>index*</code></p> <p>lots of googling hasn't let me to an answer yet...</p> <p>EDIT: update based on @moses:</p> <pre><code>from django.conf import settings from django.conf.urls import url from django.conf.urls.static import static from . import views urlpatterns = [ url(r'^(index\.?[html]{,4})?$', views.index, name='index'), # url(r'^index$', views.index, name='index'), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) </code></pre> <p>now I get: "Exception Value:index() takes exactly 1 argument (2 given)"</p>
1
2016-10-15T21:28:34Z
40,064,484
<p>You can use the following regex pattern that matches 0 or 1 repetitions of <code>'index.html'</code> in the url i.e. either <code>^$</code> or <code>r'^index.html$'</code>:</p> <pre><code>&gt;&gt;&gt; re.match(r'^(?:index\.html)?$', 'index.html') &lt;_sre.SRE_Match object; span=(0, 10), match='index.html'&gt; &gt;&gt;&gt; re.match(r'^(?:index\.html)?$', '') &lt;_sre.SRE_Match object; span=(0, 0), match=''&gt; &gt;&gt;&gt; re.match(r'^(?:index\.html)?$', 'login') &gt;&gt;&gt; </code></pre> <p>And your Django url pattern becomes:</p> <pre><code>url(r'^(?:index.html)?$', views.index, name='index') </code></pre> <p>See demo: <a href="https://regex101.com/r/MVCPDN/2" rel="nofollow">https://regex101.com/r/MVCPDN/2</a></p>
1
2016-10-15T21:38:13Z
[ "python", "html", "django" ]
Issues with shaping Tensorflow/TFLearn inputs/outputs for images
40,064,422
<p>To learn more about deep learning and computer vision, I'm working on a project to perform lane-detection on roads. I'm using TFLearn as a wrapper around Tensorflow.</p> <p><strong>Background</strong></p> <p>The training inputs are images of roads (each image represented as a 50x50 pixel 2D array, with each element being a luminance value from 0.0 to 1.0).</p> <p>The training outputs are the same shape (50x50 array), but represent the marked lane area. Essentially, non-road pixels are 0, and road pixels are 1.</p> <p>This is not a fixed-size image classification problem, but instead a problem of detecting road vs. non-road pixels from a picture.</p> <p><strong>Problem</strong></p> <p>I've not been able to successfully shape my inputs/outputs in a way that TFLearn/Tensorflow accepts, and I'm not sure why. Here is my sample code:</p> <pre><code># X = An array of training inputs (of shape (50 x 50)). # Y = An array of training outputs (of shape (50 x 50)). # "None" equals the number of samples in my training set, 50 represents # the size of the 2D image array, and 1 represents the single channel # (grayscale) of the image. network = input_data(shape=[None, 50, 50, 1]) network = conv_2d(network, 50, 50, activation='relu') # Does the 50 argument represent the output shape? Should this be 2500? network = fully_connected(network, 50, activation='softmax') network = regression(network, optimizer='adam', loss='categorical_crossentropy', learning_rate=0.001) model = tflearn.DNN(network, tensorboard_verbose=1) model.fit(X, Y, n_epoch=10, shuffle=True, validation_set=(X, Y), show_metric=True, batch_size=1) </code></pre> <p>The error I receive is on the <code>model.fit</code> call, with error:</p> <p><code>ValueError: Cannot feed value of shape (1, 50, 50) for Tensor u'InputData/X:0', which has shape '(?, 50, 50, 1)'</code></p> <p>I've tried reducing the sample input/output arrays to a 1D vector (with length 2500), but that leads to other errors.</p> <p>I'm a bit lost with how to shape all this, any help would be greatly appreciated!</p>
4
2016-10-15T21:30:02Z
40,064,653
<p>Have a look at the imageflow wrapper for tensorflow, which converts a numpy array containing multiple images into a .tfrecords file, which is the suggested format for using tensorflow <a href="https://github.com/HamedMP/ImageFlow" rel="nofollow">https://github.com/HamedMP/ImageFlow</a>.</p> <p>You have to install it using </p> <pre><code>$ pip install imageflow </code></pre> <p>Suppose your numpy array containing some 'k' images is <code>k_images</code> and the corresponding k labels (one-hot-encoded) are stored in <code>k_labels</code>, then creating a .tfrecords file with the name 'tfr_file.tfrecords' gets as simple as writing the line</p> <pre><code>imageflow.convert_images(k_images, k_labels, 'tfr_file') </code></pre> <p>Alternatively, Google's Inception model contains a code to read images in a folder assuming each folder represents one label <a href="https://github.com/tensorflow/models/blob/master/inception/inception/data/build_image_data.py" rel="nofollow">https://github.com/tensorflow/models/blob/master/inception/inception/data/build_image_data.py</a></p>
1
2016-10-15T21:59:45Z
[ "python", "machine-learning", "computer-vision", "neural-network", "tensorflow" ]
Share DB connection in a process pool
40,064,437
<p>I have a Python 3 program that updates a large list of rows based on their ids (in a table in a Postgres 9.5 database).</p> <p>I use multiprocessing to speed up the process. As Psycopg's connections can’t be shared across processes, I create a connection <strong>for each row</strong>, then close it.</p> <p>Overall, multiprocessing is faster than single processing (5 times faster with 8 CPUs). However, creating a connection is slow: I'd like to create just a few connections and keep them open as long as required.</p> <p>Since .map() chops ids_list into a number of chunks which it submits to the process pool, would it be possible to share a database connection for all ids in the same chunk/process?</p> <p>Sample code:</p> <pre><code>from multiprocessing import Pool import psycopg2 def create_db_connection(): conn = psycopg2.connect(database=database, user=user, password=password, host=host) return conn def my_function(item_id): conn = create_db_connection() # Other CPU-intensive operations are done here cur = conn.cursor() cur.execute(""" UPDATE table SET my_column = 1 WHERE id = %s; """, (item_id, )) cur.close() conn.commit() if __name__ == '__main__': ids_list = [] # Long list of ids pool = Pool() # os.cpu_count() processes pool.map(my_function, ids_list) </code></pre> <p>Thanks for any help you can provide.</p>
1
2016-10-15T21:32:00Z
40,064,748
<p>You can use the <strong>initializer</strong> parameter of the Pool constructor. Setup the DB connection in the initializer function. Maybe pass the connection credentials as parameters.</p> <p>Have a look at the docs: <a href="https://docs.python.org/3/library/multiprocessing.html#module-multiprocessing.pool" rel="nofollow">https://docs.python.org/3/library/multiprocessing.html#module-multiprocessing.pool</a></p>
0
2016-10-15T22:09:40Z
[ "python", "postgresql", "multiprocessing", "psycopg2" ]
Python: Unable to remove spaces from list
40,064,559
<p>I am trying to remove white spaces from a list of strings in Python. I have tried almost every other method, but still I am not able to remove the spaces. Here is the list:</p> <pre><code>names=[': A slund\n', ': N Brenner and B Jessop and M Jones and G Macleod\n', ': C Boone\n', ': PB Evans\n', ': F Neil utitle: uThe architecture of markets}\n', ': PA Hall and D Soskice\n', '', '', '', '', '', '', '', ': EBYP HIGONNET and DS LANDES and H ROSOVSKY\n', '', '', '', '', '', '', ': DS Landes\n', '', '', '', '', '', '', '', ': DC North\n', '', '', '', '', '', '', '', ': K Polyani\n', '', '', '', '', '', ''] </code></pre> <p>Here is my code:</p> <pre><code>for i in names: if len(i)== 0: // i=='' // len(i)&lt;=1 names.remove(i) print names </code></pre>
0
2016-10-15T21:48:39Z
40,064,591
<p>With list comprehension.</p> <pre><code>names_without_space = [name.replace(' ', '') for name in names] print(names_without_space[:3]) # [':Aslund\n', ':NBrennerandBJessopandMJonesandGMacleod\n', ':CBoone\n'] </code></pre>
1
2016-10-15T21:53:41Z
[ "python", "list", "spaces" ]
Python search text file and count occurrences of a specified string
40,064,565
<p>I am attempting to use python to search a text file and count the number of times a user defined word appears. But when I run my code below instead of getting a sum of the number of times that unique word appears in the file, I am getting a count for the number lines within that file contain that word. </p> <p>Example: the word 'bob' exists 56 times in the text file, appearing in 19 of the total 63 lines of text. When I run my code the console prints '19'.</p> <p>I am guessing I need to do something different with my split method? I am running Python 2.7.10.</p> <pre><code>user_search_value = raw_input("Enter the value or string to search for: ") count = 0 with open(file.txt, 'r') as f: for word in f.readlines(): words = word.lower().split() if user_search_value in words: count += 1 print count </code></pre>
0
2016-10-15T21:50:21Z
40,064,630
<p>One way to do this would be to loop over the words after you split the line and increment <code>count</code> for each matching word:</p> <pre><code>user_search_value = raw_input("Enter the value or string to search for: ") count = 0 with open(file.txt, 'r') as f: for line in f.readlines(): words = line.lower().split() for word in words: if word == user_search_value: count += 1 print count </code></pre>
0
2016-10-15T21:58:13Z
[ "python", "python-2.7", "string-matching" ]
Python search text file and count occurrences of a specified string
40,064,565
<p>I am attempting to use python to search a text file and count the number of times a user defined word appears. But when I run my code below instead of getting a sum of the number of times that unique word appears in the file, I am getting a count for the number lines within that file contain that word. </p> <p>Example: the word 'bob' exists 56 times in the text file, appearing in 19 of the total 63 lines of text. When I run my code the console prints '19'.</p> <p>I am guessing I need to do something different with my split method? I am running Python 2.7.10.</p> <pre><code>user_search_value = raw_input("Enter the value or string to search for: ") count = 0 with open(file.txt, 'r') as f: for word in f.readlines(): words = word.lower().split() if user_search_value in words: count += 1 print count </code></pre>
0
2016-10-15T21:50:21Z
40,075,922
<p>As I mentioned in the comment above, after playing with this for a (long) while I figured it out. My code is below.</p> <pre><code>#read file f = open(filename, "r") lines = f.readlines() f.close() #looking for patterns for line in lines: line = line.strip().lower().split() for words in line: if words.find(user_search_value.lower()) != -1: count += 1 print("\nYour search value of '%s' appears %s times in this file" % (user_search_value, count)) </code></pre>
0
2016-10-16T21:59:25Z
[ "python", "python-2.7", "string-matching" ]
Image display error after changing dtype of image matrix
40,064,587
<p>I'm using opencv + python to process fundus(retinal images). There is a problem that im facing while converting a float64 image to uint8 image.</p> <p><strong>Following is the python code:</strong></p> <pre><code>import cv2 import matplotlib.pyplot as plt import numpy as np from tkFileDialog import askopenfilename filename = askopenfilename() a = cv2.imread(filename) height, width, channel = a.shape b, Ago, Aro = cv2.split(a) mr = np.average(Aro) sr = np.std(Aro) Ar = Aro - np.mean(Aro) Ar = Ar - mr - sr Ag = Ago - np.mean(Ago) Ag = Ag - mr - sr #Values of elements in Ar # Ar = [[-179.17305527, -169.17305527, -176.17305527, ..., -177.17305527, -177.17305527, -177.17305527], # [-178.17305527, -169.17305527, -172.17305527, ..., -177.17305527, -177.17305527, -177.17305527], # [-179.17305527, -178.17305527, -179.17305527, ..., -177.17305527, -177.17305527, -177.17305527], # ..., # [-177.17305527, -177.17305527, -177.17305527, ..., -177.17305527, -177.17305527, -177.17305527], # [-177.17305527, -177.17305527, -177.17305527, ..., -177.17305527, -177.17305527, -177.17305527], # [-177.17305527, -177.17305527, -177.17305527, ..., -177.17305527, -177.17305527, -177.17305527]] Mr = np.mean(Ar) SDr = np.std(Ar) print "MR = ", Mr, "SDr = ", SDr Mg = np.mean(Ag) SDg = np.std(Ag) Thg = np.mean(Ag) + 2 * np.std(Ag) + 50 + 12 Thr = 50 - 12 - np.std(Ar) print "Thr = ", Thr Dd = np.zeros((height, width)) Dc = Dd for i in range(height): for j in range(width): if Ar[i][j] &gt; Thr: Dd[i][j] = 255 else: Dd[i][j] = 0 TDd = np.uint8(Dd) TDd2 = Dd for i in range(height): for j in range(width): if Ag[i][j] &gt; Thg: Dc[i][j] = 1 else: Dc[i][j] = 0 #CALCULATING RATIO ratio = 500.0 / Dd.shape[1] dim = (500, int(Dd.shape[0] * ratio)) # # #RESIZING TO-BE-DISPLAYED IMAGES resized_TDd = cv2.resize(TDd, dim, interpolation=cv2.INTER_AREA) resized_TDd2 = cv2.resize(TDd2, dim, interpolation=cv2.INTER_AREA) resized_original = cv2.resize(Aro, dim, interpolation=cv2.INTER_AREA) cv2.imshow('TDd', resized_TDd) cv2.imshow('TDd2', resized_TDd2) cv2.imshow('Aro', resized_original) cv2.waitKey(0) </code></pre> <p><code>Ar[][]</code> has -ve as well as +ve values and <code>Thr</code> has a -ve value. <strong><code>Dd</code> is the image which i want to display.</strong> The problem is that <code>TDd</code> displays a bizarre image <em>(255s and 0s are being assigned to appropriate pixels, i checked</em> but the image being displayed is weird and not similar to <code>TDd</code></p> <p><strong>Original image</strong></p> <p><a href="https://i.stack.imgur.com/vxtIU.jpg" rel="nofollow"><img src="https://i.stack.imgur.com/vxtIU.jpg" alt="enter image description here"></a></p> <p><strong>Red channel image:</strong></p> <p><a href="https://i.stack.imgur.com/ZWqCL.png" rel="nofollow"><img src="https://i.stack.imgur.com/ZWqCL.png" alt="enter image description here"></a></p> <p><strong>TDd (uint8 of Dd):</strong></p> <p><a href="https://i.stack.imgur.com/HOCd9.png" rel="nofollow"><img src="https://i.stack.imgur.com/HOCd9.png" alt="enter image description here"></a></p> <p><strong>TDd2 (same as Dd)</strong></p> <p><a href="https://i.stack.imgur.com/iv7al.png" rel="nofollow"><img src="https://i.stack.imgur.com/iv7al.png" alt="enter image description here"></a></p> <p><strong>Dd2 (declared uint8 dtype while initializing)</strong></p> <p><a href="https://i.stack.imgur.com/ZKHwT.png" rel="nofollow"><img src="https://i.stack.imgur.com/ZKHwT.png" alt="enter image description here"></a></p> <p>Why are the <code>TDd</code> and <code>TDd2</code> images different? <strong>Since the difference between the gray values of the pixels (as far as i understand and know) in these 2 images is only 255, 0 <em>(in TDd)</em> and 255.0, 0.0 <em>(in TDd2)</em></strong>.</p> <p>It would be a great great help if someone could tell me.</p>
1
2016-10-15T21:52:55Z
40,064,690
<p>Usually when Images are represented with np float64 arrays, RGB values are in range 0 to 1. So when converting to uint8 there is a possible precision loss when converting from float64 to uint8.</p> <p>I would directly create Dd as a:</p> <pre><code>Dd = np.zeros((height, width), dtype=np.uint8) </code></pre> <p>Then it should work.</p>
1
2016-10-15T22:03:57Z
[ "python", "opencv", "numpy" ]
Image display error after changing dtype of image matrix
40,064,587
<p>I'm using opencv + python to process fundus(retinal images). There is a problem that im facing while converting a float64 image to uint8 image.</p> <p><strong>Following is the python code:</strong></p> <pre><code>import cv2 import matplotlib.pyplot as plt import numpy as np from tkFileDialog import askopenfilename filename = askopenfilename() a = cv2.imread(filename) height, width, channel = a.shape b, Ago, Aro = cv2.split(a) mr = np.average(Aro) sr = np.std(Aro) Ar = Aro - np.mean(Aro) Ar = Ar - mr - sr Ag = Ago - np.mean(Ago) Ag = Ag - mr - sr #Values of elements in Ar # Ar = [[-179.17305527, -169.17305527, -176.17305527, ..., -177.17305527, -177.17305527, -177.17305527], # [-178.17305527, -169.17305527, -172.17305527, ..., -177.17305527, -177.17305527, -177.17305527], # [-179.17305527, -178.17305527, -179.17305527, ..., -177.17305527, -177.17305527, -177.17305527], # ..., # [-177.17305527, -177.17305527, -177.17305527, ..., -177.17305527, -177.17305527, -177.17305527], # [-177.17305527, -177.17305527, -177.17305527, ..., -177.17305527, -177.17305527, -177.17305527], # [-177.17305527, -177.17305527, -177.17305527, ..., -177.17305527, -177.17305527, -177.17305527]] Mr = np.mean(Ar) SDr = np.std(Ar) print "MR = ", Mr, "SDr = ", SDr Mg = np.mean(Ag) SDg = np.std(Ag) Thg = np.mean(Ag) + 2 * np.std(Ag) + 50 + 12 Thr = 50 - 12 - np.std(Ar) print "Thr = ", Thr Dd = np.zeros((height, width)) Dc = Dd for i in range(height): for j in range(width): if Ar[i][j] &gt; Thr: Dd[i][j] = 255 else: Dd[i][j] = 0 TDd = np.uint8(Dd) TDd2 = Dd for i in range(height): for j in range(width): if Ag[i][j] &gt; Thg: Dc[i][j] = 1 else: Dc[i][j] = 0 #CALCULATING RATIO ratio = 500.0 / Dd.shape[1] dim = (500, int(Dd.shape[0] * ratio)) # # #RESIZING TO-BE-DISPLAYED IMAGES resized_TDd = cv2.resize(TDd, dim, interpolation=cv2.INTER_AREA) resized_TDd2 = cv2.resize(TDd2, dim, interpolation=cv2.INTER_AREA) resized_original = cv2.resize(Aro, dim, interpolation=cv2.INTER_AREA) cv2.imshow('TDd', resized_TDd) cv2.imshow('TDd2', resized_TDd2) cv2.imshow('Aro', resized_original) cv2.waitKey(0) </code></pre> <p><code>Ar[][]</code> has -ve as well as +ve values and <code>Thr</code> has a -ve value. <strong><code>Dd</code> is the image which i want to display.</strong> The problem is that <code>TDd</code> displays a bizarre image <em>(255s and 0s are being assigned to appropriate pixels, i checked</em> but the image being displayed is weird and not similar to <code>TDd</code></p> <p><strong>Original image</strong></p> <p><a href="https://i.stack.imgur.com/vxtIU.jpg" rel="nofollow"><img src="https://i.stack.imgur.com/vxtIU.jpg" alt="enter image description here"></a></p> <p><strong>Red channel image:</strong></p> <p><a href="https://i.stack.imgur.com/ZWqCL.png" rel="nofollow"><img src="https://i.stack.imgur.com/ZWqCL.png" alt="enter image description here"></a></p> <p><strong>TDd (uint8 of Dd):</strong></p> <p><a href="https://i.stack.imgur.com/HOCd9.png" rel="nofollow"><img src="https://i.stack.imgur.com/HOCd9.png" alt="enter image description here"></a></p> <p><strong>TDd2 (same as Dd)</strong></p> <p><a href="https://i.stack.imgur.com/iv7al.png" rel="nofollow"><img src="https://i.stack.imgur.com/iv7al.png" alt="enter image description here"></a></p> <p><strong>Dd2 (declared uint8 dtype while initializing)</strong></p> <p><a href="https://i.stack.imgur.com/ZKHwT.png" rel="nofollow"><img src="https://i.stack.imgur.com/ZKHwT.png" alt="enter image description here"></a></p> <p>Why are the <code>TDd</code> and <code>TDd2</code> images different? <strong>Since the difference between the gray values of the pixels (as far as i understand and know) in these 2 images is only 255, 0 <em>(in TDd)</em> and 255.0, 0.0 <em>(in TDd2)</em></strong>.</p> <p>It would be a great great help if someone could tell me.</p>
1
2016-10-15T21:52:55Z
40,082,027
<p>Look I executed your code and there are the <a href="http://postimg.org/gallery/1qi7dozn0" rel="nofollow">results</a></p> <p>They seem pretty normal to me... this is the exact <a href="https://pastebin.com/6jwgKi9r" rel="nofollow">code</a> I used</p> <p>Ar is different from the others because when you <code>imShow()</code> it, it puts white where values are > 0 black otherwise. The other matrices after tour code get white where > <code>Thr</code> which is less than 0, so more pixel get white obviously.</p> <p><strong>update</strong></p> <p>You assigned Dd to Dc when you should've done Dc = np.zeros((height, width)).</p>
1
2016-10-17T08:48:48Z
[ "python", "opencv", "numpy" ]
Google search scrapper , Python
40,064,588
<p>I am new to Python and trying to make a Google search scrapper for the purpose of getting stock prices , but I run my code below I dont get any results instead I am getting the page HTML formatting.</p> <pre><code>import urllib.request from bs4 import BeautifulSoup import requests url = 'https://www.google.com/webhp?sourceid=chrome-instant&amp;ion=1&amp;espv=2&amp;ie=UTF-8#q=uwti' response = requests.get(url) html = response.content soup = BeautifulSoup(html, "html.parser") print(soup.prettify()) </code></pre> <p>Am I missing something very simple , please give me some pointers on this . I am trying to extract the current stock value.How do I extract this value in the attached image ?</p> <p><a href="https://i.stack.imgur.com/BSfxl.jpg" rel="nofollow"><img src="https://i.stack.imgur.com/BSfxl.jpg" alt="enter image description here"></a></p>
1
2016-10-15T21:53:08Z
40,064,707
<p>Check out <code>Beautiful Soup's</code> <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/#find-all" rel="nofollow">documentation</a> on how to select elements of the HTML document you just parsed you could try something like:</p> <p><code>soup.findAll("span", ['_Rnb', 'fmob_pr, 'fac-l'])</code></p> <p>The above method will find the span element that implements the classes in the list.</p> <p>FYI: The stock price does not get fetched by the initial request from what I can see, use the <code>Inspect Element</code> feature of your browser to capture the requests sent, from what I can see there is a request to the url <code>https://www.google.gr/async/finance_price_updates</code>. Maybe this is used to fetched the price for the stock, see if you can sent requests to it directly rather than fetching the whole HTML.</p>
0
2016-10-15T22:05:18Z
[ "python", "parsing", "beautifulsoup", "urllib" ]
Google search scrapper , Python
40,064,588
<p>I am new to Python and trying to make a Google search scrapper for the purpose of getting stock prices , but I run my code below I dont get any results instead I am getting the page HTML formatting.</p> <pre><code>import urllib.request from bs4 import BeautifulSoup import requests url = 'https://www.google.com/webhp?sourceid=chrome-instant&amp;ion=1&amp;espv=2&amp;ie=UTF-8#q=uwti' response = requests.get(url) html = response.content soup = BeautifulSoup(html, "html.parser") print(soup.prettify()) </code></pre> <p>Am I missing something very simple , please give me some pointers on this . I am trying to extract the current stock value.How do I extract this value in the attached image ?</p> <p><a href="https://i.stack.imgur.com/BSfxl.jpg" rel="nofollow"><img src="https://i.stack.imgur.com/BSfxl.jpg" alt="enter image description here"></a></p>
1
2016-10-15T21:53:08Z
40,064,906
<p>Like @Jeff mentioned, this kind of tasks are easier to handle by APIs rather than scrapping web pages.</p> <p>Here is a solution using Yahoo Finance API</p> <pre><code>import urllib2 response = urllib2.urlopen('http://finance.yahoo.com/d/quotes.csv?s=UWTI&amp;f=sa') print response.read() </code></pre> <p>Output:</p> <pre><code>"UWTI",27.40 </code></pre> <p>You can fine tune the returned data by changing the format string(eg:f=sab2) Here is the details on the <a href="http://www.jarloo.com/yahoo_finance/" rel="nofollow">API</a></p>
-1
2016-10-15T22:30:30Z
[ "python", "parsing", "beautifulsoup", "urllib" ]
Google search scrapper , Python
40,064,588
<p>I am new to Python and trying to make a Google search scrapper for the purpose of getting stock prices , but I run my code below I dont get any results instead I am getting the page HTML formatting.</p> <pre><code>import urllib.request from bs4 import BeautifulSoup import requests url = 'https://www.google.com/webhp?sourceid=chrome-instant&amp;ion=1&amp;espv=2&amp;ie=UTF-8#q=uwti' response = requests.get(url) html = response.content soup = BeautifulSoup(html, "html.parser") print(soup.prettify()) </code></pre> <p>Am I missing something very simple , please give me some pointers on this . I am trying to extract the current stock value.How do I extract this value in the attached image ?</p> <p><a href="https://i.stack.imgur.com/BSfxl.jpg" rel="nofollow"><img src="https://i.stack.imgur.com/BSfxl.jpg" alt="enter image description here"></a></p>
1
2016-10-15T21:53:08Z
40,065,315
<p>It is in the source when you right-click and choose view-source in your browser. You just need to change the <em>url</em> slightly and pass a <em>user-agent</em> to match what you see there using requests:</p> <pre><code>In [2]: from bs4 import BeautifulSoup ...: import requests ...: ...: url = 'https://www.google.com/search?q=uwti&amp;rct=j' ...: response = requests.get(url, headers={ ...: "user-agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (K ...: HTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36"}) ...: html = response.content ...: ...: soup = BeautifulSoup(html, "html.parser") ...: print(soup.select_one("span._Rnb.fmob_pr.fac-l").text) ...: 27.51 </code></pre> <p><code>soup.find("span", class_="_Rnb fmob_pr fac-l").text</code> would also work and is the correct way to look for a tag using the <em>css classes</em> with find or <em>find_all</em></p> <p>You can see in chrome when you use <a href="https://www.google.com/webhp?sourceid=chrome-instant&amp;ion=1&amp;espv=2&amp;ie=UTF-8#q=uwti" rel="nofollow">https://www.google.com/webhp?sourceid=chrome-instant&amp;ion=1&amp;espv=2&amp;ie=UTF-8#q=uwti</a>, there is a redirect to <a href="https://www.google.com/search?q=uwti&amp;rct=j" rel="nofollow">https://www.google.com/search?q=uwti&amp;rct=j</a>:</p> <p><a href="https://i.stack.imgur.com/uEeoM.png" rel="nofollow"><img src="https://i.stack.imgur.com/uEeoM.png" alt="enter image description here"></a></p>
2
2016-10-15T23:36:40Z
[ "python", "parsing", "beautifulsoup", "urllib" ]
Counting sub-element in string?
40,064,589
<p>Say I have a <code>string = "Nobody will give me pancakes anymore"</code></p> <p>I want to count each word in the string. So I do <code>string.split()</code> to get a list in order to get <code>['Nobody', 'will', 'give', 'me', 'pancakes', 'anymore']</code>.</p> <p>But when I want to know the length of <code>'Nobody'</code> by inputing <code>len(string[0])</code> it only gives me <code>1</code>, because it thinks that the 0th element is just <code>'N'</code> and not <code>'Nobody'</code>. </p> <p>What do I have to do to ensure I can find the length of the whole word, rather than that single element?</p>
0
2016-10-15T21:53:09Z
40,064,601
<p>You took the first letter of <code>string[0]</code>, ignoring the result of the <code>string.split()</code> call.</p> <p>Store the split result; that's a list with individual words:</p> <pre><code>words = string.split() first_worth_length = len(words[0]) </code></pre> <p>Demo:</p> <pre><code>&gt;&gt;&gt; string = "Nobody will give me pancakes anymore" &gt;&gt;&gt; words = string.split() &gt;&gt;&gt; words[0] 'Nobody' &gt;&gt;&gt; len(words[0]) 6 </code></pre>
4
2016-10-15T21:54:51Z
[ "python", "list", "string-length" ]
Counting sub-element in string?
40,064,589
<p>Say I have a <code>string = "Nobody will give me pancakes anymore"</code></p> <p>I want to count each word in the string. So I do <code>string.split()</code> to get a list in order to get <code>['Nobody', 'will', 'give', 'me', 'pancakes', 'anymore']</code>.</p> <p>But when I want to know the length of <code>'Nobody'</code> by inputing <code>len(string[0])</code> it only gives me <code>1</code>, because it thinks that the 0th element is just <code>'N'</code> and not <code>'Nobody'</code>. </p> <p>What do I have to do to ensure I can find the length of the whole word, rather than that single element?</p>
0
2016-10-15T21:53:09Z
40,064,640
<p>Yup, <code>string[0]</code> is just <code>'N'</code></p> <p>Regarding your statement...</p> <blockquote> <p>I want to count each word in the string</p> </blockquote> <pre><code>&gt;&gt;&gt; s = "Nobody will give me pancakes anymore" &gt;&gt;&gt; lens = map(lambda x: len(x), s.split()) &gt;&gt;&gt; print lens [6, 4, 4, 2, 8, 7] </code></pre> <p>So, then you can do <code>lens[0]</code></p>
1
2016-10-15T21:58:40Z
[ "python", "list", "string-length" ]
Counting sub-element in string?
40,064,589
<p>Say I have a <code>string = "Nobody will give me pancakes anymore"</code></p> <p>I want to count each word in the string. So I do <code>string.split()</code> to get a list in order to get <code>['Nobody', 'will', 'give', 'me', 'pancakes', 'anymore']</code>.</p> <p>But when I want to know the length of <code>'Nobody'</code> by inputing <code>len(string[0])</code> it only gives me <code>1</code>, because it thinks that the 0th element is just <code>'N'</code> and not <code>'Nobody'</code>. </p> <p>What do I have to do to ensure I can find the length of the whole word, rather than that single element?</p>
0
2016-10-15T21:53:09Z
40,064,994
<pre><code>words = s.split() d = {word : len(word) for word in words} or words = s.split() d = {} for word in words: if word not in d: d[word]=0 d[word]+=len(word) In [15]: d Out[15]: {'me': 2, 'anymore': 7, 'give': 4, 'pancakes': 8, 'Nobody': 6, 'will': 4} In [16]: d['Nobody'] Out[16]: 6 </code></pre>
0
2016-10-15T22:41:42Z
[ "python", "list", "string-length" ]
python program to find prime number n by seeing if they can divide evenly into prime numbers less that the squareroot of n
40,064,657
<p>How do I make this return the right results for primes less than 10 ?</p> <pre><code>from math import * def isPrime(n): i = [c for c in range(int(sqrt(n)),0,-1) if c % 2 != 0 and c &gt; 1 ] for x in i: if n % x == 0: return print('%s is not prime' % (n)) return print('%s is prime number' %(n)) def main(): loopCnt = 'y' while loopCnt != 'n': n = int(input('Enter a integer greater than 2: ')) isPrime(n) loopCnt = input('Enter any key to try again or enter n to exit').strip().lower() main() </code></pre> <p>It is not giving the desired output</p>
-3
2016-10-15T22:00:08Z
40,064,716
<pre><code>i = [c for c in range(int(sqrt(n)),0,-1) if c % 2 != 0] </code></pre> <p>This code is skipping all even divisors. This is correct for <em>most</em> divisors, but it incorrectly skips 2, so it will misclassify even numbers!</p> <p>You need to make an exception for 2, either in the filter or by adding a special case to check whether <code>n</code> is an even number greater than 2.</p> <p>(As an aside, checking divisors in reverse order will slow you down. Small divisors are more common in randomly chosen composite numbers than large ones.)</p>
0
2016-10-15T22:06:16Z
[ "python" ]
python program to find prime number n by seeing if they can divide evenly into prime numbers less that the squareroot of n
40,064,657
<p>How do I make this return the right results for primes less than 10 ?</p> <pre><code>from math import * def isPrime(n): i = [c for c in range(int(sqrt(n)),0,-1) if c % 2 != 0 and c &gt; 1 ] for x in i: if n % x == 0: return print('%s is not prime' % (n)) return print('%s is prime number' %(n)) def main(): loopCnt = 'y' while loopCnt != 'n': n = int(input('Enter a integer greater than 2: ')) isPrime(n) loopCnt = input('Enter any key to try again or enter n to exit').strip().lower() main() </code></pre> <p>It is not giving the desired output</p>
-3
2016-10-15T22:00:08Z
40,064,791
<p>Your error is that you exit the <code>for</code> loop in the first iteration <em>always</em>. You should only exit when you find it has a divisor, but otherwise you should keep looping. When you exit the loop without finding a divisor then is the time to return that fact.</p> <p>So change:</p> <pre><code>for x in i: if n % x == 0: return print('%s is not prime' % (n)) else: return print('%s is prime number' %(n)) </code></pre> <p>to:</p> <pre><code>for x in i: if n % x == 0: return print('%s is not prime' % (n)) return print('%s is prime number' %(n)) </code></pre> <p>Secondly, your <code>i</code> array includes the number 1, and since all numbers are dividable by 1 that does not make sense. So the range should stop before 1 instead of 0. Also, you should include 2 as a divider.</p> <p>So change:</p> <pre><code>i = [c for c in range(int(math.sqrt(n)),0,-1) if c % 2 != 0] </code></pre> <p>By:</p> <pre><code>i = [c for c in range(int(math.sqrt(n)),1,-1) if c % 2 != 0] + [2] </code></pre> <p>See it in <a href="https://repl.it/DxN2/1" rel="nofollow">repl.it</a></p>
0
2016-10-15T22:13:34Z
[ "python" ]
python program to find prime number n by seeing if they can divide evenly into prime numbers less that the squareroot of n
40,064,657
<p>How do I make this return the right results for primes less than 10 ?</p> <pre><code>from math import * def isPrime(n): i = [c for c in range(int(sqrt(n)),0,-1) if c % 2 != 0 and c &gt; 1 ] for x in i: if n % x == 0: return print('%s is not prime' % (n)) return print('%s is prime number' %(n)) def main(): loopCnt = 'y' while loopCnt != 'n': n = int(input('Enter a integer greater than 2: ')) isPrime(n) loopCnt = input('Enter any key to try again or enter n to exit').strip().lower() main() </code></pre> <p>It is not giving the desired output</p>
-3
2016-10-15T22:00:08Z
40,064,984
<p>As suggested by @Duskwolf, the line where you check for primes is wrong. A replacement function could simply be </p> <pre><code>import numpy as np def isPrime(n): len = int(sqrt(n)) divisors = np.zeros(len, dtype=np.bool) for i in range(1,len): if(n%(i+1)==0): divisors[i]=True prime = not divisors.any() if(prime): return print('%s is prime' % (n)) return print('%s is not a prime number' %(n)) </code></pre>
0
2016-10-15T22:40:37Z
[ "python" ]
IndexError: list index of range. Python 3
40,064,660
<p>I was just trying to create a Matrix filled with zeros, like the function of numpy.</p> <p>But it continues to give me that error. Here's the code:</p> <pre><code>def zeros(a,b): for i in range(a): for j in range(b): R[i][j]=0 return R </code></pre> <p>I tried with a=3 and b=2, so it would give me a 3x2 matrix filled with zeros. It is a part of the program to multiply matrix</p> <p>I'm new in this whole programming world, thanks for the help.</p>
-2
2016-10-15T22:00:29Z
40,064,741
<p>You could do that:</p> <pre><code>&gt;&gt;&gt; def zeros(a,b): ... return [[0 for _ in range(a)] for _ in range(b)] ... &gt;&gt;&gt; zeros(3,2) [[0, 0, 0], [0, 0, 0]] </code></pre> <p>Or something more close to your code:</p> <pre><code>def zeros(a,b): R = [] l = [0]*a for _ in range(b): R.append(l) return R </code></pre>
0
2016-10-15T22:09:12Z
[ "python", "python-3.x" ]
Python abundant, deficient, or perfect number
40,064,750
<pre><code>def classify(numb): i=1 j=1 sum=0 for i in range(numb): for j in range(numb): if (i*j==numb): sum=sum+i sum=sum+j if sum&gt;numb: print("The value",numb,"is an abundant number.") elif sum&lt;numb: print("The value",numb,"is a deficient number.") else: print("The value",numb,"is a perfect number.") break return "perfect" </code></pre> <p>The code takes a number(numb) and classifies it as an abundant, deficient or perfect number. My output is screwy and only works for certain numbers. I assume it's indentation or the break that I am using incorrectly. Help would be greatly appreciated. </p>
3
2016-10-15T22:09:45Z
40,064,812
<p>I would highly recommend u to create a one function which creates the proper divisor of given N, and after that, the job would be easy.</p> <pre><code>def get_divs(n): return [i for i in range(1, n) if n % i == 0] def classify(num): divs_sum = sum(get_divs(num)) if divs_sum &gt; num: print('{} is abundant number'.format(num)) elif divs_sum &lt; num: print('{} is deficient number'.format(num)) elif divs_sum == num: print('{} is perfect number'.format(num)) </code></pre>
2
2016-10-15T22:17:30Z
[ "python", "for-loop", "indentation", "break" ]
Python abundant, deficient, or perfect number
40,064,750
<pre><code>def classify(numb): i=1 j=1 sum=0 for i in range(numb): for j in range(numb): if (i*j==numb): sum=sum+i sum=sum+j if sum&gt;numb: print("The value",numb,"is an abundant number.") elif sum&lt;numb: print("The value",numb,"is a deficient number.") else: print("The value",numb,"is a perfect number.") break return "perfect" </code></pre> <p>The code takes a number(numb) and classifies it as an abundant, deficient or perfect number. My output is screwy and only works for certain numbers. I assume it's indentation or the break that I am using incorrectly. Help would be greatly appreciated. </p>
3
2016-10-15T22:09:45Z
40,065,111
<p>Somewhere you are misinterpreting something. As is you are printing what kind the number is, as many times as the value of the number. I might be missing something but anyway. </p> <p>The sum of proper divisors can be found naively through using modulo </p> <pre><code>def classify1(num): div_sum = sum(x for x in range(1, num) if num % x == 0) kind = "" if div_sum &lt; num: kind = "deficient" elif div_sum &gt; num: kind = "abundant" else: kind = "perfect" print("{} is a {} number".format(num, kind)) </code></pre> <hr> <p>but for big numbers or maybe numbers this will take a long time. So I welcome you to the divisor function. I just dump it and explain it. </p> <pre><code>def mark(li: list, x: int): for i in range(2*x, len(li), x): li[i] = False return li def sieve(lim: int): li = [True] * lim li[0] = li[1] = 0 for x in range(2, int(lim ** 0.5) + 1): if x: li = mark(li, x) return [2]+[x for x in range(3, lim, 2) if li[x]] def factor(num): divs = list() for prime in primes: if prime * prime &gt; num: if num &gt; 1: divs += [num] return divs while num % prime == 0: num //= prime divs += [prime] else: return divs def divisors_sum(num): """ Function that implements a geometric series to generate the sum of the divisors, but it is not the divisor function since removing original number. """ divs = factor(num) div_sum, s = 1, 0 for div in set(divs): s = 0 for exponent in range(0, divs.count(div) + 1): s += div ** exponent div_sum *= s else: return div_sum - num primes = sieve(limit) </code></pre> <p>but.. there is not much explaining due, first prime factor the numbers, and use the divisor function to get the proper divisors sum. That is it. However the speed up is ridiculously much fast. This might seem to over kill the problem but it is just that much more cooler and faster. </p>
0
2016-10-15T23:01:29Z
[ "python", "for-loop", "indentation", "break" ]
Get list of variables from Jinja2 template (parent and child)
40,064,867
<p>I'm trying to get a list of variables from a Jinja2 template.</p> <p>test1.j2:</p> <pre><code>some-non-relevant-content {{var1}} {% include 'test2.j2' %} </code></pre> <p>test2.j2:</p> <pre><code>another-text {{var2}} </code></pre> <p>I can get variables from test1 easily:</p> <pre><code>env = Environment(loader=FileSystemLoader(searchpath='./Templates')) src_t = env.loader.get_source(env, 'test1.j2')[0] parsed_t = env.parse(source=src_t) t_vars = meta.find_undeclared_variables(ast=parsed_t) </code></pre> <p>Problem is, I can only get variables from the parent template with get_source. Obviously, I can not feed class template object to parse method as well.</p> <p>Is there any way to build the full list? {'var1', 'var2'} in my case. Ideally by using Jinja2 API. Minimum custom code.</p>
0
2016-10-15T22:25:43Z
40,069,288
<p>Found a way to code that without a big pain. meta.find_referenced_templates helps to load all child templates when applied recursively. When done, it's trivial to get variables from all templates in a single list.</p>
0
2016-10-16T10:31:39Z
[ "python", "python-3.x", "jinja2" ]
Splitting strings unhashable type
40,064,881
<p>I have never split strings in Python before so I am not too sure what is going wrong here. </p> <pre><code>import pyowm owm = pyowm.OWM('####################') location = owm.weather_at_place('Leicester, uk') weather = location.get_weather() weather.get_temperature('celsius') temperature = weather.get_temperature('celsius') print(temperature[5:10]) </code></pre> <p>Error received </p> <pre><code>sudo python weather.py Traceback (most recent call last): File "weather.py", line 10, in &lt;module&gt; print(temperature[5:10]) TypeError: unhashable type </code></pre>
1
2016-10-15T22:27:55Z
40,064,912
<p><code>get_temperature</code> returns a dictionary, which you're then trying to index with a <code>slice</code> object, which is not hashable. e.g.</p> <pre><code>&gt;&gt;&gt; hash(slice(5, 10)) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: unhashable type </code></pre> <p>To get the temperature, you need to get it from the dictionary like this:</p> <pre><code>temperature['temp'] </code></pre>
2
2016-10-15T22:31:56Z
[ "python", "python-3.x" ]
python different print output for <class 'str'> and <class 'str'>
40,064,939
<p>This is probably a basic question for most, yet it's not making sense to me.</p> <p>When I try to print a str in the interpreter i'm getting different results back even though when I <code>type</code> them they are the same.</p> <p>Here's the whole thing -></p> <pre><code>&gt;&gt;&gt; print(abs.__doc__) abs(number) -&gt; number Return the absolute value of the argument. &gt;&gt;&gt; type(abs.__doc__) &lt;class 'str'&gt; &gt;&gt;&gt; f_name = input('Enter a builtin: ') Enter a builtin: abs &gt;&gt;&gt; print(f_name + '.__doc__') abs.__doc__ &gt;&gt;&gt; type(f_name + '.__doc__') &lt;class 'str'&gt; </code></pre> <p>It would seem to me that they should return the same thing, the <code>pydoc</code> of <code>abs</code>.</p> <p>Do I have to make a special call to make this work?</p>
-1
2016-10-15T22:34:52Z
40,064,953
<p>You're confusing a string, with an expression, <code>'abs.__doc__'</code> (string) is different from <code>abs.__doc__</code> (expression), you can evaluate the string as an expression with the <code>exec</code> function (Which you most probably shouldn't do unless you know what you're doing)</p>
0
2016-10-15T22:36:34Z
[ "python" ]
Working with strings in Python: Formatting the information in a very specific way
40,064,997
<p>OBS: I am working on Python 3.5.2 and I use the standard Shell and IDLE</p> <p>Hi everyone, I think one of the most difficult tasks I have when programming with python is dealing with strings. Is there someone who can help?</p> <p>One of the problems I face frequently is transforming the string so I can use it properly. For instance:</p> <pre><code>#consider I have the following string I want to work with: </code></pre> <p><strong><code>my_input = 'insert 3 ["psyduck", 30]!!!insert 10 ["a nice day at the beach", 100]!!!find 3!!!find 10'</code></strong></p> <p>How can I transform this string in a way that, with the results, I would be able to do the following:</p> <p><em>1 - Separate the following substrings into variables like this:</em></p> <pre><code>command = 'insert' node = '3' #or the int 3 list = '["psyduck", 30]' </code></pre> <p><em>2 - Or any other solution that will somehow enable me to do this in the end:</em></p> <pre><code>listOfCommands = [['insert', '3', '["psyduck", 30]'], ['insert', '10', '["a nice day at the beach", 100]'], ['find', '3'], ['find', '10']] </code></pre> <p>I need this list in order to do the following:</p> <pre><code>for entry in listOfCommands: if entry[0] == 'insert': #I will execute a part of the program elif entry[0] == 'update': #execute something else elif entry[0] == 'find': #execute something else </code></pre> <p>The problem is that I do not know exaclty what is going to appear (the number of commands or the size of the information I will have to add) in the input. I just know that it will always obey these exact formats: <strong>[A command, a 'node' where I have to store the information or update it, the information I have to store or update]</strong> or <strong>[A command, a 'node' I have to find or delete]</strong> and the blocks will be separated by '!!!'</p> <p>I can work my way around the main program but in order to be able to make it run properly, I need to have this input formatted in this really specific way.</p>
1
2016-10-15T22:41:56Z
40,065,033
<p>Maybe something like this will work:</p> <pre><code>commands = my_input.split('!!!') my_commands = [c.split(' ', 2) for c in commands] </code></pre> <p>The second argument of the <code>split</code> methods tells it how many times you want it to split the string.</p>
3
2016-10-15T22:48:26Z
[ "python", "string", "python-3.x" ]
Regex taking too long in python
40,065,108
<p>I have used regex101 to test my regex and it works fine.What i am trying to is to detect these patterns</p> <ol> <li>section 1.2 random 2</li> <li>1.2 random 2</li> <li>1.2. random 2</li> <li>random 2</li> <li>random 2.</li> </ol> <p>But its just random it shouldn't match if the string is like that</p> <ol> <li>random</li> </ol> <p>My regex is this.</p> <pre><code> m = re.match(r"^(((section)\s*|(\d+\.)|\d+|(\d+\.\d+)|[a-zA-z\s]|[a-zA-z\.\s])+((\d+\.$)|\d+$|(\d+\.\d+$)))","random random random random random",flags = re.I) </code></pre> <p>If i give in a long string it gets stuck.Any ideas?</p>
2
2016-10-15T23:00:58Z
40,065,276
<p>After some simplification, this regular expression meets the requirements stated above and reproduced in the test cases below.</p> <pre><code>import re regex = r'(?:section)*\s*(?:[0-9.])*\s*random\s+(?!random)(?:[0-9.])*' strings = [ "random random random random random", "section 1.2 random 2", "1.2 random 2", "1.2. random 2", "random 2", "random 2.", "random", ] for string in strings: m = re.match(regex, string, flags = re.I) if m: print "match on", string else: print "non match on", string </code></pre> <p>which gives an output of:</p> <pre><code>non match on random random random random random match on section 1.2 random 2 match on 1.2 random 2 match on 1.2. random 2 match on random 2 match on random 2. non match on random </code></pre> <p>See it in action at: <a href="https://eval.in/661183" rel="nofollow">https://eval.in/661183</a></p>
1
2016-10-15T23:29:08Z
[ "python", "regex" ]
check user security for modifying objects
40,065,155
<p>I am thinking about security implementation for my python web app. For example I have user and profiles. Each user can edit his profile by sending POST at /profile/user_id</p> <p>On every request i can get session user_id and compare it with profile.user_id if they not same - raise SecurityException().</p> <p>But I also can do it another more common way: generate for each profile </p> <pre><code>secret = hash(profile_data+secret_key) </code></pre> <p>and render for auth. users links like this:</p> <pre><code>/profile/4?key=secret </code></pre> <p>So idea is to generate secret key based on editable object data and check this key on server side. If user don't know secret key it can't get links to edit other profile, and so can't modify them.</p> <p>How this method of protection called? Has it any problems in comparsion with session based user_id check?</p>
0
2016-10-15T23:09:11Z
40,069,274
<blockquote> <p>/profile/4?key=secret</p> </blockquote> <p>Practical issues:</p> <ul> <li>it's generally a bad idea to put a secret in a URL. URLs leak easily through logs, history, referrers etc. Also it breaks navigation. It's better to put the secret in a cookie or POST data.</li> <li>you would typically include a time limit in the signed data, so tokens aren't valid forever</li> <li>you would typically include some kind of flag/counter/state on the user information and in the signed data, so that a user can update something (eg change password) to invalidate previously-issued tokens</li> <li>you also have to ensure that the lifecycle of signed data can't be longer than that of the token, eg that you can't delete user 4 and create a new user 4 for whom the token is still valid</li> <li>the hash you would use would be an HMAC using a server-side secret for the key</li> </ul> <p>Signed authentication tokens are typically used as an alternative to database-backed session storage, for performance or operational reasons. It's certainly possible to do sessions securely with signed tokens, but if you're already using stored sessions for other purposes anyway you don't have a lot to gain.</p>
2
2016-10-16T10:29:43Z
[ "python", "security", "web-applications" ]
Enumeration Program
40,065,285
<p>I'm in the process of creating a program that takes an IP address, performs an nmap scan, and takes the output and puts it in a text file. The scan works fine, but I can't seem to figure out why it's not writing anything to the text file.</p> <p>Here is what I have so far</p> <pre><code>if __name__ == "__main__": import socket import nmap import sys import io from libnmap.parser import NmapParser, NmapParserException from libnmap.process import NmapProcess from time import sleep from os import path #Program Banner if len(sys.argv) &lt;= 1: print( """ test """) sys.exit() #Grab IP Address as argument if len(sys.argv)==2: ip = sys.argv[1] print "\n[+] Reading IP Address" #Function - Pass IP to Nmap then start scanning print "\n[+] Passing " + ip + " to Nmap..." print("\n[+] Starting Nmap Scan\n") def nmap_scan(ip, options): parsed = None nmproc = NmapProcess(ip, options) rc = nmproc.run() if rc != 0: print("nmap scan failed: {0}".format(nmproc.stderr)) try: parsed = NmapParser.parse(nmproc.stdout) except NmapParserException as e: print("Exception raised while parsing scan: {0}".format(e.msg)) return parsed #Function - Display Nmap scan results def show_scan(nmap_report): for host in nmap_report.hosts: if len(host.hostnames): tmp_host = host.hostnames.pop() else: tmp_host = host.address print("Host is [ %s ]\n" % str.upper(host.status)) print(" PORT STATE SERVICE") for serv in host.services: pserv = "{0:&gt;5s}/{1:3s} {2:12s} {3}".format( str(serv.port), serv.protocol, serv.state, serv.service) if len(serv.banner): pserv += " ({0})".format(serv.banner) print(pserv) #Function - Define output text file name &amp; write to file def createFile(dest): name = "Enumerator-Results.txt" if not(path.isfile(dest+name)): f = open(dest+name,"a+") f.write(show_scan(report)) f.close() if __name__ == "__main__": report = nmap_scan(ip, "-sV") if report: destination = "/root/Desktop/" createFile(destination) show_scan(report) print "\nReport Complete!" else: print("No results returned") </code></pre>
0
2016-10-15T23:30:38Z
40,065,306
<p>You're using print statements in your show_scan() function. Instead try passing the file reference to show_scan() and replacing the print() calls with f.write() calls. This would save to file everything you're currently printing to the terminal.</p> <p>Alternatively you could just change your code so that the show_scan is separate from the f.write().</p> <p>ie change</p> <pre><code>f.write(show_scan(report)) </code></pre> <p>to</p> <pre><code>f.write(report) </code></pre> <p>It depends on whether you want to save the raw output or what you're printing to the screen.</p> <p>Also you will need to pass the reference of the report to createFile so that it has the report to print ie</p> <pre><code>createFile(destination, report) </code></pre> <p>Just make sure you are always calling f.write() with a string as its parameter.</p> <pre><code>#Function - Define output text file name &amp; write to file def createFile(dest, report): name = "Enumerator-Results.txt" if not(path.isfile(dest+name)): f = open(dest+name,"a+") f.write(report) f.close() if __name__ == "__main__": report = nmap_scan(ip, "-sV") if report: destination = "/root/Desktop/" createFile(destination, report) show_scan(report) print "\nReport Complete!" else: print("No results returned") </code></pre>
0
2016-10-15T23:34:38Z
[ "python", "text-files", "nmap" ]
UnsupportedOperationException: Cannot evalute expression: .. when adding new column withColumn() and udf()
40,065,302
<p>So what I am trying to do is simply to convert fields: <code>year, month, day, hour, minute</code> (which are of type integer as seen below) into a string type.</p> <p>So I have a dataframe df_src of type :</p> <pre><code>&lt;class 'pyspark.sql.dataframe.DataFrame'&gt; </code></pre> <p>and here is its schema: </p> <pre><code>root |-- src_ip: string (nullable = true) |-- year: integer (nullable = true) |-- month: integer (nullable = true) |-- day: integer (nullable = true) |-- hour: integer (nullable = true) |-- minute: integer (nullable = true) </code></pre> <p>I also declared a function earlier : </p> <pre><code>def parse_df_to_string(year, month, day, hour=0, minute=0): second = 0 return "{0:04d}-{1:02d}-{2:02d} {3:02d}:{4:02d}:{5:02d}".format(year, month, day, hour, minute, second) </code></pre> <p>And I also did a test and it works like a charm : </p> <pre><code>print parse_df_to_string(2016, 10, 15, 21) print type(parse_df_to_string(2016, 10, 15, 21)) 2016-10-15 21:00:00 &lt;type 'str'&gt; </code></pre> <p>so I also did something similar as in spark api with udf :</p> <pre><code>from pyspark.sql.functions import udf u_parse_df_to_string = udf(parse_df_to_string) </code></pre> <p>where finally this request :</p> <pre><code>df_src.select('*', u_parse_df_to_string(df_src['year'], df_src['month'], df_src['day'], df_src['hour'], df_src['minute']) ).show() </code></pre> <p>would cause : </p> <pre><code>--------------------------------------------------------------------------- Py4JJavaError Traceback (most recent call last) &lt;ipython-input-126-770b587e10e6&gt; in &lt;module&gt;() 25 # Could not make this part wor.. 26 df_src.select('*', ---&gt; 27 u_parse_df_to_string(df_src['year'], df_src['month'], df_src['day'], df_src['hour'], df_src['minute']) 28 ).show() /opt/spark-2.0.0-bin-hadoop2.7/python/pyspark/sql/dataframe.pyc in show(self, n, truncate) 285 +---+-----+ 286 """ --&gt; 287 print(self._jdf.showString(n, truncate)) 288 289 def __repr__(self): /opt/spark-2.0.0-bin-hadoop2.7/python/lib/py4j-0.10.1-src.zip/py4j/java_gateway.py in __call__(self, *args) 931 answer = self.gateway_client.send_command(command) 932 return_value = get_return_value( --&gt; 933 answer, self.gateway_client, self.target_id, self.name) 934 935 for temp_arg in temp_args: /opt/spark-2.0.0-bin-hadoop2.7/python/pyspark/sql/utils.pyc in deco(*a, **kw) 61 def deco(*a, **kw): 62 try: ---&gt; 63 return f(*a, **kw) 64 except py4j.protocol.Py4JJavaError as e: 65 s = e.java_exception.toString() ... Py4JJavaError: An error occurred while calling o5074.showString. : java.lang.UnsupportedOperationException: Cannot evaluate expression: parse_df_to_string(input[1, int, true], input[2, int, true], input[3, int, true], input[4, int, true], input[5, int, true]) at org.apache.spark.sql.catalyst.expressions.Unevaluable$class.doGenCode(Expression.scala:224) at org.apache.spark.sql.execution.python.PythonUDF.doGenCode(PythonUDF.scala:27) at org.apache.spark.sql.catalyst.expressions.Expression$$anonfun$genCode$2.apply(Expression.scala:104) at org.apache.spark.sql.catalyst.expressions.Expression$$anonfun$genCode$2.apply(Expression.scala:101) at scala.Option.getOrElse(Option.scala:121) at org.apache.spark.sql.catalyst.expressions.Expression.genCode(Expression.scala:101) at org.apache.spark.sql.catalyst.expressions.codegen.CodegenContext$$anonfun$generateExpressions$1.apply(CodeGenerator.scala:740) at org.apache.spark.sql.catalyst.expressions.codegen.CodegenContext$$anonfun$generateExpressions$1.apply(CodeGenerator.scala:740) </code></pre> <p>...</p> <p>I tried many things, I tried to call the method with only one parameter&amp;argument...but did not help.</p> <p>One way it did work though is by creating a new dataframe with a new column as follow :</p> <pre><code>df_src_grp_hr_d = df_src.select('*', concat( col("year"), lit("-"), col("month"), lit("-"), col("day"), lit(" "), col("hour"), lit(":0")).alias('time'))` </code></pre> <p>where after that I could cast the column to timestamp : </p> <pre><code>df_src_grp_hr_to_timestamp = df_src_grp_hr_d.select( df_src_grp_hr_d['src_ip'], df_src_grp_hr_d['year'], df_src_grp_hr_d['month'], df_src_grp_hr_d['day'], df_src_grp_hr_d['hour'], df_src_grp_hr_d['time'].cast('timestamp')) </code></pre>
0
2016-10-15T23:34:10Z
40,077,911
<p>allright..I think I understand the problem...The cause is because my dataFrame just had a lot of data loaded in memory causing <code>show()</code> action to fail.</p> <p>The way I realize it is that what is causing the exception : </p> <pre><code>Py4JJavaError: An error occurred while calling o2108.showString. : java.lang.UnsupportedOperationException: Cannot evaluate expression: </code></pre> <p>is really the <code>df.show()</code> action.</p> <p>I could confirm that by executing the code snippet from : <a href="https://stackoverflow.com/questions/38080748/convert-pyspark-string-to-date-format#38081786">Convert pyspark string to date format</a></p> <pre><code>from datetime import datetime from pyspark.sql.functions import col,udf, unix_timestamp from pyspark.sql.types import DateType # Creation of a dummy dataframe: df1 = sqlContext.createDataFrame([("11/25/1991","11/24/1991","11/30/1991"), ("11/25/1391","11/24/1992","11/30/1992")], schema=['first', 'second', 'third']) # Setting an user define function: # This function converts the string cell into a date: func = udf (lambda x: datetime.strptime(x, '%M/%d/%Y'), DateType()) df = df1.withColumn('test', func(col('first'))) df.show() df.printSchema() </code></pre> <p>which worked! But it still did not work with my dataFrame <code>df_src</code>.</p> <p>The <strong>cause is because I am loading a lot a lot of data in memory from my database server (like over 8-9 millions of rows) it seems that spark is unable to perform the execution within udf when <code>.show()</code> (which displays 20 entries by default) of the results loaded in a dataFrame.</strong></p> <p>Even if show(n=1) is called, same exception would be thrown.</p> <p>But if printSchema() is called, you will see that the new column is effectively added.</p> <p>One way to see if the new column is added it would be simply to call the action <code>print dataFrame.take(10)</code> instead.</p> <p>Finally, one way to make it work is to affect a new dataframe and not call <code>.show()</code> when calling udf in a select() as : </p> <pre><code>df_to_string = df_src.select('*', u_parse_df_to_string(df_src['year'], df_src['month'], df_src['day'], df_src['hour'], df_src['minute']) ) </code></pre> <p>Then cache it : </p> <pre><code>df_to_string.cache </code></pre> <p>Now <code>.show()</code> can be called with no issues : </p> <pre><code>df_to_string.show() </code></pre>
0
2016-10-17T03:06:10Z
[ "python", "apache-spark", "pyspark" ]
Creating an array of tensors in tensorflow?
40,065,313
<p>Suppose I have two tensor variables each of size 2x4:</p> <pre><code>v1 = tf.logical_and(a1, b1) v2 = tf.logical_and(a2, b2) </code></pre> <p>Instead, I want to store these in an array called <code>v</code> which is of size 2x2x4. How do I do this in Tensorflow? The idea would be something like this:</p> <pre><code>for i in range(2): v[i] = tf.logical_and(a[i],b[i]) </code></pre> <p>How do I initialize <code>v</code>? I tried initializing <code>v</code> as a numpy array which did not work. I also tried initializing it as a tensorflow variable, ie. <code>tf.Variable(tf.zeros([2]))</code> but that does not work either.</p> <p>Note, <code>a</code> and <code>b</code> are dynamic inputs, ie. they are <code>tf.placeholder</code> variables.</p>
0
2016-10-15T23:36:22Z
40,065,373
<p>tf.pack() is probably what you are looking for.</p>
1
2016-10-15T23:45:09Z
[ "python", "arrays", "numpy", "tensorflow" ]
How to include git dependencies in setup.py for pip installation
40,065,321
<p>I need to include Python packages available via public Github repositories along with my Python (2.7) package. My package should be installable via <code>pip</code> using <code>setup.py</code>.</p> <p>So far, this could be done using <code>dependency_links</code> in the <code>setup.py</code> file:</p> <pre class="lang-py prettyprint-override"><code>setuptools.setup( name="my_package", version="1.0", install_requires=[ "other_package==1.2" ], dependency_links=[ "https://github.com/user/other_package/tarball/master#egg=other_package-1.2" ] ) </code></pre> <p>This still works when the package gets installed with the <code>--process-dependency-links</code> flag, but the <code>dependency_links</code> functionality seems to be deprecated, since:</p> <pre class="lang-none prettyprint-override"><code>pip install git+https://github.com/user/my_package@master#egg=my_package-1.0 --process-dependency-links </code></pre> <p>gives me the following warning:</p> <pre class="lang-none prettyprint-override"><code>DEPRECATION: Dependency Links processing has been deprecated and will be removed in a future release. </code></pre> <p>Is there an alternative way to include <code>git</code> dependencies in the <code>setup.py</code> file with support for pip installation?</p> <p>Edit (10/17/2016) to clarify my use case:</p> <p>Let's say I find a bug in <code>other_package</code>. I fork the respective repo on Github, fix the bug and make a pull request. My pull request doesn't get immediately accepted (or never will be because the package is no longer actively maintained). I would like to distribute <code>my_package</code> together with my fork of <code>other_package</code> and want users to be able to pip install <code>my_package</code> without any further knowledge about the details of this requirement and without having to provide any additional flags upon installation. Users of <code>my_package</code> should further be able to include <code>my_package</code> as a requirement in their own custom packages.</p> <p>How can this be achieved bearing compatibly with different modes of installation (wheels, eggs, develop, ...) in mind?</p>
2
2016-10-15T23:36:58Z
40,065,404
<p>I always create a <code>requirements.txt</code> which contains all of my dependencies which can then be installed using <code>pip install -r requirements.txt</code>. A usual <code>requirements.txt</code> looks like this (this is just an example):</p> <pre><code>pytz==2016.4 six==1.10.0 SQLAlchemy==1.0.13 watchdog==0.8.3 Werkzeug==0.11.10 </code></pre> <p>If you want to add a Git dependency (e.g. from Github), add a line like this to your <code>requirements.txt</code>:</p> <pre><code>git+https://github.com/user/project.git@branch#egg=eggname </code></pre> <p>Replace the url with your required project, <code>branch</code> with the desired Git branch (or tag, which should also work) and <code>eggname</code> with the name of the directory where the dependency should be installed to at <code>.../python3.x/site-packages/eggname</code>.</p> <p>My <code>setup.py</code> looks like this:</p> <pre><code>#!/usr/bin/env python from pip.req import parse_requirements from setuptools import setup requirements = parse_requirements('./requirements.txt', session=False) setup( name='myproject', # ... # Stuff like version, author, packages, include_package_data, # entry_points, test_suite, ... # ... install_requires=[str(requirement.req) for requirement in requirements], ) </code></pre> <p>I am using Python >= 3.4, btw.</p>
0
2016-10-15T23:50:14Z
[ "python", "git", "pip", "setup.py" ]
PiCameraValueError: Incorrect buffer length for resolution 1920x1080
40,065,328
<p>This is my code to detect circle/balls. I want to detect soccer ball from Pi camera. (soccer ball could be in any color.) I am having trouble with some PiCameraValueError. What is wrong with this code. I am using Raspberry Pi 2, Python2, and OpenCV.</p> <pre><code>from picamera.array import PiRGBArray from picamera import PiCamera import time import cv2 import sys import imutils import cv2.cv as cv # initialize the camera and grab a reference to the raw camera capture camera = PiCamera() rawCapture = PiRGBArray(camera) # capture frames from the camera for frame in camera.capture_continuous(rawCapture, format="bgr"): # grab the raw NumPy array representing the image, then initialize the timestamp # and occupied/unoccupied text image = frame.array img = cv2.medianBlur(image, 5) imgg = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY) cimg = cv2.cvtColor(imgg, cv2.COLOR_GRAY2BGR) imgg = cv2.blur(imgg, (3,3)) #imgg = cv2.dilate(imgg, np.ones((5, 5))) #imgg = cv2.GaussianBlur(imgg,(5,5),0) circles = cv2.HoughCircles(imgg, cv.CV_HOUGH_GRADIENT, 1, 20, param1=100, param2=40, minRadius=5, maxRadius=90) cv2.imshow("cimg", imgg) key = cv2.waitKey(1) if key &amp; 0xFF == ord('q'): break if circles is None: continue print circles #circles = np.uint16(np.around(circles)) for i in circles[0,:]: cv2.circle(cimg,(i[0],i[1]),i[2],(0,255,0),1) # draw the outer circle #cv2.circle(cimg,(i[0],i[1]),2,(0,0,255),3) # draw the center of the circle cv2.imshow("Filtered", cimg) cv2.destroyWindow("cimg") cv2.destroyAllWindows() </code></pre>
1
2016-10-15T23:38:13Z
40,066,149
<p>As explained <a href="https://github.com/waveform80/picamera" rel="nofollow">here</a>,</p> <blockquote> <p>the <code>PiCameraValueError</code> is a secondary exception raised in response to the KeyboardInterrupt exception. This is quite normal and not a bug (it's more a consequence of how generic the output mechanism is in picamera), but it is difficult to detect and respond to in Python 2 (the usual method there would probably be to catch the PiCameraValueError as well in whatever loop your main script runs). Under Python 3, <a href="http://stackoverflow.com/questions/16414744/python-exception-chaining">exception chaining</a> is implemented so you could potentially look back through the stack of exceptions to find the KeyboardInterrupt one.</p> </blockquote> <p>What you need to do is clear the stream between captures. The <a href="http://picamera.readthedocs.org/en/release-1.7/array.html#picamera.array.PiRGBArray" rel="nofollow">PiRGBArray</a> docs cover doing this with truncate function.</p> <p>Here is an example from, <a href="http://stackoverflow.com/questions/29938829/python-face-detection-raspberry-pi-with-picamera">python face detection raspberry pi with picamera</a></p> <pre><code>import io import time import picamera with picamera.PiCamera() as camera: stream = io.BytesIO() for foo in camera.capture_continuous(stream, format='jpeg'): # YOURS: for frame in camera.capture_continuous(stream, format="bgr", use_video_port=True): # Truncate the stream to the current position (in case # prior iterations output a longer image) stream.truncate() stream.seek(0) if process(stream): break </code></pre>
0
2016-10-16T02:15:47Z
[ "python", "opencv", "raspberry-pi", "detection", "raspbian" ]
Python using custom color in plot
40,065,378
<p>I'm having a problem that (I think) should have a fairly simple solution. I'm still a relative novice in Python, so apologies if I'm doing something obviously wrong. I'm just trying to create a simple plot with multiple lines, where each line is colored by its own specific, user-defined color. When I run the following code as a test for one of the colors it ends up giving me a blank plot. What am I missing here? Thank you very much!</p> <pre><code>import numpy as np import matplotlib.pyplot as plt from colour import Color dbz53 = Color('#DD3044') *a bunch of arrays of data, two of which are called x and mpt1* fig, ax = plt.subplots() ax.plot(x, mpt1, color='dbz53', label='53 dBz') ax.set_yscale('log') ax.set_xlabel('Diameter (mm)') ax.set_ylabel('$N(D) (m^-4)$') ax.set_title('N(D) vs. D') #ax.legend(loc='upper right') plt.show() </code></pre>
2
2016-10-15T23:45:44Z
40,065,407
<p>In the <code>plot</code> command, you could enter Hex colours. A much more simple way to beautify your plot would be to simply use matplotlib styles. For instance, before any plot function, just write <code>plt.style.use('ggplot')</code></p>
0
2016-10-15T23:51:16Z
[ "python", "numpy", "matplotlib", "colors" ]
Python using custom color in plot
40,065,378
<p>I'm having a problem that (I think) should have a fairly simple solution. I'm still a relative novice in Python, so apologies if I'm doing something obviously wrong. I'm just trying to create a simple plot with multiple lines, where each line is colored by its own specific, user-defined color. When I run the following code as a test for one of the colors it ends up giving me a blank plot. What am I missing here? Thank you very much!</p> <pre><code>import numpy as np import matplotlib.pyplot as plt from colour import Color dbz53 = Color('#DD3044') *a bunch of arrays of data, two of which are called x and mpt1* fig, ax = plt.subplots() ax.plot(x, mpt1, color='dbz53', label='53 dBz') ax.set_yscale('log') ax.set_xlabel('Diameter (mm)') ax.set_ylabel('$N(D) (m^-4)$') ax.set_title('N(D) vs. D') #ax.legend(loc='upper right') plt.show() </code></pre>
2
2016-10-15T23:45:44Z
40,072,897
<p>The statement <br>ax.plot(x, mpt1, color='dbz53', label='53 dBz') <br>is wrong with quoted dbz53. Where python treated it as a string of unknown rgb value. <br>You can simply put color='#DD3044', and it will work. <br>Or you can try <br>color=dbz53.get_hex() <br>without quote if you want to use the colour module you imported.</p>
0
2016-10-16T16:57:19Z
[ "python", "numpy", "matplotlib", "colors" ]
Finding and replacing a value in a Python dictionary
40,065,381
<p>I'm a complete newbie to stackoverflow, so please excuse me if I end up posting this in the wrong place (or any other newbie-related mitakes! Thanks!).</p> <p>My question pertains to Python 3.x, where I am trying to basically access a value in a very small dictionary (3 keys, 1 value each). I have searched high and low on the web (and on here), but cannot seem to find anything pertaining to replacing a value in a dictionary. I have found the "replace" function, but does not seem to work for dictionaries.</p> <p>So, here is my dictionary:</p> <pre><code>a1 = {"Green": "Tree", "Red": "Rose", "Yellow": "Sunflower"} </code></pre> <p>How would I go about querying the value "Rose" to replace it with "Tulip," for example?</p> <p>Any help would be greatly appreciated, even if it is just to point me in the right direction!</p> <p>Thanks so much!</p>
-3
2016-10-15T23:46:06Z
40,065,439
<p>You first must find the key that has the value <code>"Rose"</code>:</p> <pre><code>for color, flower in a1.items(): if flower == "Rose": a1[color] = "Tulip" </code></pre>
0
2016-10-15T23:57:29Z
[ "python", "dictionary", "replace", "find" ]
Tensorflow: Converting a tenor [B, T, S] to list of B tensors shaped [T, S]
40,065,396
<p>Tensorflow: Converting a tenor [B, T, S] to list of B tensors shaped [T, S]. Where B, T, S are whole positive numbers ...</p> <p>How can I convert this? I can't do eval because no session is running at the time I want to do this.</p>
0
2016-10-15T23:49:10Z
40,065,428
<p>It sounds like you want tf.unpack()</p>
0
2016-10-15T23:55:58Z
[ "python", "tensorflow", "deep-learning", "lstm" ]
Google Maps API Python/R
40,065,448
<p>I am trying to use the google maps API for <a href="https://developers.google.com/maps/documentation/javascript/places#place_search_requests" rel="nofollow">nearby</a> search and ideally I'd use a <a href="https://developers.google.com/maps/documentation/javascript/reference#LatLngBounds" rel="nofollow">latlngBounds</a> object for my search. I have been using R but can do python as well and seem to run into the same issue. It's working fine with the point/radius but I'd like to set a bounding box if possible. It seems that for javascript you can input a latlngBounds object but maybe not if you're using the python or R api? Does anyone have any knowledge on if this is possible?</p> <p>Thanks!</p>
0
2016-10-15T23:58:48Z
40,075,423
<p>As you've alluded to, the Javascript API allows you to use a LatLngBounds object, however, the <a href="https://developers.google.com/places/web-service/search" rel="nofollow">web services API</a> does not.</p> <p>A couple of options I can suggest</p> <ol> <li><p>Write some Javascript and parse it yourself in R using something like <a href="https://cran.r-project.org/web/packages/V8/index.html" rel="nofollow"><code>library(V8)</code></a>, or your own <a href="https://cran.r-project.org/web/packages/htmlwidgets/index.html" rel="nofollow">html widget</a></p></li> <li><p>Also in R, use the development version of my <a href="https://github.com/SymbolixAU/googleway/blob/master/NEWS.md" rel="nofollow">googleway</a> package, and in particular the <code>google_palces()</code> function to do a <a href="https://developers.google.com/places/web-service/search" rel="nofollow">nearby serach</a>. </p></li> </ol> <hr> <pre><code>### to install the development version # devtools::install_github("SymbolixAU/googleway") library(googleway) ## you need an API key key &lt;- read.dcf("~/Documents/.googleAPI", fields = "GOOGLE_API_KEY") res &lt;- google_places(search_string = "cafe", location = c(-37.8203155,144.9800428), radius = 2000, key = key) # res$results$name # [1] "Café Vue" "Switch Board Cafe" "The Journal Cafe" # [4] "Krimper Cafe" "65 Degrees Cafe" "Basement Cafe" # [7] "Cafe Domain" "Druids Cafe" "Cafe Kinetic" # [10] "Paris End Cafe &amp; Catering Melbourne 20 Collins street" "Mothership Cafe" "THE J Walk Cafe" # [13] "Richmond Rush Cafe" "Bullrun café" "Crossroads Cafe" # [16] "Espresso Cafe Richmond" "8 Miles Cafe &amp; Convenience Store" "Cafe Bar Mile" # [19] "The Industrial Cafe" "Park Lane Cafe" </code></pre>
0
2016-10-16T21:00:55Z
[ "python", "google-maps" ]
Numpy repeat for 2d array
40,065,479
<p>Given two arrays, say </p> <pre><code>arr = array([10, 24, 24, 24, 1, 21, 1, 21, 0, 0], dtype=int32) rep = array([3, 2, 2, 0, 0, 0, 0, 0, 0, 0], dtype=int32) </code></pre> <p>np.repeat(arr, rep) returns </p> <pre><code>array([10, 10, 10, 24, 24, 24, 24], dtype=int32) </code></pre> <p>Is there any way to replicate this functionality for a set of 2D arrays?</p> <p>That is given </p> <pre><code>arr = array([[10, 24, 24, 24, 1, 21, 1, 21, 0, 0], [10, 24, 24, 1, 21, 1, 21, 32, 0, 0]], dtype=int32) rep = array([[3, 2, 2, 0, 0, 0, 0, 0, 0, 0], [2, 2, 2, 0, 0, 0, 0, 0, 0, 0]], dtype=int32) </code></pre> <p>is it possible to create a function which vectorizes?</p> <p>PS: The number of repeats in each row need not be the same. I'm padding each result row to ensure that they are of same size.</p> <pre><code>def repeat2d(arr, rep): # Find the max length of repetitions in all the rows. max_len = rep.sum(axis=-1).max() # Create a common array to hold all results. Since each repeated array will have # different sizes, some of them are padded with zero. ret_val = np.empty((arr.shape[0], maxlen)) for i in range(arr.shape[0]): # Repeated array will not have same num of cols as ret_val. temp = np.repeat(arr[i], rep[i]) ret_val[i,:temp.size] = temp return ret_val </code></pre> <p>I do know about np.vectorize and I know that it does not give any performance benefits over the normal version.</p>
5
2016-10-16T00:01:25Z
40,065,645
<p>So you have a different repeat array for each row? But the total number of repeats per row is the same?</p> <p>Just do the <code>repeat</code> on the flattened arrays, and reshape back to the correct number of rows.</p> <pre><code>In [529]: np.repeat(arr,rep.flat) Out[529]: array([10, 10, 10, 24, 24, 24, 24, 10, 10, 24, 24, 24, 24, 1]) In [530]: np.repeat(arr,rep.flat).reshape(2,-1) Out[530]: array([[10, 10, 10, 24, 24, 24, 24], [10, 10, 24, 24, 24, 24, 1]]) </code></pre> <p>If the repetitions per row vary, we have the problem of padding variable length rows. That's come up in other SO questions. I don't recall all the details, but I think the solution is along this line:</p> <p>Change <code>rep</code> so the numbers differ:</p> <pre><code>In [547]: rep Out[547]: array([[3, 2, 2, 0, 0, 0, 0, 0, 0, 0], [2, 2, 2, 1, 0, 2, 0, 0, 0, 0]]) In [548]: lens=rep.sum(axis=1) In [549]: lens Out[549]: array([7, 9]) In [550]: m=np.max(lens) In [551]: m Out[551]: 9 </code></pre> <p>create the target:</p> <pre><code>In [552]: res = np.zeros((arr.shape[0],m),arr.dtype) </code></pre> <p>create an indexing array - details need to be worked out:</p> <pre><code>In [553]: idx=np.r_[0:7,m:m+9] In [554]: idx Out[554]: array([ 0, 1, 2, 3, 4, 5, 6, 9, 10, 11, 12, 13, 14, 15, 16, 17]) </code></pre> <p>flat indexed assignment:</p> <pre><code>In [555]: res.flat[idx]=np.repeat(arr,rep.flat) In [556]: res Out[556]: array([[10, 10, 10, 24, 24, 24, 24, 0, 0], [10, 10, 24, 24, 24, 24, 1, 1, 1]]) </code></pre>
3
2016-10-16T00:34:37Z
[ "python", "arrays", "numpy", "vectorization" ]
Numpy repeat for 2d array
40,065,479
<p>Given two arrays, say </p> <pre><code>arr = array([10, 24, 24, 24, 1, 21, 1, 21, 0, 0], dtype=int32) rep = array([3, 2, 2, 0, 0, 0, 0, 0, 0, 0], dtype=int32) </code></pre> <p>np.repeat(arr, rep) returns </p> <pre><code>array([10, 10, 10, 24, 24, 24, 24], dtype=int32) </code></pre> <p>Is there any way to replicate this functionality for a set of 2D arrays?</p> <p>That is given </p> <pre><code>arr = array([[10, 24, 24, 24, 1, 21, 1, 21, 0, 0], [10, 24, 24, 1, 21, 1, 21, 32, 0, 0]], dtype=int32) rep = array([[3, 2, 2, 0, 0, 0, 0, 0, 0, 0], [2, 2, 2, 0, 0, 0, 0, 0, 0, 0]], dtype=int32) </code></pre> <p>is it possible to create a function which vectorizes?</p> <p>PS: The number of repeats in each row need not be the same. I'm padding each result row to ensure that they are of same size.</p> <pre><code>def repeat2d(arr, rep): # Find the max length of repetitions in all the rows. max_len = rep.sum(axis=-1).max() # Create a common array to hold all results. Since each repeated array will have # different sizes, some of them are padded with zero. ret_val = np.empty((arr.shape[0], maxlen)) for i in range(arr.shape[0]): # Repeated array will not have same num of cols as ret_val. temp = np.repeat(arr[i], rep[i]) ret_val[i,:temp.size] = temp return ret_val </code></pre> <p>I do know about np.vectorize and I know that it does not give any performance benefits over the normal version.</p>
5
2016-10-16T00:01:25Z
40,066,467
<p>Another solution similar to @hpaulj's solution:</p> <pre><code>def repeat2dvect(arr, rep): lens = rep.sum(axis=-1) maxlen = lens.max() ret_val = np.zeros((arr.shape[0], maxlen)) mask = (lens[:,None]&gt;np.arange(maxlen)) ret_val[mask] = np.repeat(arr.ravel(), rep.ravel()) return ret_val </code></pre> <p>Instead of storing indices, I'm creating a bool mask and using the mask to set the values.</p>
1
2016-10-16T03:17:33Z
[ "python", "arrays", "numpy", "vectorization" ]
Python - Removing 1 char from a series of nested lists
40,065,495
<p>I've solved the problem with the code below, but I'm trying to understand a better way to strip out the zeros at the end of the each string of numbers because they throw off the calculation. The solution I have seems heavy handed, is there a more elegant way to solve this without a for loop removing the 0s?</p> <h1>Coding Problem:</h1> <p>Determine the average of a series of numbers like this:</p> <blockquote> <p>97 143 3 149 1 181 195 76 0</p> <p>8042 4302 1273 3858 4019 8051 4831 7747 4887 768 6391 7817 2635 6203 0</p> <p>1783 218 154 360 409 929 1503 428 73 1505 1868 1625 64 1613 0</p> </blockquote> <pre><code>import sys inp = sys.stdin.readlines() lin = [] for i in inp[1:]: lin.append(map(int,i.split())) </code></pre> <p>/---Crux----</p> <pre><code>for r in lin: del r[-1] </code></pre> <p>/-------------</p> <pre><code>for n in lin: print int(round((sum(n) / float(len(n))))), </code></pre> <p>Any other critiques and constructive criticisms are appreciated.</p>
-1
2016-10-16T00:07:00Z
40,065,517
<p>As far getting the job done I think looks okay. Why not just do:</p> <pre><code>If r[-1] == 0: Del r[-1] </code></pre>
-1
2016-10-16T00:12:08Z
[ "python", "list" ]
Python - Removing 1 char from a series of nested lists
40,065,495
<p>I've solved the problem with the code below, but I'm trying to understand a better way to strip out the zeros at the end of the each string of numbers because they throw off the calculation. The solution I have seems heavy handed, is there a more elegant way to solve this without a for loop removing the 0s?</p> <h1>Coding Problem:</h1> <p>Determine the average of a series of numbers like this:</p> <blockquote> <p>97 143 3 149 1 181 195 76 0</p> <p>8042 4302 1273 3858 4019 8051 4831 7747 4887 768 6391 7817 2635 6203 0</p> <p>1783 218 154 360 409 929 1503 428 73 1505 1868 1625 64 1613 0</p> </blockquote> <pre><code>import sys inp = sys.stdin.readlines() lin = [] for i in inp[1:]: lin.append(map(int,i.split())) </code></pre> <p>/---Crux----</p> <pre><code>for r in lin: del r[-1] </code></pre> <p>/-------------</p> <pre><code>for n in lin: print int(round((sum(n) / float(len(n))))), </code></pre> <p>Any other critiques and constructive criticisms are appreciated.</p>
-1
2016-10-16T00:07:00Z
40,065,520
<p>You can do it all in one go using slicing and list comprehension:</p> <pre><code>lin = [map(int,i.split())[:-1] for i in inp[1:]] </code></pre>
0
2016-10-16T00:12:54Z
[ "python", "list" ]
Python - Removing 1 char from a series of nested lists
40,065,495
<p>I've solved the problem with the code below, but I'm trying to understand a better way to strip out the zeros at the end of the each string of numbers because they throw off the calculation. The solution I have seems heavy handed, is there a more elegant way to solve this without a for loop removing the 0s?</p> <h1>Coding Problem:</h1> <p>Determine the average of a series of numbers like this:</p> <blockquote> <p>97 143 3 149 1 181 195 76 0</p> <p>8042 4302 1273 3858 4019 8051 4831 7747 4887 768 6391 7817 2635 6203 0</p> <p>1783 218 154 360 409 929 1503 428 73 1505 1868 1625 64 1613 0</p> </blockquote> <pre><code>import sys inp = sys.stdin.readlines() lin = [] for i in inp[1:]: lin.append(map(int,i.split())) </code></pre> <p>/---Crux----</p> <pre><code>for r in lin: del r[-1] </code></pre> <p>/-------------</p> <pre><code>for n in lin: print int(round((sum(n) / float(len(n))))), </code></pre> <p>Any other critiques and constructive criticisms are appreciated.</p>
-1
2016-10-16T00:07:00Z
40,065,529
<p>Cant you just do:</p> <pre><code>lin=[] for line in sys.stdin: lin.append([float(e) for e in line.split()[:-1]]) </code></pre> <p>So that becomes a single line:</p> <pre><code>lin=[[float(e) for e in line.split()[:-1]] for line in sys.stdin] </code></pre> <p>Then your averages become:</p> <pre><code>avgs=[sum(e)/len(e) for e in lin] &gt;&gt;&gt; avgs [105.625, 5058.857142857143, 895.1428571428571] </code></pre>
-1
2016-10-16T00:14:10Z
[ "python", "list" ]
Connecting to a SQL db using python
40,065,615
<p>I currently have a python script that can connect to a mySQL db and execute queries. I wish to modify it so that I can connect to a different SQL db to run a separate query. I am having trouble doing this, running osx 10.11. This is my first question and I'm a newbie programmer so please take it easy on me...</p> <p>Here is the program i used to for mySQL</p> <pre><code>sf_username = "user" sf_password = "pass" sf_api_token = "token" sf_update = beatbox.PythonClient() password = str("%s%s" % (sf_password, sf_api_token)) sf_update.login(sf_username, password) t = Terminal() hub = [stuff] def FINAL_RUN(): cnx = alternate_modify(hub) cur = cnx.cursor() queryinput = """ SQL QUERY I WANT """ cur.execute(queryinput) rez = cur.fetchone() while rez is not None: write_to_sf(rez) rez = cur.fetchone() FINAL_RUN() </code></pre>
0
2016-10-16T00:29:33Z
40,069,734
<p>You can use a Python library called SQLAlchemy. It abstracts away the "low-level" operations you would do with a database (e.g. specifying queries manually).</p> <p>A tutorial for using SQLAlchemy can be found <a href="http://www.rmunn.com/sqlalchemy-tutorial/tutorial.html" rel="nofollow">here</a>.</p>
0
2016-10-16T11:29:51Z
[ "python", "mysql", "sql", "database" ]
Connecting to a SQL db using python
40,065,615
<p>I currently have a python script that can connect to a mySQL db and execute queries. I wish to modify it so that I can connect to a different SQL db to run a separate query. I am having trouble doing this, running osx 10.11. This is my first question and I'm a newbie programmer so please take it easy on me...</p> <p>Here is the program i used to for mySQL</p> <pre><code>sf_username = "user" sf_password = "pass" sf_api_token = "token" sf_update = beatbox.PythonClient() password = str("%s%s" % (sf_password, sf_api_token)) sf_update.login(sf_username, password) t = Terminal() hub = [stuff] def FINAL_RUN(): cnx = alternate_modify(hub) cur = cnx.cursor() queryinput = """ SQL QUERY I WANT """ cur.execute(queryinput) rez = cur.fetchone() while rez is not None: write_to_sf(rez) rez = cur.fetchone() FINAL_RUN() </code></pre>
0
2016-10-16T00:29:33Z
40,114,063
<p>I was able to get connected using SQL Alchemy--thank you. If anyone else tries, I think you'll need a ODBC driver per this page: </p> <p><a href="http://docs.sqlalchemy.org/en/latest/dialects/mssql.html" rel="nofollow">http://docs.sqlalchemy.org/en/latest/dialects/mssql.html</a></p> <p>Alternatively, pymssql is a nice tool. If you run into trouble installing like I did, there is a neat workaround here:</p> <p><a href="http://stackoverflow.com/questions/37771434/mac-pip-install-pymssql-error">mac - pip install pymssql error</a></p> <p>Thanks again</p>
0
2016-10-18T17:00:25Z
[ "python", "mysql", "sql", "database" ]
Python Pandas Concat "WHERE" a Condition is met
40,065,641
<p>How can I "concat" a specific column from many Python Pandas dataframes, WHERE another column in each of the many dataframes meets a certain condition (colloquially termed condition "X" here).</p> <p>In SQL this would be simple using JOIN clause with WHERE df2.Col2 = "X" and df3.Col2 = "X" and df4.col2 = "X"... etc (which can be run dynamically).</p> <p>In my case, I want to create a big dataframe with all the "Col1"s from each of the many dataframes, but only include the Col1 row values WHERE the corresponding Col2 row value is greater than "0.8". When this condition isn't met, the Col1 value should be "NaN".</p> <p>Any ideas would be most helpful! Thanks in advance!</p>
2
2016-10-16T00:33:21Z
40,068,065
<p>consider the <code>list</code> <code>dfs</code> of <code>pd.DataFrame</code>s</p> <pre><code>import pandas as pd import numpy as np np.random.seed([3,1415]) dfs = [pd.DataFrame(np.random.rand(10, 2), columns=['Col1', 'Col2']) for _ in range(5)] </code></pre> <p>I'll use <code>pd.concat</code> to join</p> <p><strong><em>raw concat</em></strong><br> stack values without regard to where it came from</p> <pre><code>pd.concat([d.Col1.loc[d.Col2.gt(.8)] for d in dfs], ignore_index=True) 0 0.850445 1 0.934829 2 0.879891 3 0.085823 4 0.739635 5 0.700566 6 0.542329 7 0.882029 8 0.496250 9 0.585309 10 0.883372 Name: Col1, dtype: float64 </code></pre> <p><strong><em>join with source information</em></strong><br> use the <code>keys</code> parameter</p> <pre><code>pd.concat([d.Col1.loc[d.Col2.gt(.8)] for d in dfs], keys=range(len(dfs))) 0 3 0.850445 5 0.934829 6 0.879891 1 1 0.085823 2 0.739635 7 0.700566 2 4 0.542329 3 3 0.882029 4 0.496250 8 0.585309 4 0 0.883372 Name: Col1, dtype: float64 </code></pre> <p><strong><em>another approach</em></strong><br> use <code>query</code></p> <pre><code>pd.concat([d.query('Col2 &gt; .8').Col1 for d in dfs], keys=range(len(dfs))) 0 3 0.850445 5 0.934829 6 0.879891 1 1 0.085823 2 0.739635 7 0.700566 2 4 0.542329 3 3 0.882029 4 0.496250 8 0.585309 4 0 0.883372 Name: Col1, dtype: float64 </code></pre>
2
2016-10-16T07:42:07Z
[ "python", "pandas", "join", "where", "concat" ]
TypeError: 'float' object is not subscriptable in 3d array
40,065,702
<p>guys I'm trying to write a function which get a 3-D array and check how many of its cells are empty. but i will got the following error</p> <pre><code>in checkpoint if m[i][j][0] == 0: TypeError: 'float' object is not subscriptable </code></pre> <p>my function is as following</p> <pre><code>def checkpoint(m, i, j): c = 0 if m[i][j][0] == 0: c += 1.0 if m[i][j][1] == 0: c += 1.0 if m[i][j][2] == 0: c += 1.0 if m[i][j][3] == 0: c += 1.0 return c </code></pre> <p>its from a large module that I'm working with here is the function that work with it </p> <pre><code>def check(m, size): flag = 2 for i in range(size): for j in range(size): print(i, j, "/n") c = checkpoint(m, i, j) s = summ(m, i, j) if c == 2: if s == 2 or -2: flag = 1.0 if m[i][j][0] == 0: if m[i][j][1] == 0: m[i][j][0] = m[i][j][1] = (-s/2) fix(m, i, j, 0, size) fix(m, i, j, 1, size) elif m[i][j][2] == 0: m[i][j][0] = m[i][j][2] = (-s/2) fix(m, i, j, 0, size) fix(m, i, j, 2, size) else: m[i][j][0] = m[i][j][3] = (-s/2) fix(m, i, j, 0, size) fix(m, i, j, 3, size) elif m[i][j][1] == 0: if m[i][j][2] == 0: m[i][j][1] = m[i][j][2] = (-s/2) fix(m, i, j, 1, size) fix(m, i, j, 2, size) elif m[i][j][3] == 0: m[i][j][1] = m[i][j][3] = (-s/2) fix(m, i, j, 1, size) fix(m, i, j, 3, size) else: m[i][j][2] = m[i][j][3] = (-s/2) if c == 3: flag = 1.0 if m[i][j][0] == 0: m[i][j][0] = -s elif m[i][j][1] == 0: m[i][j][1] = -s elif m[i][j][2] == 0: m[i][j][2] = -s else: m[i][j][3] = -s return m, flag </code></pre> <p>any comment would be appreciated</p> <p>update:</p> <p>i desperately run the function inside the module and i saw that there isn't any problem whit first iteration and second iteration of the i and j in check function. but after that will faced with the error.</p> <p>here is my output:<a href="https://i.stack.imgur.com/CV7xS.png" rel="nofollow">the output of the code that I'm trying to run</a></p> <p>as you can see it didn't have any problem in first iteration of the i in check function.<br> here is my fix function. it changes some other cells with respect to the arrow that cell that just changed.</p> <pre><code>def fix(m, i, j, k, size): ip = i - 1 jp = j - 1 iz = i + 1 jz = j + 1 if ip &lt; 0: ip = size - 1 if jp &lt; 0: jp = size - 1 if iz &gt; size - 1: iz = 0 if jz &gt; size - 1: jz = 0 kp = (k+2) % 4 if k == 0: m[i][jz][kp] = -1 * m[i][j][k] if k == 1: m[iz][j][kp] = -1 * m[i][j][k] if k == 2: m[i][jp][kp] = -1 * m[i][j][k] if k == 3: m[ip][j][kp] = -1 * m[i][j][k] return m </code></pre> <p>here you can find whole package: <a href="https://codeshare.io/dsT8l" rel="nofollow">my code</a></p>
0
2016-10-16T00:44:05Z
40,065,751
<p>That means m is not actually 3d array, the code is trying to do <code>[i]</code> or <code>[i][j]</code> or <code>[i][j][0]</code> on a <code>float</code>. </p> <p>"containers" are "scriptable" as described <a href="http://stackoverflow.com/questions/216972/in-python-what-does-it-mean-if-an-object-is-subscriptable-or-not">here</a></p>
0
2016-10-16T00:51:51Z
[ "python", "arrays", "python-3.x", "object", "typeerror" ]
Collecting Summary Statistics on Dataframe built by randomly sampling other dataframes
40,065,703
<p>My goal is to build a dataframe by randomly sampling from other dataframes, collecting summary statistics on the new dataframe, and then append those statistics to a list. Ideally, I can iterate through this process n number of times (e.g. bootstrap). </p> <pre><code>dfposlist = [OFdf, Firstdf, Seconddf, Thirddf, CFdf, RFdf, Cdf, SSdf] OFdf.head() playerID OPW POS salary 87 bondsba01 62.061290 OF 8541667 785 ramirma02 35.785630 OF 13050000 966 walkela01 30.644305 OF 6050000 859 sheffga01 29.090699 OF 9916667 357 gilesbr02 28.160054 OF 7666666 </code></pre> <p>All the dataframes in the list have the same headers. What I'm trying to do looks something like this:</p> <pre><code>teamdist = [] for df in dfposlist: frames = [df.sample(n=1)] team = pd.concat(frames) teamopw = team['OPW'].sum() teamsal = team['salary'].sum() teamplayers = team['playerID'].tolist() teamdic = {'Salary':teamsal, 'OPW':teamopw, 'Players':teamplayers} teamdist.append(teamdic) </code></pre> <p>The output I'm looking for is something like this:</p> <pre><code>teamdist = [{'Salary':4900000, 'OPW':78.452, 'Players':[bondsba01, etc, etc]}] </code></pre> <p>But for some reason all the sum actions like <code>teamopw = team['OPW'].sum()</code> do not work how I'd like, and just returns the elements in <code>team['OPW']</code></p> <pre><code>print(teamopw) 0.17118131814601256 38.10700006434629 1.5699939126695253 32.9068837019903 16.990760776263674 18.22428871113601 13.447706356730897 </code></pre> <p>Any advice on how to get this working? Thanks!</p> <p>Edit: Working solution as follows. Not sure if it is the most pythonic way, but it works. </p> <pre><code>teamdist = [] team = pd.concat([df.sample(n=1) for df in dfposlist]) teamopw = team[['OPW']].values.sum() teamsal = team[['salary']].values.sum() teamplayers = team['playerID'].tolist() teamdic = {'Salary':teamsal, 'OPW':teamopw, 'Players':teamplayers} teamdist.append(teamdic) </code></pre>
1
2016-10-16T00:44:07Z
40,067,759
<p>Here (with random data):</p> <pre><code>import pandas as pd import numpy as np dfposlist = dict(zip(range(10), [pd.DataFrame(np.random.randn(10, 5), columns=list('abcde')) for i in range(10)])) for df in dfposlist.values(): df['f'] = list('qrstuvwxyz') teamdist = [] team = pd.concat([df.sample(n=1) for df in dfposlist.values()]) print(team.info()) teamdic = team[['a', 'c', 'e']].sum().to_dict() teamdic['f'] = team['f'].tolist() teamdist.append(teamdic) print(teamdist) # Output: ## team.info(): &lt;class 'pandas.core.frame.DataFrame'&gt; Int64Index: 10 entries, 1 to 6 Data columns (total 6 columns): a 10 non-null float64 b 10 non-null float64 c 10 non-null float64 d 10 non-null float64 e 10 non-null float64 f 10 non-null object dtypes: float64(5), object(1) memory usage: 560.0+ bytes None ## teamdist: [{'a': -3.5380097363724601, 'c': 2.0951152809401776, 'e': 3.1439230427971863, 'f': ['r', 'w', 'z', 'v', 'x', 'q', 't', 'q', 'v', 'w']}] </code></pre>
2
2016-10-16T07:00:57Z
[ "python", "loops", "pandas", "dictionary" ]
Python Import Dependency
40,065,715
<p>I know this question has been asked many times, but even after I tried many SO suggestions, I still cannot get it right. So, posting here for your help.</p> <p>I'm building a simple web server with Flask-Restful and Flask-SqlAlchemy. Basically, I think I'm getting an error because of a circular import. My <strong>Widget</strong> class is dependent on <strong>Visualization</strong> class and vice versa...</p> <p>The error message:</p> <pre><code>Traceback (most recent call last): File "server.py", line 1, in &lt;module&gt; from app.resources.dashboard import Dashboards, Dashboard File "app/__init__.py", line 14, in &lt;module&gt; from models import * File "app/models/__init__.py", line 1, in &lt;module&gt; import visualization.Visualization as VisualizationModel File "app/models/visualization.py", line 3, in &lt;module&gt; from app.models import WidgetModel ImportError: cannot import name WidgetModel </code></pre> <p>Directory structure:</p> <pre><code>├── app │   ├── app/__init__.py │   ├── app/models │   │   ├── app/models/__init__.py │   │   ├── app/models/dashboard.py │   │   ├── app/models/visualization.py │   │   ├── app/models/widget.py │   └── app/resources │   ├── app/resources/__init__.py │   ├── app/resources/dashboard.py │   ├── app/resources/visualization.py │   ├── app/resources/widget.py ├── server.py </code></pre> <p>app/models/__init__.py:</p> <pre><code>from visualization import Visualization as VisualizationModel from widget import Widget as WidgetModel from dashboard import Dashboard as DashboardModel </code></pre> <p>app/models/visualization.py</p> <pre><code>from sqlalchemy import types from app import db from app.models import WidgetModel class Visualization(db.Model): __tablename__ = 'visualizations' ... widget = db.relationship(WidgetModel, cascade="all, delete-orphan", backref="visualizations") </code></pre> <p>app/models/widget.py</p> <pre><code>from app import db from app.models import VisualizationModel class Widget(db.Model): __tablename__ = 'widgets' ... visualization = db.relationship(VisualizationModel, backref="widgets") </code></pre> <p>I tried changing my import to <code>from app import models</code>, and then use <code>models.WidgetModel</code> / <code>models.VisualizationModel</code>. However, still getting an ImportError.</p> <p>Error message:</p> <pre><code>Traceback (most recent call last): File "server.py", line 1, in &lt;module&gt; from app.resources.dashboard import Dashboards, Dashboard File "app/__init__.py", line 14, in &lt;module&gt; from models import * File "app/models/__init__.py", line 1, in &lt;module&gt; from visualization import Visualization as VisualizationModel File "app/models/visualization.py", line 3, in &lt;module&gt; from app import models ImportError: cannot import name models </code></pre> <p>I'm very new to Python. I would be grateful if you can help me out. Thanks for you help in advance!</p> <hr> <p><strong>Update</strong> </p> <p>The intention of defining bi-directional relationship is that I want to attach the <strong>Visualization</strong> object in the fields of <strong>Widget</strong> object upon a return of GET request on a widget record.</p> <p>In the app/resources/widget.py I have:</p> <pre><code>... from flask_restful import fields, Resource, marshal_with, abort from app.models import WidgetModel import visualization as visualizationResource widget_fields = { 'id': fields.String, ... 'dashboard_id': fields.String, 'visualization_id': fields.String, 'visualization': fields.Nested(visualizationResource.visualization_fields) } class Widgets(Resource): @marshal_with(widget_fields) def get(self): return WidgetModel.query.all() </code></pre> <p>I also want to have the <code>cascade delete</code> feature because if a <strong>widget</strong> cannot exist without a <strong>visualization</strong>.</p>
0
2016-10-16T00:45:58Z
40,065,739
<p>Change your import to look like this:</p> <pre><code>from app import models </code></pre> <p>And then use <code>models.WidgetModel</code> / <code>models.VisualizationModel</code> instead.</p> <p>The problem is that you're creating a circular import dependency where both files require the other file to already have been processed before they can be processed. By moving to importing the entire <code>models</code> namespace rather than trying to import a specific model name at import time, you avoid making the import dependent on a fully processed file. That way, both files can be fully processed before either tries to invoke an object created by the other.</p> <p>It may still not work in this case however because you're trying to immediately use the import in part of the class definition, which is evaluated at processing time.</p> <hr> <p>It looks like you're trying to define bi-directional relationships - the <code>backref</code> parameter is intended to do this automatically without you having to specify the relationship on both models. (<code>backref</code> tells sqlalchemy what field to add to the <em>other</em> model to point back to the original models that link to it). So you may not need to be doing both of these imports in the first place.</p> <p>For instance, the fact that <code>Visualization.widget</code> is defined with <code>backref="visualizations"</code> means that <code>Widget.visualizations</code> will <em>already exist</em> - you don't need to explicitly create it.</p> <p>If what you specifically need is many:many relationships, then chances are what you actually want to do is <a href="http://docs.sqlalchemy.org/en/latest/orm/basic_relationships.html#many-to-many" rel="nofollow">define an association table for the many-to-many relationship</a>.</p>
1
2016-10-16T00:50:07Z
[ "python", "flask-sqlalchemy", "flask-restful" ]
I'm trying to write a line of code at ask the user for two inputs but can't figure out how to complete this
40,065,720
<h1>Why does this line of code not split the two</h1> <pre><code>Lat1,long1 = input("Enter the Lat and Long of the source point separated by a comma eg 20,30").split() </code></pre>
0
2016-10-16T00:47:15Z
40,065,740
<p>By default using <code>split()</code> will only split on a space. You are asking the user to enter two entries separated by a <code>,</code>, so you will end up getting a</p> <pre><code>ValueError: not enough values to unpack (expected 2, got 1) </code></pre> <p>To resolve this, you need to split on the identifier you are looking to split with. In this case it is a ',', so call <code>split</code> as <code>split(',')</code>:</p> <pre><code>Lat1,long1 = input("Enter the Lat and Long of the source point separated by a comma eg 20,30").split(',') </code></pre> <p>Demo:</p> <pre><code>&gt;&gt;&gt; Lat1,long1 = input("Enter the Lat and Long of the source point separated by a comma eg 20,30").split(',') Enter the Lat and Long of the source point separated by a comma eg 20,3060,80 &gt;&gt;&gt; Lat1 '60' &gt;&gt;&gt; long1 '80' </code></pre> <p>Here is the documentation on split:</p> <p><a href="https://docs.python.org/3/library/stdtypes.html#str.split" rel="nofollow">https://docs.python.org/3/library/stdtypes.html#str.split</a></p>
2
2016-10-16T00:50:13Z
[ "python", "split" ]
How can i find the closest match
40,065,725
<p>I am matching values which is slightly different in that case how can i find the closest match</p> <p>In this example everything has very close relationship but how can my script find a match</p> <p>Eg script which i wrote</p> <pre><code>a = ["12,th 3rd street","6th avenue 3r cross","6th street pan,CA","345 hoston road CA","345 hoston road CA"] b = ["12,th 3rd st","6th av 3rd crs","6th street pan CA WY","345 hoston road, CA","345 hoston road,CA"] for s in a: for v in b: if s == v: python s </code></pre> <p>If you see both this array only some worrs will differ</p> <pre><code>a = ["12,th 3rd street","6th avenue 3r cross","6th street pan,CA","345 hoston road CA","345 hoston road CA"] b = ["12,th 3rd st","6th av 3rd crs","6th street pan CA WY","345 hoston road, CA","345 hoston road,CA"] </code></pre>
0
2016-10-16T00:47:43Z
40,065,823
<p>I hope you need some predefined words for matching <code>this or that</code>.</p> <pre><code>for eg., {cross:{cr,crs}, avenue:{av,avn}} </code></pre> <p>you can match the some continuous strings directly </p> <pre><code>for i in a: for j in b: if i in j or j in i: print (i,j) </code></pre> <p>This gives,</p> <p><code>12,th 3rd street</code> <code>12,th 3rd st</code></p> <p>to match other cases use the dictionary to select any value using key or vice versa.</p>
0
2016-10-16T01:07:55Z
[ "python", "algorithm", "data-structures", "string-matching" ]
Why does this code take so long to be executed? - Python
40,065,760
<p>I coded this on Python. It took way too long to finish if the input were just 40x40 (it's for image processing using <code>numpy</code>). Its behavious is the following: there's an array with objects in it (which have an 'image' attribute which is a numpy array) and then I check if that object is somewhere in another array, and then take the next from the first array and repeat the process until I've checked if all are in the other array:</p> <pre><code> #__sub_images is the array containing the objects to be compared #to_compare_image is the image that is received as parameter to check if the objects are in there. #get_sub_images() is just to retrieve the objects from the array from the received array to find. #get_image() is the method that retrieves the attribute from the objects same = True rows_pixels = 40 #problem size cols_pixels = 40 #problem size i = 0 #row index to move the array containing the object that must be checked if exist j = 0 #col index to move the array containing the object that must be checked if exist k = 0 #row index to move the array where will be checked if the object exist l = 0 #col index to move the array where will be checked if the object exist while i &lt; len(self.__sub_images) and k &lt; len(to_compare_image.get_sub_images()) and l &lt; len(to_compare_image.get_sub_images()[0]): if not np.array_equal(self.__sub_images[i][j].get_image(), to_compare_image.get_sub_images()[k][l].get_image()): same = False else: same = True k = 0 l = 0 if j == len(self.__sub_images[0]) - 1: j = 0 i += 1 else: j += 1 if not same: if l == len(to_compare_image.get_sub_images()[0]) - 1: l = 0 k += 1 else: l += 1 </code></pre> <p>I managed to code it with just a <code>while</code>, instead of 4 <code>for-loops</code> which is what I used to do before. Why is it taking so long still? Is it normal or is there something wrong? The complexity is supposed to be x and not x⁴</p> <p>The code that is not included are just getters, I hope you can understand it with the <code>#notes</code> at the begining.</p> <p>THanks.</p>
0
2016-10-16T00:53:10Z
40,065,951
<p>Instead of this:</p> <pre><code>if not np.array_equal(self.__sub_images[i][j].get_image(), to_compare_image.get_sub_images()[k][l].get_image()): same = False else: same = True #snip if not same: #snip </code></pre> <p>You can do this:</p> <pre><code>same=np.array_equal(self.__sub_images[i][j].get_image(), to_compare_image.get_sub_images()[k][l].get_image()) if same: #snip else: #snip </code></pre> <p>This uses less if-branches than before.</p>
-1
2016-10-16T01:34:35Z
[ "python", "performance", "loops" ]