qid
int64
46k
74.7M
question
stringlengths
54
37.8k
date
stringlengths
10
10
metadata
listlengths
3
3
response_j
stringlengths
17
26k
response_k
stringlengths
26
26k
43,630,195
`A = [[[1,2,3],[4]],[[1,4],[2,3]]]` Here I want to find lists in A which sum of all sublists in list not grater than 5. Which the result should be `[[1,4],[2,3]]` I tried a long time to solve this problem in python. But I still can't figure out the right solution, which I stuck at loop out multiple loops. My code as follows, but its obviously wrong, how to correct it? ``` A = [[[1,2,3],[4]],[[1,4],[2,3]]] z = [] for l in A: for list in l: sum = 0 while sum < 5: for i in list: sum+=i else: break else: z.append(l) print z ``` Asking for help~
2017/04/26
[ "https://Stackoverflow.com/questions/43630195", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5702561/" ]
Simplification of @KindStranger method in a one-liner: ``` >> [sub for x in A for sub in x if max(sum(sub) for sub in x) <= 5] [[1, 4], [2, 3]] ```
The one with `all()` ``` [t for item in A for t in item if all(sum(t)<=5 for t in item)] ```
54,093,050
I'm following this code example from a [python course](https://www.python-course.eu/python3_properties.php): ``` class P: def __init__(self,x): self.x = x @property def x(self): return self.__x @x.setter def x(self, x): if x < 0: self.__x = 0 elif x > 1000: self.__x = 1000 else: self.__x = x ``` And I tried to implement this pattern to my own code: ``` class PCAModel(object): def __init__(self): self.M_inv = None @property def M_inv(self): return self.__M_inv @M_inv.setter def set_M_inv(self): M = self.var * np.eye(self.W.shape[1]) + np.matmul(self.W.T, self.W) self.__M_inv = np.linalg.inv(M) ``` Note that I want the `M_inv` property to be `None` before I have run the setter the first time. Also, the setter solely relies on other properties of the class object, and not on input arguments. The setter decorator generates an error: ``` NameError: name 'M_inv' is not defined ``` Why is this?
2019/01/08
[ "https://Stackoverflow.com/questions/54093050", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3128156/" ]
Your setter method should be like below: ``` @M_inv.setter def M_inv(self): M = self.var * np.eye(self.W.shape[1]) + np.matmul(self.W.T, self.W) self.__M_inv = np.linalg.inv(M) ``` The decorator `@M_inv.setter` and the function `def M_inv(self):` name should be same
The example is wrong. EDIT: Example was using a setter in `__init__` on purpose. Getters and setters, even though they act like properties, are just methods that access a private attribute. That attribute **must exist**. In the example, `self.__x` is never created. Here is my suggested use : ``` class PCAModel(object): def __init__(self): # We create a private variable self.__M_inv = None @property def M_inv(self): # Accessing M_inv returns the value of the previously created variable return self.__M_inv @M_inv.setter def M_inv(self): # Keep the same name than your propery M = self.var * np.eye(self.W.shape[1]) + np.matmul(self.W.T, self.W) self.__M_inv = np.linalg.inv(M) ```
58,798,388
I feel silly having to ask this question, but my memory evades me of better alternatives. Two appraoches that spring to mind: First: ``` def f1(v): return sum(2**i for i,va in enumerate(v) if va) >>> f1([True, False, True]) 5 ``` Second: ``` def f2(v): return int('0b' + "".join(str(int(va)) for va in v),2) >>> f2([True, False, True]) 5 ``` I feel that f1 is almost to clunky to be pythonic, and f2 is plainly too ugly as I'm jumping between multiple datatypes. Maybe its my age...?
2019/11/11
[ "https://Stackoverflow.com/questions/58798388", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1186019/" ]
Using booleans in arithmetic operations (also lambda functions) is very pythonic: ``` lst = [True, False, True] func = lambda x: sum(2 ** num * i for num, i in enumerate(x)) print(func(lst)) # 5 ```
This is another hacky way I came up with: ``` def f1(v): return int(''.join(str(int(b)) for b in v), 2) ``` Example: ``` >>> def f1(v): ... return int(''.join(str(int(b)) for b in v), 2) ... >>> f1([True, False, True]) 5 >>> ``` Another identical example using `map` (more readable in my view): ``` def f1(v): return int(''.join(map(str, map(int, v))), 2) ```
58,798,388
I feel silly having to ask this question, but my memory evades me of better alternatives. Two appraoches that spring to mind: First: ``` def f1(v): return sum(2**i for i,va in enumerate(v) if va) >>> f1([True, False, True]) 5 ``` Second: ``` def f2(v): return int('0b' + "".join(str(int(va)) for va in v),2) >>> f2([True, False, True]) 5 ``` I feel that f1 is almost to clunky to be pythonic, and f2 is plainly too ugly as I'm jumping between multiple datatypes. Maybe its my age...?
2019/11/11
[ "https://Stackoverflow.com/questions/58798388", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1186019/" ]
Using a left shift is slightly faster than raising to powers (at least on my machine). Using a bitwise operation encourages the reader of the code to think in terms of binary data. ``` >>> sum(v << i for i, v in enumerate([True, False, True])) 5 ```
This is another hacky way I came up with: ``` def f1(v): return int(''.join(str(int(b)) for b in v), 2) ``` Example: ``` >>> def f1(v): ... return int(''.join(str(int(b)) for b in v), 2) ... >>> f1([True, False, True]) 5 >>> ``` Another identical example using `map` (more readable in my view): ``` def f1(v): return int(''.join(map(str, map(int, v))), 2) ```
58,798,388
I feel silly having to ask this question, but my memory evades me of better alternatives. Two appraoches that spring to mind: First: ``` def f1(v): return sum(2**i for i,va in enumerate(v) if va) >>> f1([True, False, True]) 5 ``` Second: ``` def f2(v): return int('0b' + "".join(str(int(va)) for va in v),2) >>> f2([True, False, True]) 5 ``` I feel that f1 is almost to clunky to be pythonic, and f2 is plainly too ugly as I'm jumping between multiple datatypes. Maybe its my age...?
2019/11/11
[ "https://Stackoverflow.com/questions/58798388", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1186019/" ]
Just for contrast here's a way that you would do this if you were writing python as if you were writing something like c. ``` def f(l): output = 0 for i in range(len(l)): output |= l[i] << i return output ```
This is another hacky way I came up with: ``` def f1(v): return int(''.join(str(int(b)) for b in v), 2) ``` Example: ``` >>> def f1(v): ... return int(''.join(str(int(b)) for b in v), 2) ... >>> f1([True, False, True]) 5 >>> ``` Another identical example using `map` (more readable in my view): ``` def f1(v): return int(''.join(map(str, map(int, v))), 2) ```
58,798,388
I feel silly having to ask this question, but my memory evades me of better alternatives. Two appraoches that spring to mind: First: ``` def f1(v): return sum(2**i for i,va in enumerate(v) if va) >>> f1([True, False, True]) 5 ``` Second: ``` def f2(v): return int('0b' + "".join(str(int(va)) for va in v),2) >>> f2([True, False, True]) 5 ``` I feel that f1 is almost to clunky to be pythonic, and f2 is plainly too ugly as I'm jumping between multiple datatypes. Maybe its my age...?
2019/11/11
[ "https://Stackoverflow.com/questions/58798388", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1186019/" ]
Using a left shift is slightly faster than raising to powers (at least on my machine). Using a bitwise operation encourages the reader of the code to think in terms of binary data. ``` >>> sum(v << i for i, v in enumerate([True, False, True])) 5 ```
Using booleans in arithmetic operations (also lambda functions) is very pythonic: ``` lst = [True, False, True] func = lambda x: sum(2 ** num * i for num, i in enumerate(x)) print(func(lst)) # 5 ```
58,798,388
I feel silly having to ask this question, but my memory evades me of better alternatives. Two appraoches that spring to mind: First: ``` def f1(v): return sum(2**i for i,va in enumerate(v) if va) >>> f1([True, False, True]) 5 ``` Second: ``` def f2(v): return int('0b' + "".join(str(int(va)) for va in v),2) >>> f2([True, False, True]) 5 ``` I feel that f1 is almost to clunky to be pythonic, and f2 is plainly too ugly as I'm jumping between multiple datatypes. Maybe its my age...?
2019/11/11
[ "https://Stackoverflow.com/questions/58798388", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1186019/" ]
Using booleans in arithmetic operations (also lambda functions) is very pythonic: ``` lst = [True, False, True] func = lambda x: sum(2 ** num * i for num, i in enumerate(x)) print(func(lst)) # 5 ```
Its little more rigid solution but its very **computationally efficient** ``` >>> import numpy as np >>> predefined_bytes = 2**(np.arange(32)) >>> predefined_bytes array([ 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536, 131072, 262144, 524288, 1048576, 2097152, 4194304, 8388608, 16777216, 33554432, 67108864, 134217728, 268435456, 536870912, 1073741824, 2147483648]) def binary2decimal(bits,predefined_bytes): bits = np.array(bits) return np.sum(bits*predefined_bytes[:bits.shape[0]]) >>> binary2decimal([1,1,1,1,1,1,1,1],predefined_bytes) 255 ```
58,798,388
I feel silly having to ask this question, but my memory evades me of better alternatives. Two appraoches that spring to mind: First: ``` def f1(v): return sum(2**i for i,va in enumerate(v) if va) >>> f1([True, False, True]) 5 ``` Second: ``` def f2(v): return int('0b' + "".join(str(int(va)) for va in v),2) >>> f2([True, False, True]) 5 ``` I feel that f1 is almost to clunky to be pythonic, and f2 is plainly too ugly as I'm jumping between multiple datatypes. Maybe its my age...?
2019/11/11
[ "https://Stackoverflow.com/questions/58798388", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1186019/" ]
Just for contrast here's a way that you would do this if you were writing python as if you were writing something like c. ``` def f(l): output = 0 for i in range(len(l)): output |= l[i] << i return output ```
Using booleans in arithmetic operations (also lambda functions) is very pythonic: ``` lst = [True, False, True] func = lambda x: sum(2 ** num * i for num, i in enumerate(x)) print(func(lst)) # 5 ```
58,798,388
I feel silly having to ask this question, but my memory evades me of better alternatives. Two appraoches that spring to mind: First: ``` def f1(v): return sum(2**i for i,va in enumerate(v) if va) >>> f1([True, False, True]) 5 ``` Second: ``` def f2(v): return int('0b' + "".join(str(int(va)) for va in v),2) >>> f2([True, False, True]) 5 ``` I feel that f1 is almost to clunky to be pythonic, and f2 is plainly too ugly as I'm jumping between multiple datatypes. Maybe its my age...?
2019/11/11
[ "https://Stackoverflow.com/questions/58798388", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1186019/" ]
Using a left shift is slightly faster than raising to powers (at least on my machine). Using a bitwise operation encourages the reader of the code to think in terms of binary data. ``` >>> sum(v << i for i, v in enumerate([True, False, True])) 5 ```
Its little more rigid solution but its very **computationally efficient** ``` >>> import numpy as np >>> predefined_bytes = 2**(np.arange(32)) >>> predefined_bytes array([ 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536, 131072, 262144, 524288, 1048576, 2097152, 4194304, 8388608, 16777216, 33554432, 67108864, 134217728, 268435456, 536870912, 1073741824, 2147483648]) def binary2decimal(bits,predefined_bytes): bits = np.array(bits) return np.sum(bits*predefined_bytes[:bits.shape[0]]) >>> binary2decimal([1,1,1,1,1,1,1,1],predefined_bytes) 255 ```
58,798,388
I feel silly having to ask this question, but my memory evades me of better alternatives. Two appraoches that spring to mind: First: ``` def f1(v): return sum(2**i for i,va in enumerate(v) if va) >>> f1([True, False, True]) 5 ``` Second: ``` def f2(v): return int('0b' + "".join(str(int(va)) for va in v),2) >>> f2([True, False, True]) 5 ``` I feel that f1 is almost to clunky to be pythonic, and f2 is plainly too ugly as I'm jumping between multiple datatypes. Maybe its my age...?
2019/11/11
[ "https://Stackoverflow.com/questions/58798388", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1186019/" ]
Using a left shift is slightly faster than raising to powers (at least on my machine). Using a bitwise operation encourages the reader of the code to think in terms of binary data. ``` >>> sum(v << i for i, v in enumerate([True, False, True])) 5 ```
Just for contrast here's a way that you would do this if you were writing python as if you were writing something like c. ``` def f(l): output = 0 for i in range(len(l)): output |= l[i] << i return output ```
58,798,388
I feel silly having to ask this question, but my memory evades me of better alternatives. Two appraoches that spring to mind: First: ``` def f1(v): return sum(2**i for i,va in enumerate(v) if va) >>> f1([True, False, True]) 5 ``` Second: ``` def f2(v): return int('0b' + "".join(str(int(va)) for va in v),2) >>> f2([True, False, True]) 5 ``` I feel that f1 is almost to clunky to be pythonic, and f2 is plainly too ugly as I'm jumping between multiple datatypes. Maybe its my age...?
2019/11/11
[ "https://Stackoverflow.com/questions/58798388", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1186019/" ]
Just for contrast here's a way that you would do this if you were writing python as if you were writing something like c. ``` def f(l): output = 0 for i in range(len(l)): output |= l[i] << i return output ```
Its little more rigid solution but its very **computationally efficient** ``` >>> import numpy as np >>> predefined_bytes = 2**(np.arange(32)) >>> predefined_bytes array([ 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536, 131072, 262144, 524288, 1048576, 2097152, 4194304, 8388608, 16777216, 33554432, 67108864, 134217728, 268435456, 536870912, 1073741824, 2147483648]) def binary2decimal(bits,predefined_bytes): bits = np.array(bits) return np.sum(bits*predefined_bytes[:bits.shape[0]]) >>> binary2decimal([1,1,1,1,1,1,1,1],predefined_bytes) 255 ```
54,757,300
I have an existing python array instantiated with zeros. How do I iterate through and change the values? I can't iterate through and change elements of a Python array? ``` num_list = [1,2,3,3,4,5,] mu = np.mean(num_list) sigma = np.std(num_list) std_array = np.zeros(len(num_list)) for i in std_array: temp_num = ((i-mu)/sigma) std_array[i]=temp_num ``` This the error: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices
2019/02/19
[ "https://Stackoverflow.com/questions/54757300", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7671993/" ]
In your code you are iterating over the elements of the `numpy.array` `std_array`, but then using these elements as indices to dereference `std_array`. An easy solution would be the following. ``` num_arr = np.array(num_list) for i,element in enumerate(num_arr): temp_num = (element-mu)/sigma std_array[i]=temp_num ``` where I am assuming you wanted to use the value of the `num_list` in the first line of the loop when computing `temp_num`. Notice that I created a new `numpy.array` called `num_arr` though. This is because rather than looping, we can use alternative solution that takes advantage of [broadcasting](https://docs.scipy.org/doc/numpy/user/basics.broadcasting.html): ``` std_array = (num_arr-mu)/sigma ``` This is equivalent to the loop, but faster to execute and simpler.
You `i` is an element from `std_array`, which is `float`. `Numpy` is therefore complaining that you are trying slicing with `float` where: > > only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) > and integer or boolean arrays are valid indices > > > If you don't have to use `for`, then `numpy` can broadcast the calculations for you: ``` (std_array - mu)/sigma # array([-2.32379001, -2.32379001, -2.32379001, -2.32379001, -2.32379001, -2.32379001]) ```
32,200,565
I`ve got this exception when using returnvalue in function ``` @inlineCallbacks def my_func(id): yield somefunc(id) @inlineCallbacks def somefunc(id): somevar = yield func(id) returnValue(somevar) returnValue(somevar) File "/usr/lib64/python2.7/site-packages/twisted/internet/defer.py", line 1105, in returnValue raise _DefGen_Return(val) twisted.internet.defer._DefGen_Return: ``` The function works fine, but raises an exception. How can i avoid this exception? I just need to return some value from the function.
2015/08/25
[ "https://Stackoverflow.com/questions/32200565", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4349456/" ]
Just download and install [wp-pagenavi](https://wordpress.org/plugins/wp-pagenavi/) plugin and then use: ``` if(method_exists('wp_pagenavi')){ wp_pagenavi(array('query' => $query)); } ``` Pass your query object in wp\_pagenavi method argument.
i guess, you are seeking a numbered pagination for custom query, than try this article [Kvcodes](http://www.kvcodes.com/2015/08/how-to-add-numeric-pagination-in-your-wordpress-theme-without-plugin/). here is the code. ``` function kvcodes_pagination_fn($pages = '', $range = 2){ $showitems = ($range * 2)+1; // This is the items range, that we can pass it as parameter depending on your necessary. global $paged; // Global variable to catch the page counts if(empty($paged)) $paged = 1; if($pages == '') { // paged is not defined than its first page. just assign it first page. global $wp_query; $pages = $wp_query->max_num_pages; if(!$pages) $pages = 1; } if(1 != $pages) { //For other pages, make the pagination work on other page queries echo "<div class='kvc_pagination'>"; if($paged > 2 && $paged > $range+1 && $showitems < $pages) echo "<a href='".get_pagenum_link(1)."'>&laquo;</a>"; if($paged > 1 && $showitems < $pages) echo "<a href='".get_pagenum_link($paged - 1)."'>&lsaquo;</a>"; for ($i=1; $i <= $pages; $i++) { if (1 != $pages &&( !($i >= $paged+$range+1 || $i <= $paged-$range-1) || $pages <= $showitems )) echo ($paged == $i)? "<span class='current'>".$i."</span>":"<a href='".get_pagenum_link($i)."' class='inactive' >".$i."</a>"; } if ($paged < $pages && $showitems < $pages) echo "<a href='".get_pagenum_link($paged + 1)."'>&rsaquo;</a>"; if ($paged < $pages-1 && $paged+$range-1 < $pages && $showitems < $pages) echo "<a href='".get_pagenum_link($pages)."'>&raquo;</a>"; echo "</div>\n"; } } ``` place the function on your current theme, functions.php and use it on loop.php or index.php ``` kvcodes_pagination_fn(); ``` and for the WP\_Query example ``` $custom_query = new WP_Query("post_type=receipes&author=kvcodes"); while ($custom_query->have_posts()) : $custom_query->the_post(); // Show loop content... endwhile; kvcodes_pagination_fn($custom_query->max_num_pages); ``` that's it.
59,723,005
For my report, I'm creating a special color plot in jupyter notebook. There are two parameters, `x` and `y`. ``` import numpy as np x = np.arange(-1,1,0.1) y = np.arange(1,11,1) ``` with which I compute a third quantity. Here is an example to demonstrate the concept: ``` values = [] for i in range(len(y)) : z = y[i] * x**3 # in my case the value z represents phases of oscillators # so I will transform the computed values to the intervall [0,2pi) values.append(z) values = np.array(values) % 2*np.pi ``` I'm plotting `y` vs `x`. For each `y = 1,2,3,4...` there will be a horizontal line with total length two. For example: The coordinate `(0.5,8)` stands for a single point on line 8 at position `x = 0.5` and `z(0.5,8)` is its associated value. Now I want to represent each point on all ten lines with a unique color that is determined by `z(x,y)`. Since `z(x,y)` takes only values in `[0,2pi)` I need a color scheme that starts at zero (for example `z=0` corresponds to blue). For increasing z the color continuously changes and in the end at `2pi` it takes the same color again (so at `z ~ 2pi` it becomes blue again). Does someone know how this can be done in python?
2020/01/13
[ "https://Stackoverflow.com/questions/59723005", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
A known (reasonably) numerically-stable version of the geometric mean is: ```py import torch def gmean(input_x, dim): log_x = torch.log(input_x) return torch.exp(torch.mean(log_x, dim=dim)) x = torch.Tensor([2.0] * 1000).requires_grad_(True) print(gmean(x, dim=0)) # tensor(2.0000, grad_fn=<ExpBackward>) ``` This kind of implementation can be found, for example, in SciPy ([see here](https://github.com/scipy/scipy/blob/1cc8beed5362ed290f5a8ddf4e99db49b4de6286/scipy/stats/mstats_basic.py#L268-L271)), which is a quite stable lib. --- The implementation above does not handle zeros and negative numbers. Some will argue that the geometric mean with negative numbers is not well-defined, at least when not all of them are negative.
torch.prod() helps: ``` import torch x = torch.FloatTensor(3).uniform_().requires_grad_(True) print(x) y = x.prod() ** (1.0/x.shape[0]) print(y) y.backward() print(x.grad) # tensor([0.5692, 0.7495, 0.1702], requires_grad=True) # tensor(0.4172, grad_fn=<PowBackward0>) # tensor([0.2443, 0.1856, 0.8169]) ``` EDIT: ?what about ``` y = (x.abs() ** (1.0/x.shape[0]) * x.sign() ).prod() ```
5,268,391
Is it possible to pipe numpy data (from one python script ) into the other? suppose that `script1.py` looks like this: `x = np.zeros(3, dtype={'names':['col1', 'col2'], 'formats':['i4','f4']})` `print x` Suppose that from the linux command, I run the following: `python script1.py | script2.py` Will `script2.py` get the piped numpy data as an input (stdin)? will the data still be in the same format of numpy? (so that I can, for example, perform numpy operations on it from within `script2.py`)?
2011/03/11
[ "https://Stackoverflow.com/questions/5268391", "https://Stackoverflow.com", "https://Stackoverflow.com/users/540009/" ]
No, data is passed through a pipe as text. You'll need to serialize the data in `script1.py` before writing, and deserialize it in `script2.py` after reading.
Check out the `save` and `load` functions. I don't think they would object to being passed a pipe instead of a file.
5,268,391
Is it possible to pipe numpy data (from one python script ) into the other? suppose that `script1.py` looks like this: `x = np.zeros(3, dtype={'names':['col1', 'col2'], 'formats':['i4','f4']})` `print x` Suppose that from the linux command, I run the following: `python script1.py | script2.py` Will `script2.py` get the piped numpy data as an input (stdin)? will the data still be in the same format of numpy? (so that I can, for example, perform numpy operations on it from within `script2.py`)?
2011/03/11
[ "https://Stackoverflow.com/questions/5268391", "https://Stackoverflow.com", "https://Stackoverflow.com/users/540009/" ]
No, data is passed through a pipe as text. You'll need to serialize the data in `script1.py` before writing, and deserialize it in `script2.py` after reading.
See [this question](https://stackoverflow.com/questions/5033799/how-do-i-pass-large-numpy-arrays-between-python-subprocesses-without-saving-to-di). If you're willing to use the `subprocess` module, you can share memory between processes to pass numpy arrays rapidly. If not, I've found saving to a file beats the pants off of piping, probably because converting the array to a string is so slow.
5,268,391
Is it possible to pipe numpy data (from one python script ) into the other? suppose that `script1.py` looks like this: `x = np.zeros(3, dtype={'names':['col1', 'col2'], 'formats':['i4','f4']})` `print x` Suppose that from the linux command, I run the following: `python script1.py | script2.py` Will `script2.py` get the piped numpy data as an input (stdin)? will the data still be in the same format of numpy? (so that I can, for example, perform numpy operations on it from within `script2.py`)?
2011/03/11
[ "https://Stackoverflow.com/questions/5268391", "https://Stackoverflow.com", "https://Stackoverflow.com/users/540009/" ]
Check out the `save` and `load` functions. I don't think they would object to being passed a pipe instead of a file.
See [this question](https://stackoverflow.com/questions/5033799/how-do-i-pass-large-numpy-arrays-between-python-subprocesses-without-saving-to-di). If you're willing to use the `subprocess` module, you can share memory between processes to pass numpy arrays rapidly. If not, I've found saving to a file beats the pants off of piping, probably because converting the array to a string is so slow.
26,373,356
I am not sure why I am getting an error that game is not defined: ``` #!/usr/bin/python # global variables wins = 0 losses = 0 draws = 0 games = 0 # Welcome and get name of human player print 'Welcome to Rock Paper Scissors!!' human = raw_input('What is your name?') print 'Hello ',human # start game game() def game(): humanSelect = raw_input('Enter selection: R - Rock, P - Paper, S - Scissors, Q - Quit: ') while humanSelect not in ['R', 'P', 'S', 'Q']: print humanSelect, 'is not a valid selection' humanSelect = raw_input('Enter a valid option please') return humanSelect main() ```
2014/10/15
[ "https://Stackoverflow.com/questions/26373356", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4147288/" ]
You have to define the function `game` before you can call it. ``` def game(): ... game() ```
Okay, I spent some time tinkering with this today and now have the following: ``` import random import string # global variables global wins wins = 0 global losses losses = 0 global draws draws = 0 global games games = 0 # Welcome and get name of human player print 'Welcome to Rock Paper Scissors!!' human = raw_input('What is your name? ') print 'Hello ',human def readyToPlay(): ready = raw_input('Ready to Play? <Y> or <N> ') ready = string.upper(ready) if ready == 'Y': game() else: if games == 0: print 'Thanks for playing' exit else: gameResults(games, wins, losses, draws) return def game(): global games games += 1 human = humanChoice() computer = computerChoice() playResults(human, computer) readyToPlay() def humanChoice(): humanSelect = raw_input('Enter selection: R - Rock, P - Paper, S - Scissors: ') while humanSelect not in ['R', 'P', 'S']: print humanSelect, 'is not a valid selection' humanSelect = raw_input('Enter a valid option please') return humanSelect def computerChoice(): computerInt = random.randint(1, 3) if computerInt == '1': computerSelect = 'R' elif computerInt == '2': computerSelect = 'P' else: computerSelect = 'S' return computerSelect def playResults(human, computer): global draws global wins global losses if human == computer: print 'Draw' draws += 1 elif human == 'R' and computer == 'P': print 'My Paper wrapped your Rock, you lose.' losses += 1 elif human == 'R' and computer == 'S': print 'Your Rock smashed my Scissors, you win!' wins += 1 elif human == 'P' and computer == 'S': print 'My Scissors cut your paper, you lose.' losses += 1 elif human == 'P' and computer == 'R': print 'Your Paper covers my Rock, you win!' wins += 1 elif human == 'S' and computer == 'R': print 'My Rock smashes your Scissors, you lose.' losses += 1 elif human == 'S' and computer == 'P': print 'Your Scissors cut my Paper, you win!' wins += 1 def gameResults(games, wins, losses, draws): print 'Total games played', games print 'Wins: ', wins, ' Losses: ',losses, ' Draws: ', draws exit readyToPlay() ``` I am going to work on the forcing the humanSelect variable to upper case in the same manner that I did with ready, ready = string.upper(ready). I ran into indentation errors earlier today, but will iron that out later tonight. I do have a question. Is it possible to use a variable between the () of a raw\_input function similar to this: ``` if game == 0: greeting = 'Would you like to play Rock, Paper, Scissors?' else: greeting = 'Play again?' ready = raw_input(greeting) ```
26,373,356
I am not sure why I am getting an error that game is not defined: ``` #!/usr/bin/python # global variables wins = 0 losses = 0 draws = 0 games = 0 # Welcome and get name of human player print 'Welcome to Rock Paper Scissors!!' human = raw_input('What is your name?') print 'Hello ',human # start game game() def game(): humanSelect = raw_input('Enter selection: R - Rock, P - Paper, S - Scissors, Q - Quit: ') while humanSelect not in ['R', 'P', 'S', 'Q']: print humanSelect, 'is not a valid selection' humanSelect = raw_input('Enter a valid option please') return humanSelect main() ```
2014/10/15
[ "https://Stackoverflow.com/questions/26373356", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4147288/" ]
Because, at the time the statement `game()` is executed you have not yet reached the statement `def game():` and game is, therefore, undefined. If you move `game()` to after `def game()` you will then get a similar error on `main()` which is harder to fix as you don't appear to be defining a function called `main` anywhere in the code.
Okay, I spent some time tinkering with this today and now have the following: ``` import random import string # global variables global wins wins = 0 global losses losses = 0 global draws draws = 0 global games games = 0 # Welcome and get name of human player print 'Welcome to Rock Paper Scissors!!' human = raw_input('What is your name? ') print 'Hello ',human def readyToPlay(): ready = raw_input('Ready to Play? <Y> or <N> ') ready = string.upper(ready) if ready == 'Y': game() else: if games == 0: print 'Thanks for playing' exit else: gameResults(games, wins, losses, draws) return def game(): global games games += 1 human = humanChoice() computer = computerChoice() playResults(human, computer) readyToPlay() def humanChoice(): humanSelect = raw_input('Enter selection: R - Rock, P - Paper, S - Scissors: ') while humanSelect not in ['R', 'P', 'S']: print humanSelect, 'is not a valid selection' humanSelect = raw_input('Enter a valid option please') return humanSelect def computerChoice(): computerInt = random.randint(1, 3) if computerInt == '1': computerSelect = 'R' elif computerInt == '2': computerSelect = 'P' else: computerSelect = 'S' return computerSelect def playResults(human, computer): global draws global wins global losses if human == computer: print 'Draw' draws += 1 elif human == 'R' and computer == 'P': print 'My Paper wrapped your Rock, you lose.' losses += 1 elif human == 'R' and computer == 'S': print 'Your Rock smashed my Scissors, you win!' wins += 1 elif human == 'P' and computer == 'S': print 'My Scissors cut your paper, you lose.' losses += 1 elif human == 'P' and computer == 'R': print 'Your Paper covers my Rock, you win!' wins += 1 elif human == 'S' and computer == 'R': print 'My Rock smashes your Scissors, you lose.' losses += 1 elif human == 'S' and computer == 'P': print 'Your Scissors cut my Paper, you win!' wins += 1 def gameResults(games, wins, losses, draws): print 'Total games played', games print 'Wins: ', wins, ' Losses: ',losses, ' Draws: ', draws exit readyToPlay() ``` I am going to work on the forcing the humanSelect variable to upper case in the same manner that I did with ready, ready = string.upper(ready). I ran into indentation errors earlier today, but will iron that out later tonight. I do have a question. Is it possible to use a variable between the () of a raw\_input function similar to this: ``` if game == 0: greeting = 'Would you like to play Rock, Paper, Scissors?' else: greeting = 'Play again?' ready = raw_input(greeting) ```
53,350,132
I'm trying to understand how to pull a specific item from the code below. ``` var snake = [[{x : 20, y : 30}],[{x : 40, y: 50}]]; ``` Coming from python I found this to be useful when dealing with for loops to have all my objects in an array within an array. Say for instance I want to pull the first `x:` value from the first object container. I thought `snake[0][0].x` would return `20`, and `snake[1][1].y`would return `50`. but instead I receive: `Uncaught TypeError: Cannot read property 'x' of undefined` ```js var snake = [[{x : 20, y : 30}],[{x : 40, y: 50}]]; snake[0][0].x; snake[1][1].y; ``` I'm new to JavaScript, trying to understand why this doesn't work and if there is a way to write this so that it may. Thank you for your help in advance.
2018/11/17
[ "https://Stackoverflow.com/questions/53350132", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10444342/" ]
You are deleting a large number of rows. That is the problem. There is lots of overhead in deletions. If you are deleting a significant number of rows in a table -- and significant might only be a few percent -- then it is often faster to recreate the table: ``` select b.* into temp_b -- actually, I wouldn't use a temporary table in case the server goes down from b where b.id = (select max(a.id) from b b2 where b2.id = b.a_id); truncate table b; insert into b select * from temp_b; ``` Before attempting this, be sure that you have backed up `b` or at least stashed a copy of it somewhere. Note that I changed the structure of the `NOT IN`. I strongly discourage the use of `NOT IN`, because the semantics are not intuitive when the subquery returns `NULL` values. If there were a single `NULL` value, then the `WHERE` would never evaluate to TRUE. Even if `NULL` values are not a problem in this case, I strongly recommend using other alternatives so you won't have a problem when `NULL`s are a possibility. For performance on the `SELECT`, you want an index on `b(a_id, id)`. You might find that such an index helps on your original query.
Your query looks fine to me. Your problem seems to be that you have a very large amount of data and need ways to optimize performance. What you can do is materialize your subquery, and make sure max\_id is indexed, for example by making it a primary key. So create a temporary table `Max_B`, and store the results of your sub query in this table. Then perform the delete and drop the temp table afterwards.
51,869,152
Supposing that a have this dict with the keys and some range: ``` d = {"x": (0, 2), "y": (2, 4)} ``` I need to create dicts using the range above, I will get: ``` >>> keys = [k for k,v in d.items()] >>> >>> def newDict(keys,array): ... return dict(zip(keys,array)) ... >>> for i in range(0,2): ... for j in range(2,4): ... dd = newDict(keys, [i,j]) ... print (dd) ... {'x': 0, 'y': 2} {'x': 0, 'y': 3} {'x': 1, 'y': 2} {'x': 1, 'y': 3} ``` My doubt is how to iterate change the key **using the ranges** and create a new dicts in a more pythonic way. Supposing the I add more one key **z**: ``` d = {"x": (0, 2), "y": (2, 4), "z": (3, 5)} ``` So, I will need to add a more for loop nested. Is there another approach?
2018/08/16
[ "https://Stackoverflow.com/questions/51869152", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2452792/" ]
This is known behavior that came about a few versions ago (I think 2016). This `#{style}` interpolation is not supported in attributes: > > Caution > > > Previous versions of Pug/Jade supported an interpolation syntax such > as: > > > a(href="/#{url}") Link This syntax is no longer supported. > Alternatives are found below. (Check our migration guide for more > information on other incompatibilities between Pug v2 and previous > versions.) > > > For more see: <https://pugjs.org/language/attributes.html> You should be able to use regular [template literals](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals): ``` a(href=`${originalUrl}`) ```
There is an easy way to do that, write directly the variable, without using quotes, brackets, $, !, or #, like this: ``` a(href=originalUrl) !{originalURL} ``` The result of this is a link with the text in originalURL Example: if originalUrl = 'www.google.es' ``` a(href='www.google.es') www.google.es ``` finally you get the link: [www.google.es](http://www.google.es)
58,928,062
``` import pandas as pd from sqlalchemy import create_engine host='user@127.0.0.1' port=10000 schema ='result' table='new_table' engine = create_engine(f'hive://{host}:{port}/{schema}') conn=engine.connect() engine.execute('CREATE TABLE ' + table + ' (year int, GDP_rate int, GDP string)') data = { 'year': [2017, 2018], 'GDP_rate': [31, 30], 'GDP': ['1.73M', '1.83M'] } df = pd.DataFrame(data) df.to_sql(name=table, con=engine,schema='result',index=False,if_exists='append',chunksize=5000) conn.close() ``` this is my code make pandas dataframe which save to hive table but when i run the code i got the error message like this ``` File "/opt/rh/rh-python36/root/usr/lib/python3.6/site-packages/pyhive/hive.py", line 380, in _fetch_more raise ProgrammingError("No result set") sqlalchemy.exc.ProgrammingError: (pyhive.exc.ProgrammingError) No result set [SQL: INSERT INTO TABLE `result`.`new_table` VALUES (%(year)s, %(GDP_rate)s, %(GDP)s)] [parameters: ({'year': 2017, 'GDP_rate': 31, 'GDP': '1.73M'}, {'year': 2018, 'GDP_rate': 30, 'GDP': '1.83M'})] (Background on this error at: http://sqlalche.me/e/f405) ``` actually i don't know why and the result only one dataframe save at hive table if someone knows that the reason plz teach me thank you
2019/11/19
[ "https://Stackoverflow.com/questions/58928062", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12300690/" ]
Kindly add method='multi' for batch insert df.to\_sql("table\_name", con = engine,index=False,method='multi')
A likely pyhive bug. See <https://github.com/dropbox/PyHive/issues/250>. The problem happens when inserting multiple rows.
48,524,013
So i'm starting to use Django but i had some problems trying to run my server. I have two versions of python installed. So in my mysite package i tried to run `python manage.py runserver` but i got this error: ``` Unhandled exception in thread started by <function wrapper at 0x058E1430> Traceback (most recent call last): File "C:\Python27\lib\site-packages\django\utils\autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "C:\Python27\lib\site-packages\django\core\management\commands\runserver.py", line 125, in inner_run self.check(display_num_errors=True) File "C:\Python27\lib\site-packages\django\core\management\base.py", line 359, in check include_deployment_checks=include_deployment_checks, File "C:\Python27\lib\site-packages\django\core\management\base.py", line 346, in _run_checks return checks.run_checks(**kwargs) File "C:\Python27\lib\site-packages\django\core\checks\registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "C:\Python27\lib\site-packages\django\core\checks\urls.py", line 16, in check_url_config return check_resolver(resolver) File "C:\Python27\lib\site-packages\django\core\checks\urls.py", line 26, in check_resolver return check_method() File "C:\Python27\lib\site-packages\django\urls\resolvers.py", line 254, in check for pattern in self.url_patterns: File "C:\Python27\lib\site-packages\django\utils\functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Python27\lib\site-packages\django\urls\resolvers.py", line 405, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Python27\lib\site-packages\django\utils\functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Python27\lib\site-packages\django\urls\resolvers.py", line 398, in urlconf_module return import_module(self.urlconf_name) File "C:\Python27\lib\importlib\__init__.py", line 37, in import_module __import__(name) File "C:\Users\Davide\Desktop\django-proj\mysite\mysite\urls.py", line 17, in <module> from django.urls import path ImportError: cannot import name path ``` Is it because i have two versions installed?
2018/01/30
[ "https://Stackoverflow.com/questions/48524013", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9217311/" ]
Not sure what django version you are currently using but if you are working with Django 2.0 then python2 wouldn't work ( Cause Django2.0 support only Python 3.4+) So in your case if you are in Django2.0 (assuming you already have installed latest version of python in your machine) then you should run following command. ``` python3 manage.py runserver ``` Or install python3 instead of python2 in your virtual environment. Then hopefully your command ``` python manage.py runserver ``` will work perfectly.
Have you tried to upgrade django with pip or pip3? ``` pip install --upgrade django --user ```
48,524,013
So i'm starting to use Django but i had some problems trying to run my server. I have two versions of python installed. So in my mysite package i tried to run `python manage.py runserver` but i got this error: ``` Unhandled exception in thread started by <function wrapper at 0x058E1430> Traceback (most recent call last): File "C:\Python27\lib\site-packages\django\utils\autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "C:\Python27\lib\site-packages\django\core\management\commands\runserver.py", line 125, in inner_run self.check(display_num_errors=True) File "C:\Python27\lib\site-packages\django\core\management\base.py", line 359, in check include_deployment_checks=include_deployment_checks, File "C:\Python27\lib\site-packages\django\core\management\base.py", line 346, in _run_checks return checks.run_checks(**kwargs) File "C:\Python27\lib\site-packages\django\core\checks\registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "C:\Python27\lib\site-packages\django\core\checks\urls.py", line 16, in check_url_config return check_resolver(resolver) File "C:\Python27\lib\site-packages\django\core\checks\urls.py", line 26, in check_resolver return check_method() File "C:\Python27\lib\site-packages\django\urls\resolvers.py", line 254, in check for pattern in self.url_patterns: File "C:\Python27\lib\site-packages\django\utils\functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Python27\lib\site-packages\django\urls\resolvers.py", line 405, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Python27\lib\site-packages\django\utils\functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Python27\lib\site-packages\django\urls\resolvers.py", line 398, in urlconf_module return import_module(self.urlconf_name) File "C:\Python27\lib\importlib\__init__.py", line 37, in import_module __import__(name) File "C:\Users\Davide\Desktop\django-proj\mysite\mysite\urls.py", line 17, in <module> from django.urls import path ImportError: cannot import name path ``` Is it because i have two versions installed?
2018/01/30
[ "https://Stackoverflow.com/questions/48524013", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9217311/" ]
Not sure what django version you are currently using but if you are working with Django 2.0 then python2 wouldn't work ( Cause Django2.0 support only Python 3.4+) So in your case if you are in Django2.0 (assuming you already have installed latest version of python in your machine) then you should run following command. ``` python3 manage.py runserver ``` Or install python3 instead of python2 in your virtual environment. Then hopefully your command ``` python manage.py runserver ``` will work perfectly.
**You need to upgrade Django** ``` pip install --upgrade django pip3 install --upgrade django ```
29,858,752
I am using selenium with python and have downloaded the chromedriver for my windows computer from this site: <http://chromedriver.storage.googleapis.com/index.html?path=2.15/> After downloading the zip file, I unpacked the zip file to my downloads folder. Then I put the path to the executable binary (C:\Users\michael\Downloads\chromedriver\_win32) into the Environment Variable "Path". However, when I run the following code: ``` from selenium import webdriver driver = webdriver.Chrome() ``` ... I keep getting the following error message: ``` WebDriverException: Message: 'chromedriver' executable needs to be available in the path. Please look at http://docs.seleniumhq.org/download/#thirdPartyDrivers and read up at http://code.google.com/p/selenium/wiki/ChromeDriver ``` But - as explained above - the executable is(!) in the path ... what is going on here?
2015/04/24
[ "https://Stackoverflow.com/questions/29858752", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4474430/" ]
*For Linux and OSX* **Step 1: Download chromedriver** ``` # You can find more recent/older versions at http://chromedriver.storage.googleapis.com/ # Also make sure to pick the right driver, based on your Operating System wget http://chromedriver.storage.googleapis.com/81.0.4044.69/chromedriver_mac64.zip ``` For debian: `wget https://chromedriver.storage.googleapis.com/2.41/chromedriver_linux64.zip` **Step 2: Add chromedriver to `/usr/local/bin`** ``` unzip chromedriver_mac64.zip sudo mv chromedriver /usr/local/bin sudo chown root:root /usr/local/bin/chromedriver sudo chmod +x /usr/local/bin/chromedriver ``` --- You should now be able to run ``` from selenium import webdriver browser = webdriver.Chrome() browser.get('http://localhost:8000') ``` without any issues
Had this issue with Mac Mojave running Robot test framework and Chrome 77. This solved the problem. Kudos @Navarasu for pointing me to the right track. ``` $ pip install webdriver-manager --user # install webdriver-manager lib for python $ python # open python prompt ``` Next, in python prompt: ``` from selenium import webdriver from webdriver_manager.chrome import ChromeDriverManager driver = webdriver.Chrome(ChromeDriverManager().install()) # ctrl+d to exit ``` This leads to the following error: ``` Checking for mac64 chromedriver:xx.x.xxxx.xx in cache There is no cached driver. Downloading new one... Trying to download new driver from http://chromedriver.storage.googleapis.com/xx.x.xxxx.xx/chromedriver_mac64.zip ... TypeError: makedirs() got an unexpected keyword argument 'exist_ok' ``` * I now got the newest download link + Download and unzip chromedriver to where you want + For example: `~/chromedriver/chromedriver` Open `~/.bash_profile` with editor and add: ``` export PATH="$HOME/chromedriver:$PATH" ``` Open new terminal window, ta-da
29,858,752
I am using selenium with python and have downloaded the chromedriver for my windows computer from this site: <http://chromedriver.storage.googleapis.com/index.html?path=2.15/> After downloading the zip file, I unpacked the zip file to my downloads folder. Then I put the path to the executable binary (C:\Users\michael\Downloads\chromedriver\_win32) into the Environment Variable "Path". However, when I run the following code: ``` from selenium import webdriver driver = webdriver.Chrome() ``` ... I keep getting the following error message: ``` WebDriverException: Message: 'chromedriver' executable needs to be available in the path. Please look at http://docs.seleniumhq.org/download/#thirdPartyDrivers and read up at http://code.google.com/p/selenium/wiki/ChromeDriver ``` But - as explained above - the executable is(!) in the path ... what is going on here?
2015/04/24
[ "https://Stackoverflow.com/questions/29858752", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4474430/" ]
You can test if it actually is in the PATH, if you open a cmd and type in `chromedriver` (assuming your chromedriver executable is still named like this) and hit Enter. If `Starting ChromeDriver 2.15.322448` is appearing, the PATH is set appropriately and there is something else going wrong. Alternatively you can use a direct path to the chromedriver like this: ``` driver = webdriver.Chrome('/path/to/chromedriver') ``` So in your specific case: ``` driver = webdriver.Chrome("C:/Users/michael/Downloads/chromedriver_win32/chromedriver.exe") ```
Could try to restart computer if it doesn't work after you are quite sure that PATH is set correctly. In my case on windows 7, I always got the error on WebDriverException: Message: for chromedriver, gecodriver, IEDriverServer. I am pretty sure that i have correct path. Restart computer, all work
29,858,752
I am using selenium with python and have downloaded the chromedriver for my windows computer from this site: <http://chromedriver.storage.googleapis.com/index.html?path=2.15/> After downloading the zip file, I unpacked the zip file to my downloads folder. Then I put the path to the executable binary (C:\Users\michael\Downloads\chromedriver\_win32) into the Environment Variable "Path". However, when I run the following code: ``` from selenium import webdriver driver = webdriver.Chrome() ``` ... I keep getting the following error message: ``` WebDriverException: Message: 'chromedriver' executable needs to be available in the path. Please look at http://docs.seleniumhq.org/download/#thirdPartyDrivers and read up at http://code.google.com/p/selenium/wiki/ChromeDriver ``` But - as explained above - the executable is(!) in the path ... what is going on here?
2015/04/24
[ "https://Stackoverflow.com/questions/29858752", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4474430/" ]
When you unzip chromedriver, please do specify an exact location so that you can trace it later. Below, you are getting the right chromedriver for your OS, and then unzipping it to an exact location, which could be provided as argument later on in your code. `wget http://chromedriver.storage.googleapis.com/2.10/chromedriver_linux64.zip unzip chromedriver_linux64.zip -d /home/virtualenv/python2.7.9/`
In my case, this error disappears when I have copied chromedriver file to c:\Windows folder. Its because windows directory is in the path which python script check for chromedriver availability.
29,858,752
I am using selenium with python and have downloaded the chromedriver for my windows computer from this site: <http://chromedriver.storage.googleapis.com/index.html?path=2.15/> After downloading the zip file, I unpacked the zip file to my downloads folder. Then I put the path to the executable binary (C:\Users\michael\Downloads\chromedriver\_win32) into the Environment Variable "Path". However, when I run the following code: ``` from selenium import webdriver driver = webdriver.Chrome() ``` ... I keep getting the following error message: ``` WebDriverException: Message: 'chromedriver' executable needs to be available in the path. Please look at http://docs.seleniumhq.org/download/#thirdPartyDrivers and read up at http://code.google.com/p/selenium/wiki/ChromeDriver ``` But - as explained above - the executable is(!) in the path ... what is going on here?
2015/04/24
[ "https://Stackoverflow.com/questions/29858752", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4474430/" ]
After testing to check that ChromeDriver is installed ``` chromedriver ``` You should see ``` Starting ChromeDriver version.number ChromeDriver was successful ``` Check the path of the ChromeDriver path ``` which chromedriver ``` Use the Path in your code ``` ... from selenium import webdriver options = Options() options.headless = True options.add_argument('windows-size=1920x1080') path = '/usr/local/bin/chromedriver' driver = webdriver.Chrome(path, options=options) ```
For mac osx users ``` brew tap homebrew/cask brew cask install chromedriver ```
29,858,752
I am using selenium with python and have downloaded the chromedriver for my windows computer from this site: <http://chromedriver.storage.googleapis.com/index.html?path=2.15/> After downloading the zip file, I unpacked the zip file to my downloads folder. Then I put the path to the executable binary (C:\Users\michael\Downloads\chromedriver\_win32) into the Environment Variable "Path". However, when I run the following code: ``` from selenium import webdriver driver = webdriver.Chrome() ``` ... I keep getting the following error message: ``` WebDriverException: Message: 'chromedriver' executable needs to be available in the path. Please look at http://docs.seleniumhq.org/download/#thirdPartyDrivers and read up at http://code.google.com/p/selenium/wiki/ChromeDriver ``` But - as explained above - the executable is(!) in the path ... what is going on here?
2015/04/24
[ "https://Stackoverflow.com/questions/29858752", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4474430/" ]
You can test if it actually is in the PATH, if you open a cmd and type in `chromedriver` (assuming your chromedriver executable is still named like this) and hit Enter. If `Starting ChromeDriver 2.15.322448` is appearing, the PATH is set appropriately and there is something else going wrong. Alternatively you can use a direct path to the chromedriver like this: ``` driver = webdriver.Chrome('/path/to/chromedriver') ``` So in your specific case: ``` driver = webdriver.Chrome("C:/Users/michael/Downloads/chromedriver_win32/chromedriver.exe") ```
For MAC users: 1. Download Chromedriver: <https://sites.google.com/a/chromium.org/chromedriver/downloads> 2.In Terminal type "sudo nano /etc/paths" 3.Add line with path to Cromedriver as example: "/Users/username/Downloads" 4. Try to run your test again!
29,858,752
I am using selenium with python and have downloaded the chromedriver for my windows computer from this site: <http://chromedriver.storage.googleapis.com/index.html?path=2.15/> After downloading the zip file, I unpacked the zip file to my downloads folder. Then I put the path to the executable binary (C:\Users\michael\Downloads\chromedriver\_win32) into the Environment Variable "Path". However, when I run the following code: ``` from selenium import webdriver driver = webdriver.Chrome() ``` ... I keep getting the following error message: ``` WebDriverException: Message: 'chromedriver' executable needs to be available in the path. Please look at http://docs.seleniumhq.org/download/#thirdPartyDrivers and read up at http://code.google.com/p/selenium/wiki/ChromeDriver ``` But - as explained above - the executable is(!) in the path ... what is going on here?
2015/04/24
[ "https://Stackoverflow.com/questions/29858752", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4474430/" ]
Before you add the chromedriver to your path, make sure it's the same version as your browser. If not, you will need to match versions: either update/downgrade you chrome, and upgrade/downgrade your webdriver. I recommend updating your chrome version as much as possible, and the matching the webdriver. To update chrome: * On the top right corner, click on the three dots. * click `help` -> `About Google Chrome` * update the version and restart chrome Then download the compatible version from here: <http://chromedriver.chromium.org/downloads> . Note: The newest chromedriver doesn't always match the newest version of chrome! Now you can add it to the PATH: 1. create a new folder somewhere in your computer, where you will place your web drivers. I created a folder named `webdrivers` in `C:\Program Files` 2. copy the folder path. In my case it was `C:\Program Files\webdrivers` 3. right click on `this PC` -> `properties`: [![enter image description here](https://i.stack.imgur.com/MhVbt.png)](https://i.stack.imgur.com/MhVbt.png) 4. On the right click `Advanced System settings` 5. Click `Environment Variables` 6. In `System variables`, click on `path` and click `edit` 7. click `new` 8. paste the path you copied before 9. click OK on all the windows Thats it! I used pycharm and I had to reopen it. Maybe its the same with other IDEs or terminals.
**pip install webdriver-manager** If you run script by using python3: **pip3 install webdriver-manager** * Then in script please use: ``` from selenium import webdriver from webdriver_manager.chrome import ChromeDriverManager driver = webdriver.Chrome(ChromeDriverManager().install()) ```
29,858,752
I am using selenium with python and have downloaded the chromedriver for my windows computer from this site: <http://chromedriver.storage.googleapis.com/index.html?path=2.15/> After downloading the zip file, I unpacked the zip file to my downloads folder. Then I put the path to the executable binary (C:\Users\michael\Downloads\chromedriver\_win32) into the Environment Variable "Path". However, when I run the following code: ``` from selenium import webdriver driver = webdriver.Chrome() ``` ... I keep getting the following error message: ``` WebDriverException: Message: 'chromedriver' executable needs to be available in the path. Please look at http://docs.seleniumhq.org/download/#thirdPartyDrivers and read up at http://code.google.com/p/selenium/wiki/ChromeDriver ``` But - as explained above - the executable is(!) in the path ... what is going on here?
2015/04/24
[ "https://Stackoverflow.com/questions/29858752", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4474430/" ]
Another way is download and unzip chromedriver and put '**chromedriver.exe'** in **C:\Program Files\Python38\Scripts** and then you need not to provide the path of driver, just driver= webdriver.Chrome()
Check the path of your chrome driver, it might not get it from there. Simply Copy paste the driver location into the code.
29,858,752
I am using selenium with python and have downloaded the chromedriver for my windows computer from this site: <http://chromedriver.storage.googleapis.com/index.html?path=2.15/> After downloading the zip file, I unpacked the zip file to my downloads folder. Then I put the path to the executable binary (C:\Users\michael\Downloads\chromedriver\_win32) into the Environment Variable "Path". However, when I run the following code: ``` from selenium import webdriver driver = webdriver.Chrome() ``` ... I keep getting the following error message: ``` WebDriverException: Message: 'chromedriver' executable needs to be available in the path. Please look at http://docs.seleniumhq.org/download/#thirdPartyDrivers and read up at http://code.google.com/p/selenium/wiki/ChromeDriver ``` But - as explained above - the executable is(!) in the path ... what is going on here?
2015/04/24
[ "https://Stackoverflow.com/questions/29858752", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4474430/" ]
I see the discussions still talk about the old way of setting up chromedriver by downloading the binary and configuring the path manually. This can be done automatically using [webdriver-manager](https://pypi.org/project/webdriver-manager/) ``` pip install webdriver-manager ``` Now the above code in the question will work simply with below change, ``` from selenium import webdriver from webdriver_manager.chrome import ChromeDriverManager driver = webdriver.Chrome(ChromeDriverManager().install()) ``` The same can be used to set Firefox, Edge and ie binaries.
If you are using remote interpreter you have to also check if its executable PATH is defined. In my case switching from remote Docker interpreter to local interpreter solved the problem.
29,858,752
I am using selenium with python and have downloaded the chromedriver for my windows computer from this site: <http://chromedriver.storage.googleapis.com/index.html?path=2.15/> After downloading the zip file, I unpacked the zip file to my downloads folder. Then I put the path to the executable binary (C:\Users\michael\Downloads\chromedriver\_win32) into the Environment Variable "Path". However, when I run the following code: ``` from selenium import webdriver driver = webdriver.Chrome() ``` ... I keep getting the following error message: ``` WebDriverException: Message: 'chromedriver' executable needs to be available in the path. Please look at http://docs.seleniumhq.org/download/#thirdPartyDrivers and read up at http://code.google.com/p/selenium/wiki/ChromeDriver ``` But - as explained above - the executable is(!) in the path ... what is going on here?
2015/04/24
[ "https://Stackoverflow.com/questions/29858752", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4474430/" ]
When I downloaded chromedriver.exe I just move it in PATH folder C:\Windows\System32\chromedriver.exe and had exact same problem. For me solution was to just change folder in PATH, so I just moved it at Pycharm Community bin folder that was also in PATH. ex: * C:\Windows\System32\chromedriver.exe --> Gave me exception * C:\Program Files\JetBrains\PyCharm Community Edition 2019.1.3\bin\chromedriver.exe --> worked fine
I had this problem on Webdriver 3.8.0 (Chrome 73.0.3683.103 and ChromeDriver 73.0.3683.68). The problem disappeared after I did ``` pip install -U selenium ``` to upgrade Webdriver to 3.14.1.
29,858,752
I am using selenium with python and have downloaded the chromedriver for my windows computer from this site: <http://chromedriver.storage.googleapis.com/index.html?path=2.15/> After downloading the zip file, I unpacked the zip file to my downloads folder. Then I put the path to the executable binary (C:\Users\michael\Downloads\chromedriver\_win32) into the Environment Variable "Path". However, when I run the following code: ``` from selenium import webdriver driver = webdriver.Chrome() ``` ... I keep getting the following error message: ``` WebDriverException: Message: 'chromedriver' executable needs to be available in the path. Please look at http://docs.seleniumhq.org/download/#thirdPartyDrivers and read up at http://code.google.com/p/selenium/wiki/ChromeDriver ``` But - as explained above - the executable is(!) in the path ... what is going on here?
2015/04/24
[ "https://Stackoverflow.com/questions/29858752", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4474430/" ]
*For Linux and OSX* **Step 1: Download chromedriver** ``` # You can find more recent/older versions at http://chromedriver.storage.googleapis.com/ # Also make sure to pick the right driver, based on your Operating System wget http://chromedriver.storage.googleapis.com/81.0.4044.69/chromedriver_mac64.zip ``` For debian: `wget https://chromedriver.storage.googleapis.com/2.41/chromedriver_linux64.zip` **Step 2: Add chromedriver to `/usr/local/bin`** ``` unzip chromedriver_mac64.zip sudo mv chromedriver /usr/local/bin sudo chown root:root /usr/local/bin/chromedriver sudo chmod +x /usr/local/bin/chromedriver ``` --- You should now be able to run ``` from selenium import webdriver browser = webdriver.Chrome() browser.get('http://localhost:8000') ``` without any issues
Before you add the chromedriver to your path, make sure it's the same version as your browser. If not, you will need to match versions: either update/downgrade you chrome, and upgrade/downgrade your webdriver. I recommend updating your chrome version as much as possible, and the matching the webdriver. To update chrome: * On the top right corner, click on the three dots. * click `help` -> `About Google Chrome` * update the version and restart chrome Then download the compatible version from here: <http://chromedriver.chromium.org/downloads> . Note: The newest chromedriver doesn't always match the newest version of chrome! Now you can add it to the PATH: 1. create a new folder somewhere in your computer, where you will place your web drivers. I created a folder named `webdrivers` in `C:\Program Files` 2. copy the folder path. In my case it was `C:\Program Files\webdrivers` 3. right click on `this PC` -> `properties`: [![enter image description here](https://i.stack.imgur.com/MhVbt.png)](https://i.stack.imgur.com/MhVbt.png) 4. On the right click `Advanced System settings` 5. Click `Environment Variables` 6. In `System variables`, click on `path` and click `edit` 7. click `new` 8. paste the path you copied before 9. click OK on all the windows Thats it! I used pycharm and I had to reopen it. Maybe its the same with other IDEs or terminals.
52,566,756
I tried to draw a decision tree in Jupyter Notebook this way. ``` mglearn.plots.plot_animal_tree() ``` But I didn't make it in the right way and got the following error message. ``` --------------------------------------------------------------------------- ModuleNotFoundError Traceback (most recent call last) <ipython-input-65-45733bae690a> in <module>() 1 ----> 2 mglearn.plots.plot_animal_tree() ~\Desktop\introduction_to_ml_with_python\mglearn\plot_animal_tree.py in plot_animal_tree(ax) 4 5 def plot_animal_tree(ax=None): ----> 6 import graphviz 7 if ax is None: 8 ax = plt.gca() ModuleNotFoundError: No module named 'graphviz ``` So I downloaded [Graphviz Windows Packages](https://graphviz.gitlab.io/_pages/Download/Download_windows.html) and installed it. And I added the PATH installed path(C:\Program Files (x86)\Graphviz2.38\bin) to USER PATH and (C:\Program Files (x86)\Graphviz2.38\bin\dot.exe) to SYSTEM PATH. And restarted my PC. But it didnt work. I still can't get it working. So I searched over the internet and got another solution that, I can add the PATH in my code like this. ``` import os os.environ["PATH"] += os.pathsep + 'C:/Program Files (x86)/Graphviz2.38/bin' ``` But it didn't work. So I do not know how to figure it out now. I use the Python3.6 integrated into Anacode3. And I ALSO tried installing graphviz via PIP like this. ``` pip install graphviz ``` BUT it still doesn't work. Hope someone can help me, sincerely.
2018/09/29
[ "https://Stackoverflow.com/questions/52566756", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5574794/" ]
in Anaconda install * python-graphviz * pydot This will fix your problem
In case if your operation system is **Ubuntu** I recommend to try command: ``` sudo apt-get install -y graphviz libgraphviz-dev ```
52,566,756
I tried to draw a decision tree in Jupyter Notebook this way. ``` mglearn.plots.plot_animal_tree() ``` But I didn't make it in the right way and got the following error message. ``` --------------------------------------------------------------------------- ModuleNotFoundError Traceback (most recent call last) <ipython-input-65-45733bae690a> in <module>() 1 ----> 2 mglearn.plots.plot_animal_tree() ~\Desktop\introduction_to_ml_with_python\mglearn\plot_animal_tree.py in plot_animal_tree(ax) 4 5 def plot_animal_tree(ax=None): ----> 6 import graphviz 7 if ax is None: 8 ax = plt.gca() ModuleNotFoundError: No module named 'graphviz ``` So I downloaded [Graphviz Windows Packages](https://graphviz.gitlab.io/_pages/Download/Download_windows.html) and installed it. And I added the PATH installed path(C:\Program Files (x86)\Graphviz2.38\bin) to USER PATH and (C:\Program Files (x86)\Graphviz2.38\bin\dot.exe) to SYSTEM PATH. And restarted my PC. But it didnt work. I still can't get it working. So I searched over the internet and got another solution that, I can add the PATH in my code like this. ``` import os os.environ["PATH"] += os.pathsep + 'C:/Program Files (x86)/Graphviz2.38/bin' ``` But it didn't work. So I do not know how to figure it out now. I use the Python3.6 integrated into Anacode3. And I ALSO tried installing graphviz via PIP like this. ``` pip install graphviz ``` BUT it still doesn't work. Hope someone can help me, sincerely.
2018/09/29
[ "https://Stackoverflow.com/questions/52566756", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5574794/" ]
As @grrr answered above, here is the code: ``` conda install -c anaconda python-graphviz conda install -c anaconda pydot ```
In case if your operation system is **Ubuntu** I recommend to try command: ``` sudo apt-get install -y graphviz libgraphviz-dev ```
52,566,756
I tried to draw a decision tree in Jupyter Notebook this way. ``` mglearn.plots.plot_animal_tree() ``` But I didn't make it in the right way and got the following error message. ``` --------------------------------------------------------------------------- ModuleNotFoundError Traceback (most recent call last) <ipython-input-65-45733bae690a> in <module>() 1 ----> 2 mglearn.plots.plot_animal_tree() ~\Desktop\introduction_to_ml_with_python\mglearn\plot_animal_tree.py in plot_animal_tree(ax) 4 5 def plot_animal_tree(ax=None): ----> 6 import graphviz 7 if ax is None: 8 ax = plt.gca() ModuleNotFoundError: No module named 'graphviz ``` So I downloaded [Graphviz Windows Packages](https://graphviz.gitlab.io/_pages/Download/Download_windows.html) and installed it. And I added the PATH installed path(C:\Program Files (x86)\Graphviz2.38\bin) to USER PATH and (C:\Program Files (x86)\Graphviz2.38\bin\dot.exe) to SYSTEM PATH. And restarted my PC. But it didnt work. I still can't get it working. So I searched over the internet and got another solution that, I can add the PATH in my code like this. ``` import os os.environ["PATH"] += os.pathsep + 'C:/Program Files (x86)/Graphviz2.38/bin' ``` But it didn't work. So I do not know how to figure it out now. I use the Python3.6 integrated into Anacode3. And I ALSO tried installing graphviz via PIP like this. ``` pip install graphviz ``` BUT it still doesn't work. Hope someone can help me, sincerely.
2018/09/29
[ "https://Stackoverflow.com/questions/52566756", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5574794/" ]
In case if your operation system is **Ubuntu** I recommend to try command: ``` sudo apt-get install -y graphviz libgraphviz-dev ```
I know the question has already been answered, but for future readers, I came here with the same jupyter notebook issue; after installing python-graphviz and pydot I still had the same issue. Here's what worked for me: Make sure that the python version of your terminal matches that of the jupyter notebook, so run this both in python in your terminal and then in your juypter notebook. If you are using a conda environment, load the environment before checking the python version. `import sys` `print(sys.version)` If they do not match, i.e. python 3.6.x vs python 3.7.x then give your jupyter notebook the ability to find the version of python you want. `conda install nb_conda_kernels` `conda install ipykernel` and if you are using a conda environment, `python -m ipykernel install --user --name myenv--display-name "Python (myenv)"` where `myenv` is the name of your environment. Then go into your jupyter notebook, and in kernel -> change kernel, select the correct version of python. Fixed the issue!
52,566,756
I tried to draw a decision tree in Jupyter Notebook this way. ``` mglearn.plots.plot_animal_tree() ``` But I didn't make it in the right way and got the following error message. ``` --------------------------------------------------------------------------- ModuleNotFoundError Traceback (most recent call last) <ipython-input-65-45733bae690a> in <module>() 1 ----> 2 mglearn.plots.plot_animal_tree() ~\Desktop\introduction_to_ml_with_python\mglearn\plot_animal_tree.py in plot_animal_tree(ax) 4 5 def plot_animal_tree(ax=None): ----> 6 import graphviz 7 if ax is None: 8 ax = plt.gca() ModuleNotFoundError: No module named 'graphviz ``` So I downloaded [Graphviz Windows Packages](https://graphviz.gitlab.io/_pages/Download/Download_windows.html) and installed it. And I added the PATH installed path(C:\Program Files (x86)\Graphviz2.38\bin) to USER PATH and (C:\Program Files (x86)\Graphviz2.38\bin\dot.exe) to SYSTEM PATH. And restarted my PC. But it didnt work. I still can't get it working. So I searched over the internet and got another solution that, I can add the PATH in my code like this. ``` import os os.environ["PATH"] += os.pathsep + 'C:/Program Files (x86)/Graphviz2.38/bin' ``` But it didn't work. So I do not know how to figure it out now. I use the Python3.6 integrated into Anacode3. And I ALSO tried installing graphviz via PIP like this. ``` pip install graphviz ``` BUT it still doesn't work. Hope someone can help me, sincerely.
2018/09/29
[ "https://Stackoverflow.com/questions/52566756", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5574794/" ]
In case if your operation system is **Ubuntu** I recommend to try command: ``` sudo apt-get install -y graphviz libgraphviz-dev ```
I installed the grphviz package using conda. However, I kept getting "module not found error" even after restart kernel multiple times. Then following the suggestions on this page, I even installed "PyDot", however, it didn't really help. Finally, I installed the package using ``` pip install graphviz ``` and finally I can import it.
52,566,756
I tried to draw a decision tree in Jupyter Notebook this way. ``` mglearn.plots.plot_animal_tree() ``` But I didn't make it in the right way and got the following error message. ``` --------------------------------------------------------------------------- ModuleNotFoundError Traceback (most recent call last) <ipython-input-65-45733bae690a> in <module>() 1 ----> 2 mglearn.plots.plot_animal_tree() ~\Desktop\introduction_to_ml_with_python\mglearn\plot_animal_tree.py in plot_animal_tree(ax) 4 5 def plot_animal_tree(ax=None): ----> 6 import graphviz 7 if ax is None: 8 ax = plt.gca() ModuleNotFoundError: No module named 'graphviz ``` So I downloaded [Graphviz Windows Packages](https://graphviz.gitlab.io/_pages/Download/Download_windows.html) and installed it. And I added the PATH installed path(C:\Program Files (x86)\Graphviz2.38\bin) to USER PATH and (C:\Program Files (x86)\Graphviz2.38\bin\dot.exe) to SYSTEM PATH. And restarted my PC. But it didnt work. I still can't get it working. So I searched over the internet and got another solution that, I can add the PATH in my code like this. ``` import os os.environ["PATH"] += os.pathsep + 'C:/Program Files (x86)/Graphviz2.38/bin' ``` But it didn't work. So I do not know how to figure it out now. I use the Python3.6 integrated into Anacode3. And I ALSO tried installing graphviz via PIP like this. ``` pip install graphviz ``` BUT it still doesn't work. Hope someone can help me, sincerely.
2018/09/29
[ "https://Stackoverflow.com/questions/52566756", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5574794/" ]
in Anaconda install * python-graphviz * pydot This will fix your problem
As @grrr answered above, here is the code: ``` conda install -c anaconda python-graphviz conda install -c anaconda pydot ```
52,566,756
I tried to draw a decision tree in Jupyter Notebook this way. ``` mglearn.plots.plot_animal_tree() ``` But I didn't make it in the right way and got the following error message. ``` --------------------------------------------------------------------------- ModuleNotFoundError Traceback (most recent call last) <ipython-input-65-45733bae690a> in <module>() 1 ----> 2 mglearn.plots.plot_animal_tree() ~\Desktop\introduction_to_ml_with_python\mglearn\plot_animal_tree.py in plot_animal_tree(ax) 4 5 def plot_animal_tree(ax=None): ----> 6 import graphviz 7 if ax is None: 8 ax = plt.gca() ModuleNotFoundError: No module named 'graphviz ``` So I downloaded [Graphviz Windows Packages](https://graphviz.gitlab.io/_pages/Download/Download_windows.html) and installed it. And I added the PATH installed path(C:\Program Files (x86)\Graphviz2.38\bin) to USER PATH and (C:\Program Files (x86)\Graphviz2.38\bin\dot.exe) to SYSTEM PATH. And restarted my PC. But it didnt work. I still can't get it working. So I searched over the internet and got another solution that, I can add the PATH in my code like this. ``` import os os.environ["PATH"] += os.pathsep + 'C:/Program Files (x86)/Graphviz2.38/bin' ``` But it didn't work. So I do not know how to figure it out now. I use the Python3.6 integrated into Anacode3. And I ALSO tried installing graphviz via PIP like this. ``` pip install graphviz ``` BUT it still doesn't work. Hope someone can help me, sincerely.
2018/09/29
[ "https://Stackoverflow.com/questions/52566756", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5574794/" ]
in Anaconda install * python-graphviz * pydot This will fix your problem
I know the question has already been answered, but for future readers, I came here with the same jupyter notebook issue; after installing python-graphviz and pydot I still had the same issue. Here's what worked for me: Make sure that the python version of your terminal matches that of the jupyter notebook, so run this both in python in your terminal and then in your juypter notebook. If you are using a conda environment, load the environment before checking the python version. `import sys` `print(sys.version)` If they do not match, i.e. python 3.6.x vs python 3.7.x then give your jupyter notebook the ability to find the version of python you want. `conda install nb_conda_kernels` `conda install ipykernel` and if you are using a conda environment, `python -m ipykernel install --user --name myenv--display-name "Python (myenv)"` where `myenv` is the name of your environment. Then go into your jupyter notebook, and in kernel -> change kernel, select the correct version of python. Fixed the issue!
52,566,756
I tried to draw a decision tree in Jupyter Notebook this way. ``` mglearn.plots.plot_animal_tree() ``` But I didn't make it in the right way and got the following error message. ``` --------------------------------------------------------------------------- ModuleNotFoundError Traceback (most recent call last) <ipython-input-65-45733bae690a> in <module>() 1 ----> 2 mglearn.plots.plot_animal_tree() ~\Desktop\introduction_to_ml_with_python\mglearn\plot_animal_tree.py in plot_animal_tree(ax) 4 5 def plot_animal_tree(ax=None): ----> 6 import graphviz 7 if ax is None: 8 ax = plt.gca() ModuleNotFoundError: No module named 'graphviz ``` So I downloaded [Graphviz Windows Packages](https://graphviz.gitlab.io/_pages/Download/Download_windows.html) and installed it. And I added the PATH installed path(C:\Program Files (x86)\Graphviz2.38\bin) to USER PATH and (C:\Program Files (x86)\Graphviz2.38\bin\dot.exe) to SYSTEM PATH. And restarted my PC. But it didnt work. I still can't get it working. So I searched over the internet and got another solution that, I can add the PATH in my code like this. ``` import os os.environ["PATH"] += os.pathsep + 'C:/Program Files (x86)/Graphviz2.38/bin' ``` But it didn't work. So I do not know how to figure it out now. I use the Python3.6 integrated into Anacode3. And I ALSO tried installing graphviz via PIP like this. ``` pip install graphviz ``` BUT it still doesn't work. Hope someone can help me, sincerely.
2018/09/29
[ "https://Stackoverflow.com/questions/52566756", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5574794/" ]
in Anaconda install * python-graphviz * pydot This will fix your problem
I installed the grphviz package using conda. However, I kept getting "module not found error" even after restart kernel multiple times. Then following the suggestions on this page, I even installed "PyDot", however, it didn't really help. Finally, I installed the package using ``` pip install graphviz ``` and finally I can import it.
52,566,756
I tried to draw a decision tree in Jupyter Notebook this way. ``` mglearn.plots.plot_animal_tree() ``` But I didn't make it in the right way and got the following error message. ``` --------------------------------------------------------------------------- ModuleNotFoundError Traceback (most recent call last) <ipython-input-65-45733bae690a> in <module>() 1 ----> 2 mglearn.plots.plot_animal_tree() ~\Desktop\introduction_to_ml_with_python\mglearn\plot_animal_tree.py in plot_animal_tree(ax) 4 5 def plot_animal_tree(ax=None): ----> 6 import graphviz 7 if ax is None: 8 ax = plt.gca() ModuleNotFoundError: No module named 'graphviz ``` So I downloaded [Graphviz Windows Packages](https://graphviz.gitlab.io/_pages/Download/Download_windows.html) and installed it. And I added the PATH installed path(C:\Program Files (x86)\Graphviz2.38\bin) to USER PATH and (C:\Program Files (x86)\Graphviz2.38\bin\dot.exe) to SYSTEM PATH. And restarted my PC. But it didnt work. I still can't get it working. So I searched over the internet and got another solution that, I can add the PATH in my code like this. ``` import os os.environ["PATH"] += os.pathsep + 'C:/Program Files (x86)/Graphviz2.38/bin' ``` But it didn't work. So I do not know how to figure it out now. I use the Python3.6 integrated into Anacode3. And I ALSO tried installing graphviz via PIP like this. ``` pip install graphviz ``` BUT it still doesn't work. Hope someone can help me, sincerely.
2018/09/29
[ "https://Stackoverflow.com/questions/52566756", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5574794/" ]
As @grrr answered above, here is the code: ``` conda install -c anaconda python-graphviz conda install -c anaconda pydot ```
I know the question has already been answered, but for future readers, I came here with the same jupyter notebook issue; after installing python-graphviz and pydot I still had the same issue. Here's what worked for me: Make sure that the python version of your terminal matches that of the jupyter notebook, so run this both in python in your terminal and then in your juypter notebook. If you are using a conda environment, load the environment before checking the python version. `import sys` `print(sys.version)` If they do not match, i.e. python 3.6.x vs python 3.7.x then give your jupyter notebook the ability to find the version of python you want. `conda install nb_conda_kernels` `conda install ipykernel` and if you are using a conda environment, `python -m ipykernel install --user --name myenv--display-name "Python (myenv)"` where `myenv` is the name of your environment. Then go into your jupyter notebook, and in kernel -> change kernel, select the correct version of python. Fixed the issue!
52,566,756
I tried to draw a decision tree in Jupyter Notebook this way. ``` mglearn.plots.plot_animal_tree() ``` But I didn't make it in the right way and got the following error message. ``` --------------------------------------------------------------------------- ModuleNotFoundError Traceback (most recent call last) <ipython-input-65-45733bae690a> in <module>() 1 ----> 2 mglearn.plots.plot_animal_tree() ~\Desktop\introduction_to_ml_with_python\mglearn\plot_animal_tree.py in plot_animal_tree(ax) 4 5 def plot_animal_tree(ax=None): ----> 6 import graphviz 7 if ax is None: 8 ax = plt.gca() ModuleNotFoundError: No module named 'graphviz ``` So I downloaded [Graphviz Windows Packages](https://graphviz.gitlab.io/_pages/Download/Download_windows.html) and installed it. And I added the PATH installed path(C:\Program Files (x86)\Graphviz2.38\bin) to USER PATH and (C:\Program Files (x86)\Graphviz2.38\bin\dot.exe) to SYSTEM PATH. And restarted my PC. But it didnt work. I still can't get it working. So I searched over the internet and got another solution that, I can add the PATH in my code like this. ``` import os os.environ["PATH"] += os.pathsep + 'C:/Program Files (x86)/Graphviz2.38/bin' ``` But it didn't work. So I do not know how to figure it out now. I use the Python3.6 integrated into Anacode3. And I ALSO tried installing graphviz via PIP like this. ``` pip install graphviz ``` BUT it still doesn't work. Hope someone can help me, sincerely.
2018/09/29
[ "https://Stackoverflow.com/questions/52566756", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5574794/" ]
As @grrr answered above, here is the code: ``` conda install -c anaconda python-graphviz conda install -c anaconda pydot ```
I installed the grphviz package using conda. However, I kept getting "module not found error" even after restart kernel multiple times. Then following the suggestions on this page, I even installed "PyDot", however, it didn't really help. Finally, I installed the package using ``` pip install graphviz ``` and finally I can import it.
58,838,759
I have multiple csv files containing item and invoicing data (proprietary and edifact files). They look roughly like this: ``` 0001;12345;Item1 0002;12345;EUR;1.99 0003;12345;EUR;1.99 ``` The always start with 0001 but do not necessarily have more than one row. How do I group them efficiently? Currently I read them line by line, split them by ';', and add them all to one list until the first value is again 0001. Should I first split them using regular expressions and then continue parsing? What is the most pythonic way?
2019/11/13
[ "https://Stackoverflow.com/questions/58838759", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11766755/" ]
With my knowledge of EDIFACT-style files, they're basically hierarchical, with some row code (`0001` here) acting as a "start-of-group" symbol. So yeah – something like this is a fast, Pythonic way to group by that symbol. (`input_file` can just as well be a disk file, but for the sake of a self-contained example, it's an `io.StringIO()`.) This particular implementation has the extra feature of crashing if the file smells invalid, i.e. doesn't start with an `0001` record. ```py import io from pprint import pprint import csv input_file = io.StringIO(""" 0001;12345;Item1 0002;12345;EUR;1.99 0003;12345;EUR;1.99 0001;12345;Item2 0002;12345;EUR;1.99 0003;12345;EUR;1.99 0001;12345;Item3 0002;12345;EUR;1.99 0003;12345;EUR;1.99 0001;12345;Item4 0002;12345;EUR;1.99 0003;12345;EUR;1.99 """.strip()) groups = [] for line in csv.reader(input_file, delimiter=";"): if line[0] == "0001": groups.append([]) groups[-1].append(line) pprint(groups) ``` The output is a list of lists of split rows: ``` [[['0001', '12345', 'Item1'], ['0002', '12345', 'EUR', '1.99'], ['0003', '12345', 'EUR', '1.99']], [['0001', '12345', 'Item2'], ['0002', '12345', 'EUR', '1.99'], ['0003', '12345', 'EUR', '1.99']], [['0001', '12345', 'Item3'], ['0002', '12345', 'EUR', '1.99'], ['0003', '12345', 'EUR', '1.99']], [['0001', '12345', 'Item4'], ['0002', '12345', 'EUR', '1.99'], ['0003', '12345', 'EUR', '1.99']]] ```
If the files have the same columns, it would be interesting to read it in dataframes, and append to each one this thing. `df1= pd.read_csv(Path+File1, sep=';') df2= pd.read_csv(Path+File2, sep=';') df2.append(df1, ignore_index = True, sort=False).` Afterward, you can just sort by the first column that contains the '0001' `df.sort_values(by=['col1'], ascending=False)`
52,676,660
I am totally new to Jupyter Notebook. Currently, I am using the notebook with R and it is working well. Now, I tried to use it with Python and I receive the following error. > > [I 09:00:52.947 NotebookApp] KernelRestarter: restarting kernel (4/5), > new random ports > > > Traceback (most recent call last): > > > File "/usr/lib/python3.6/runpy.py", line 193, in \_run\_module\_as\_main > "main", mod\_spec) > > > File "/usr/lib/python3.6/runpy.py", line 85, in \_run\_code exec(code, > run\_globals) > > > File > "/home/frey/.local/lib/python3.6/site-packages/ipykernel\_launcher.py", > line 15, in from ipykernel import kernelapp as app > > > File > "/home/frey/.local/lib/python3.6/site-packages/ipykernel/init.py", > line 2, in from .connect import \* > > > File > "/home/frey/.local/lib/python3.6/site-packages/ipykernel/connect.py", > line 13, in from IPython.core.profiledir import ProfileDir > > > File "/home/frey/.local/lib/python3.6/site-packages/IPython/init.py", > line 55, in from .terminal.embed import embed > > > File > "/home/frey/.local/lib/python3.6/site-packages/IPython/terminal/embed.py", > line 16, in from IPython.terminal.interactiveshell import > TerminalInteractiveShell > > > File > "/home/frey/.local/lib/python3.6/site-packages/IPython/terminal/interactiveshell.py", > line 20, in from prompt\_toolkit.formatted\_text import PygmentsTokens > ModuleNotFoundError: No module named 'prompt\_toolkit.formatted\_text' > > > [W 09:00:55.956 NotebookApp] KernelRestarter: restart failed [W > 09:00:55.956 NotebookApp] Kernel 24117cd7-38e5-4978-8bda-d1b84f498051 > died, removing from map. > > > Hopefully, someone can help me.
2018/10/06
[ "https://Stackoverflow.com/questions/52676660", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10464893/" ]
> > ipython` 7.0.1 has requirement prompt-toolkit<2.1.0,>=2.0.0, but you'll have prompt-toolkit 1.0.15 which is incompatible > > > <https://github.com/jupyter/jupyter_console/issues/158> > > > Upgrading `prompt-toolkit` will fix the problem. ``` pip install --upgrade prompt-toolkit ```
It's more stable to create a kernel with an Anaconda virtualenv. Follow these steps. 1. Execute Anaconda prompt. 2. Type `conda create --name $ENVIRONMENT_NAME R -y` 3. Type `conda activate $ENVIRONMENT_NAME` 4. Type `python -m ipykernel install` 5. Type `ipython kernel install --user --name $ENVIRONMENT_NAME` Then, you'll have a new jupyter kernel named 'R' with R installed.
52,676,660
I am totally new to Jupyter Notebook. Currently, I am using the notebook with R and it is working well. Now, I tried to use it with Python and I receive the following error. > > [I 09:00:52.947 NotebookApp] KernelRestarter: restarting kernel (4/5), > new random ports > > > Traceback (most recent call last): > > > File "/usr/lib/python3.6/runpy.py", line 193, in \_run\_module\_as\_main > "main", mod\_spec) > > > File "/usr/lib/python3.6/runpy.py", line 85, in \_run\_code exec(code, > run\_globals) > > > File > "/home/frey/.local/lib/python3.6/site-packages/ipykernel\_launcher.py", > line 15, in from ipykernel import kernelapp as app > > > File > "/home/frey/.local/lib/python3.6/site-packages/ipykernel/init.py", > line 2, in from .connect import \* > > > File > "/home/frey/.local/lib/python3.6/site-packages/ipykernel/connect.py", > line 13, in from IPython.core.profiledir import ProfileDir > > > File "/home/frey/.local/lib/python3.6/site-packages/IPython/init.py", > line 55, in from .terminal.embed import embed > > > File > "/home/frey/.local/lib/python3.6/site-packages/IPython/terminal/embed.py", > line 16, in from IPython.terminal.interactiveshell import > TerminalInteractiveShell > > > File > "/home/frey/.local/lib/python3.6/site-packages/IPython/terminal/interactiveshell.py", > line 20, in from prompt\_toolkit.formatted\_text import PygmentsTokens > ModuleNotFoundError: No module named 'prompt\_toolkit.formatted\_text' > > > [W 09:00:55.956 NotebookApp] KernelRestarter: restart failed [W > 09:00:55.956 NotebookApp] Kernel 24117cd7-38e5-4978-8bda-d1b84f498051 > died, removing from map. > > > Hopefully, someone can help me.
2018/10/06
[ "https://Stackoverflow.com/questions/52676660", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10464893/" ]
> > ipython` 7.0.1 has requirement prompt-toolkit<2.1.0,>=2.0.0, but you'll have prompt-toolkit 1.0.15 which is incompatible > > > <https://github.com/jupyter/jupyter_console/issues/158> > > > Upgrading `prompt-toolkit` will fix the problem. ``` pip install --upgrade prompt-toolkit ```
I had the same problem, I fixed in the way its say in Github: <https://github.com/jupyter/notebook/issues/4079> * open Anaconda Prompt typing ``` python -m ipykernel install --user ```
52,676,660
I am totally new to Jupyter Notebook. Currently, I am using the notebook with R and it is working well. Now, I tried to use it with Python and I receive the following error. > > [I 09:00:52.947 NotebookApp] KernelRestarter: restarting kernel (4/5), > new random ports > > > Traceback (most recent call last): > > > File "/usr/lib/python3.6/runpy.py", line 193, in \_run\_module\_as\_main > "main", mod\_spec) > > > File "/usr/lib/python3.6/runpy.py", line 85, in \_run\_code exec(code, > run\_globals) > > > File > "/home/frey/.local/lib/python3.6/site-packages/ipykernel\_launcher.py", > line 15, in from ipykernel import kernelapp as app > > > File > "/home/frey/.local/lib/python3.6/site-packages/ipykernel/init.py", > line 2, in from .connect import \* > > > File > "/home/frey/.local/lib/python3.6/site-packages/ipykernel/connect.py", > line 13, in from IPython.core.profiledir import ProfileDir > > > File "/home/frey/.local/lib/python3.6/site-packages/IPython/init.py", > line 55, in from .terminal.embed import embed > > > File > "/home/frey/.local/lib/python3.6/site-packages/IPython/terminal/embed.py", > line 16, in from IPython.terminal.interactiveshell import > TerminalInteractiveShell > > > File > "/home/frey/.local/lib/python3.6/site-packages/IPython/terminal/interactiveshell.py", > line 20, in from prompt\_toolkit.formatted\_text import PygmentsTokens > ModuleNotFoundError: No module named 'prompt\_toolkit.formatted\_text' > > > [W 09:00:55.956 NotebookApp] KernelRestarter: restart failed [W > 09:00:55.956 NotebookApp] Kernel 24117cd7-38e5-4978-8bda-d1b84f498051 > died, removing from map. > > > Hopefully, someone can help me.
2018/10/06
[ "https://Stackoverflow.com/questions/52676660", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10464893/" ]
> > ipython` 7.0.1 has requirement prompt-toolkit<2.1.0,>=2.0.0, but you'll have prompt-toolkit 1.0.15 which is incompatible > > > <https://github.com/jupyter/jupyter_console/issues/158> > > > Upgrading `prompt-toolkit` will fix the problem. ``` pip install --upgrade prompt-toolkit ```
Check your environment variable `Path`! In the system variable `Path` add the following line > > C:\Users\\AppData\Roaming\Python\Python37\Scripts > > >
52,676,660
I am totally new to Jupyter Notebook. Currently, I am using the notebook with R and it is working well. Now, I tried to use it with Python and I receive the following error. > > [I 09:00:52.947 NotebookApp] KernelRestarter: restarting kernel (4/5), > new random ports > > > Traceback (most recent call last): > > > File "/usr/lib/python3.6/runpy.py", line 193, in \_run\_module\_as\_main > "main", mod\_spec) > > > File "/usr/lib/python3.6/runpy.py", line 85, in \_run\_code exec(code, > run\_globals) > > > File > "/home/frey/.local/lib/python3.6/site-packages/ipykernel\_launcher.py", > line 15, in from ipykernel import kernelapp as app > > > File > "/home/frey/.local/lib/python3.6/site-packages/ipykernel/init.py", > line 2, in from .connect import \* > > > File > "/home/frey/.local/lib/python3.6/site-packages/ipykernel/connect.py", > line 13, in from IPython.core.profiledir import ProfileDir > > > File "/home/frey/.local/lib/python3.6/site-packages/IPython/init.py", > line 55, in from .terminal.embed import embed > > > File > "/home/frey/.local/lib/python3.6/site-packages/IPython/terminal/embed.py", > line 16, in from IPython.terminal.interactiveshell import > TerminalInteractiveShell > > > File > "/home/frey/.local/lib/python3.6/site-packages/IPython/terminal/interactiveshell.py", > line 20, in from prompt\_toolkit.formatted\_text import PygmentsTokens > ModuleNotFoundError: No module named 'prompt\_toolkit.formatted\_text' > > > [W 09:00:55.956 NotebookApp] KernelRestarter: restart failed [W > 09:00:55.956 NotebookApp] Kernel 24117cd7-38e5-4978-8bda-d1b84f498051 > died, removing from map. > > > Hopefully, someone can help me.
2018/10/06
[ "https://Stackoverflow.com/questions/52676660", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10464893/" ]
> > ipython` 7.0.1 has requirement prompt-toolkit<2.1.0,>=2.0.0, but you'll have prompt-toolkit 1.0.15 which is incompatible > > > <https://github.com/jupyter/jupyter_console/issues/158> > > > Upgrading `prompt-toolkit` will fix the problem. ``` pip install --upgrade prompt-toolkit ```
First Select your environment name. In my case it was **"env"**. ![img](https://i.stack.imgur.com/LUP3s.png) Then install the jupyter notebook from there. It worked for me.
52,676,660
I am totally new to Jupyter Notebook. Currently, I am using the notebook with R and it is working well. Now, I tried to use it with Python and I receive the following error. > > [I 09:00:52.947 NotebookApp] KernelRestarter: restarting kernel (4/5), > new random ports > > > Traceback (most recent call last): > > > File "/usr/lib/python3.6/runpy.py", line 193, in \_run\_module\_as\_main > "main", mod\_spec) > > > File "/usr/lib/python3.6/runpy.py", line 85, in \_run\_code exec(code, > run\_globals) > > > File > "/home/frey/.local/lib/python3.6/site-packages/ipykernel\_launcher.py", > line 15, in from ipykernel import kernelapp as app > > > File > "/home/frey/.local/lib/python3.6/site-packages/ipykernel/init.py", > line 2, in from .connect import \* > > > File > "/home/frey/.local/lib/python3.6/site-packages/ipykernel/connect.py", > line 13, in from IPython.core.profiledir import ProfileDir > > > File "/home/frey/.local/lib/python3.6/site-packages/IPython/init.py", > line 55, in from .terminal.embed import embed > > > File > "/home/frey/.local/lib/python3.6/site-packages/IPython/terminal/embed.py", > line 16, in from IPython.terminal.interactiveshell import > TerminalInteractiveShell > > > File > "/home/frey/.local/lib/python3.6/site-packages/IPython/terminal/interactiveshell.py", > line 20, in from prompt\_toolkit.formatted\_text import PygmentsTokens > ModuleNotFoundError: No module named 'prompt\_toolkit.formatted\_text' > > > [W 09:00:55.956 NotebookApp] KernelRestarter: restart failed [W > 09:00:55.956 NotebookApp] Kernel 24117cd7-38e5-4978-8bda-d1b84f498051 > died, removing from map. > > > Hopefully, someone can help me.
2018/10/06
[ "https://Stackoverflow.com/questions/52676660", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10464893/" ]
It's more stable to create a kernel with an Anaconda virtualenv. Follow these steps. 1. Execute Anaconda prompt. 2. Type `conda create --name $ENVIRONMENT_NAME R -y` 3. Type `conda activate $ENVIRONMENT_NAME` 4. Type `python -m ipykernel install` 5. Type `ipython kernel install --user --name $ENVIRONMENT_NAME` Then, you'll have a new jupyter kernel named 'R' with R installed.
I had the same problem, I fixed in the way its say in Github: <https://github.com/jupyter/notebook/issues/4079> * open Anaconda Prompt typing ``` python -m ipykernel install --user ```
52,676,660
I am totally new to Jupyter Notebook. Currently, I am using the notebook with R and it is working well. Now, I tried to use it with Python and I receive the following error. > > [I 09:00:52.947 NotebookApp] KernelRestarter: restarting kernel (4/5), > new random ports > > > Traceback (most recent call last): > > > File "/usr/lib/python3.6/runpy.py", line 193, in \_run\_module\_as\_main > "main", mod\_spec) > > > File "/usr/lib/python3.6/runpy.py", line 85, in \_run\_code exec(code, > run\_globals) > > > File > "/home/frey/.local/lib/python3.6/site-packages/ipykernel\_launcher.py", > line 15, in from ipykernel import kernelapp as app > > > File > "/home/frey/.local/lib/python3.6/site-packages/ipykernel/init.py", > line 2, in from .connect import \* > > > File > "/home/frey/.local/lib/python3.6/site-packages/ipykernel/connect.py", > line 13, in from IPython.core.profiledir import ProfileDir > > > File "/home/frey/.local/lib/python3.6/site-packages/IPython/init.py", > line 55, in from .terminal.embed import embed > > > File > "/home/frey/.local/lib/python3.6/site-packages/IPython/terminal/embed.py", > line 16, in from IPython.terminal.interactiveshell import > TerminalInteractiveShell > > > File > "/home/frey/.local/lib/python3.6/site-packages/IPython/terminal/interactiveshell.py", > line 20, in from prompt\_toolkit.formatted\_text import PygmentsTokens > ModuleNotFoundError: No module named 'prompt\_toolkit.formatted\_text' > > > [W 09:00:55.956 NotebookApp] KernelRestarter: restart failed [W > 09:00:55.956 NotebookApp] Kernel 24117cd7-38e5-4978-8bda-d1b84f498051 > died, removing from map. > > > Hopefully, someone can help me.
2018/10/06
[ "https://Stackoverflow.com/questions/52676660", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10464893/" ]
It's more stable to create a kernel with an Anaconda virtualenv. Follow these steps. 1. Execute Anaconda prompt. 2. Type `conda create --name $ENVIRONMENT_NAME R -y` 3. Type `conda activate $ENVIRONMENT_NAME` 4. Type `python -m ipykernel install` 5. Type `ipython kernel install --user --name $ENVIRONMENT_NAME` Then, you'll have a new jupyter kernel named 'R' with R installed.
Check your environment variable `Path`! In the system variable `Path` add the following line > > C:\Users\\AppData\Roaming\Python\Python37\Scripts > > >
52,676,660
I am totally new to Jupyter Notebook. Currently, I am using the notebook with R and it is working well. Now, I tried to use it with Python and I receive the following error. > > [I 09:00:52.947 NotebookApp] KernelRestarter: restarting kernel (4/5), > new random ports > > > Traceback (most recent call last): > > > File "/usr/lib/python3.6/runpy.py", line 193, in \_run\_module\_as\_main > "main", mod\_spec) > > > File "/usr/lib/python3.6/runpy.py", line 85, in \_run\_code exec(code, > run\_globals) > > > File > "/home/frey/.local/lib/python3.6/site-packages/ipykernel\_launcher.py", > line 15, in from ipykernel import kernelapp as app > > > File > "/home/frey/.local/lib/python3.6/site-packages/ipykernel/init.py", > line 2, in from .connect import \* > > > File > "/home/frey/.local/lib/python3.6/site-packages/ipykernel/connect.py", > line 13, in from IPython.core.profiledir import ProfileDir > > > File "/home/frey/.local/lib/python3.6/site-packages/IPython/init.py", > line 55, in from .terminal.embed import embed > > > File > "/home/frey/.local/lib/python3.6/site-packages/IPython/terminal/embed.py", > line 16, in from IPython.terminal.interactiveshell import > TerminalInteractiveShell > > > File > "/home/frey/.local/lib/python3.6/site-packages/IPython/terminal/interactiveshell.py", > line 20, in from prompt\_toolkit.formatted\_text import PygmentsTokens > ModuleNotFoundError: No module named 'prompt\_toolkit.formatted\_text' > > > [W 09:00:55.956 NotebookApp] KernelRestarter: restart failed [W > 09:00:55.956 NotebookApp] Kernel 24117cd7-38e5-4978-8bda-d1b84f498051 > died, removing from map. > > > Hopefully, someone can help me.
2018/10/06
[ "https://Stackoverflow.com/questions/52676660", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10464893/" ]
It's more stable to create a kernel with an Anaconda virtualenv. Follow these steps. 1. Execute Anaconda prompt. 2. Type `conda create --name $ENVIRONMENT_NAME R -y` 3. Type `conda activate $ENVIRONMENT_NAME` 4. Type `python -m ipykernel install` 5. Type `ipython kernel install --user --name $ENVIRONMENT_NAME` Then, you'll have a new jupyter kernel named 'R' with R installed.
First Select your environment name. In my case it was **"env"**. ![img](https://i.stack.imgur.com/LUP3s.png) Then install the jupyter notebook from there. It worked for me.
52,676,660
I am totally new to Jupyter Notebook. Currently, I am using the notebook with R and it is working well. Now, I tried to use it with Python and I receive the following error. > > [I 09:00:52.947 NotebookApp] KernelRestarter: restarting kernel (4/5), > new random ports > > > Traceback (most recent call last): > > > File "/usr/lib/python3.6/runpy.py", line 193, in \_run\_module\_as\_main > "main", mod\_spec) > > > File "/usr/lib/python3.6/runpy.py", line 85, in \_run\_code exec(code, > run\_globals) > > > File > "/home/frey/.local/lib/python3.6/site-packages/ipykernel\_launcher.py", > line 15, in from ipykernel import kernelapp as app > > > File > "/home/frey/.local/lib/python3.6/site-packages/ipykernel/init.py", > line 2, in from .connect import \* > > > File > "/home/frey/.local/lib/python3.6/site-packages/ipykernel/connect.py", > line 13, in from IPython.core.profiledir import ProfileDir > > > File "/home/frey/.local/lib/python3.6/site-packages/IPython/init.py", > line 55, in from .terminal.embed import embed > > > File > "/home/frey/.local/lib/python3.6/site-packages/IPython/terminal/embed.py", > line 16, in from IPython.terminal.interactiveshell import > TerminalInteractiveShell > > > File > "/home/frey/.local/lib/python3.6/site-packages/IPython/terminal/interactiveshell.py", > line 20, in from prompt\_toolkit.formatted\_text import PygmentsTokens > ModuleNotFoundError: No module named 'prompt\_toolkit.formatted\_text' > > > [W 09:00:55.956 NotebookApp] KernelRestarter: restart failed [W > 09:00:55.956 NotebookApp] Kernel 24117cd7-38e5-4978-8bda-d1b84f498051 > died, removing from map. > > > Hopefully, someone can help me.
2018/10/06
[ "https://Stackoverflow.com/questions/52676660", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10464893/" ]
I had the same problem, I fixed in the way its say in Github: <https://github.com/jupyter/notebook/issues/4079> * open Anaconda Prompt typing ``` python -m ipykernel install --user ```
Check your environment variable `Path`! In the system variable `Path` add the following line > > C:\Users\\AppData\Roaming\Python\Python37\Scripts > > >
52,676,660
I am totally new to Jupyter Notebook. Currently, I am using the notebook with R and it is working well. Now, I tried to use it with Python and I receive the following error. > > [I 09:00:52.947 NotebookApp] KernelRestarter: restarting kernel (4/5), > new random ports > > > Traceback (most recent call last): > > > File "/usr/lib/python3.6/runpy.py", line 193, in \_run\_module\_as\_main > "main", mod\_spec) > > > File "/usr/lib/python3.6/runpy.py", line 85, in \_run\_code exec(code, > run\_globals) > > > File > "/home/frey/.local/lib/python3.6/site-packages/ipykernel\_launcher.py", > line 15, in from ipykernel import kernelapp as app > > > File > "/home/frey/.local/lib/python3.6/site-packages/ipykernel/init.py", > line 2, in from .connect import \* > > > File > "/home/frey/.local/lib/python3.6/site-packages/ipykernel/connect.py", > line 13, in from IPython.core.profiledir import ProfileDir > > > File "/home/frey/.local/lib/python3.6/site-packages/IPython/init.py", > line 55, in from .terminal.embed import embed > > > File > "/home/frey/.local/lib/python3.6/site-packages/IPython/terminal/embed.py", > line 16, in from IPython.terminal.interactiveshell import > TerminalInteractiveShell > > > File > "/home/frey/.local/lib/python3.6/site-packages/IPython/terminal/interactiveshell.py", > line 20, in from prompt\_toolkit.formatted\_text import PygmentsTokens > ModuleNotFoundError: No module named 'prompt\_toolkit.formatted\_text' > > > [W 09:00:55.956 NotebookApp] KernelRestarter: restart failed [W > 09:00:55.956 NotebookApp] Kernel 24117cd7-38e5-4978-8bda-d1b84f498051 > died, removing from map. > > > Hopefully, someone can help me.
2018/10/06
[ "https://Stackoverflow.com/questions/52676660", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10464893/" ]
First Select your environment name. In my case it was **"env"**. ![img](https://i.stack.imgur.com/LUP3s.png) Then install the jupyter notebook from there. It worked for me.
Check your environment variable `Path`! In the system variable `Path` add the following line > > C:\Users\\AppData\Roaming\Python\Python37\Scripts > > >
2,623,524
As asked and answered in [this post](https://stackoverflow.com/questions/2595119/python-glob-and-bracket-characters), I need to replace '[' with '[[]', and ']' with '[]]'. I tried to use s.replace(), but as it's not in place change, I ran as follows to get a wrong anwser. ``` path1 = "/Users/smcho/Desktop/bracket/[10,20]" path2 = path1.replace('[','[[]') path3 = path2.replace(']','[]]') pathName = os.path.join(path3, "*.txt") print pathName --> /Users/smcho/Desktop/bracket/[[[]]10,20[]]/*.txt ``` * How can I do the multiple replace in python? * Or how can I replace '[' and ']' at the same time?
2010/04/12
[ "https://Stackoverflow.com/questions/2623524", "https://Stackoverflow.com", "https://Stackoverflow.com/users/260127/" ]
I would use code like ``` path = "/Users/smcho/Desktop/bracket/[10,20]" replacements = {"[": "[[]", "]": "[]]"} new_path = "".join(replacements.get(c, c) for c in path) ```
``` import re path2 = re.sub(r'(\[|\])', r'[\1]', path1) ```
2,623,524
As asked and answered in [this post](https://stackoverflow.com/questions/2595119/python-glob-and-bracket-characters), I need to replace '[' with '[[]', and ']' with '[]]'. I tried to use s.replace(), but as it's not in place change, I ran as follows to get a wrong anwser. ``` path1 = "/Users/smcho/Desktop/bracket/[10,20]" path2 = path1.replace('[','[[]') path3 = path2.replace(']','[]]') pathName = os.path.join(path3, "*.txt") print pathName --> /Users/smcho/Desktop/bracket/[[[]]10,20[]]/*.txt ``` * How can I do the multiple replace in python? * Or how can I replace '[' and ']' at the same time?
2010/04/12
[ "https://Stackoverflow.com/questions/2623524", "https://Stackoverflow.com", "https://Stackoverflow.com/users/260127/" ]
I would use code like ``` path = "/Users/smcho/Desktop/bracket/[10,20]" replacements = {"[": "[[]", "]": "[]]"} new_path = "".join(replacements.get(c, c) for c in path) ```
X = TE$%ST C@"DE specialChars = "@#$%&" for specialChar in specialChars: ``` X = X.replace(specialChar, '') ``` Y = appname1.replace(" ", "") print(Y) TESTCODE
2,623,524
As asked and answered in [this post](https://stackoverflow.com/questions/2595119/python-glob-and-bracket-characters), I need to replace '[' with '[[]', and ']' with '[]]'. I tried to use s.replace(), but as it's not in place change, I ran as follows to get a wrong anwser. ``` path1 = "/Users/smcho/Desktop/bracket/[10,20]" path2 = path1.replace('[','[[]') path3 = path2.replace(']','[]]') pathName = os.path.join(path3, "*.txt") print pathName --> /Users/smcho/Desktop/bracket/[[[]]10,20[]]/*.txt ``` * How can I do the multiple replace in python? * Or how can I replace '[' and ']' at the same time?
2010/04/12
[ "https://Stackoverflow.com/questions/2623524", "https://Stackoverflow.com", "https://Stackoverflow.com/users/260127/" ]
I would use code like ``` path = "/Users/smcho/Desktop/bracket/[10,20]" replacements = {"[": "[[]", "]": "[]]"} new_path = "".join(replacements.get(c, c) for c in path) ```
There is also this generic python multiple replace recipe: [Single pass multiple replace](http://code.activestate.com/recipes/81330-single-pass-multiple-replace/)
2,623,524
As asked and answered in [this post](https://stackoverflow.com/questions/2595119/python-glob-and-bracket-characters), I need to replace '[' with '[[]', and ']' with '[]]'. I tried to use s.replace(), but as it's not in place change, I ran as follows to get a wrong anwser. ``` path1 = "/Users/smcho/Desktop/bracket/[10,20]" path2 = path1.replace('[','[[]') path3 = path2.replace(']','[]]') pathName = os.path.join(path3, "*.txt") print pathName --> /Users/smcho/Desktop/bracket/[[[]]10,20[]]/*.txt ``` * How can I do the multiple replace in python? * Or how can I replace '[' and ']' at the same time?
2010/04/12
[ "https://Stackoverflow.com/questions/2623524", "https://Stackoverflow.com", "https://Stackoverflow.com/users/260127/" ]
There is also this generic python multiple replace recipe: [Single pass multiple replace](http://code.activestate.com/recipes/81330-single-pass-multiple-replace/)
Or, to avoid regex, I would replace the opening bracket with a unique string, then replace the closing bracket and then replace the unique string - maybe a round about way, but to my mind it looks simpler - only a test would say if it is faster. Also, I'd tend to reuse the same name. i.e. ``` path1 = "/Users/smcho/Desktop/bracket/[10,20]" path1 = path1.replace('[','*UNIQUE*') path1 = path1.replace(']','[]]') path1 = path1.replace('*UNIQUE*','[[]') pathName = os.path.join(path1, "*.txt") ```
2,623,524
As asked and answered in [this post](https://stackoverflow.com/questions/2595119/python-glob-and-bracket-characters), I need to replace '[' with '[[]', and ']' with '[]]'. I tried to use s.replace(), but as it's not in place change, I ran as follows to get a wrong anwser. ``` path1 = "/Users/smcho/Desktop/bracket/[10,20]" path2 = path1.replace('[','[[]') path3 = path2.replace(']','[]]') pathName = os.path.join(path3, "*.txt") print pathName --> /Users/smcho/Desktop/bracket/[[[]]10,20[]]/*.txt ``` * How can I do the multiple replace in python? * Or how can I replace '[' and ']' at the same time?
2010/04/12
[ "https://Stackoverflow.com/questions/2623524", "https://Stackoverflow.com", "https://Stackoverflow.com/users/260127/" ]
``` import re path2 = re.sub(r'(\[|])', r'[\1]', path) ``` Explanation: `\[|]` will match a bracket (opening or closing). Placing it in the parentheses will make it capture into a group. Then in the replacement string, `\1` will be substituted with the content of the group.
Or, to avoid regex, I would replace the opening bracket with a unique string, then replace the closing bracket and then replace the unique string - maybe a round about way, but to my mind it looks simpler - only a test would say if it is faster. Also, I'd tend to reuse the same name. i.e. ``` path1 = "/Users/smcho/Desktop/bracket/[10,20]" path1 = path1.replace('[','*UNIQUE*') path1 = path1.replace(']','[]]') path1 = path1.replace('*UNIQUE*','[[]') pathName = os.path.join(path1, "*.txt") ```
2,623,524
As asked and answered in [this post](https://stackoverflow.com/questions/2595119/python-glob-and-bracket-characters), I need to replace '[' with '[[]', and ']' with '[]]'. I tried to use s.replace(), but as it's not in place change, I ran as follows to get a wrong anwser. ``` path1 = "/Users/smcho/Desktop/bracket/[10,20]" path2 = path1.replace('[','[[]') path3 = path2.replace(']','[]]') pathName = os.path.join(path3, "*.txt") print pathName --> /Users/smcho/Desktop/bracket/[[[]]10,20[]]/*.txt ``` * How can I do the multiple replace in python? * Or how can I replace '[' and ']' at the same time?
2010/04/12
[ "https://Stackoverflow.com/questions/2623524", "https://Stackoverflow.com", "https://Stackoverflow.com/users/260127/" ]
``` import re path2 = re.sub(r'(\[|])', r'[\1]', path) ``` Explanation: `\[|]` will match a bracket (opening or closing). Placing it in the parentheses will make it capture into a group. Then in the replacement string, `\1` will be substituted with the content of the group.
``` import re path2 = re.sub(r'(\[|\])', r'[\1]', path1) ```
2,623,524
As asked and answered in [this post](https://stackoverflow.com/questions/2595119/python-glob-and-bracket-characters), I need to replace '[' with '[[]', and ']' with '[]]'. I tried to use s.replace(), but as it's not in place change, I ran as follows to get a wrong anwser. ``` path1 = "/Users/smcho/Desktop/bracket/[10,20]" path2 = path1.replace('[','[[]') path3 = path2.replace(']','[]]') pathName = os.path.join(path3, "*.txt") print pathName --> /Users/smcho/Desktop/bracket/[[[]]10,20[]]/*.txt ``` * How can I do the multiple replace in python? * Or how can I replace '[' and ']' at the same time?
2010/04/12
[ "https://Stackoverflow.com/questions/2623524", "https://Stackoverflow.com", "https://Stackoverflow.com/users/260127/" ]
There is also this generic python multiple replace recipe: [Single pass multiple replace](http://code.activestate.com/recipes/81330-single-pass-multiple-replace/)
X = TE$%ST C@"DE specialChars = "@#$%&" for specialChar in specialChars: ``` X = X.replace(specialChar, '') ``` Y = appname1.replace(" ", "") print(Y) TESTCODE
2,623,524
As asked and answered in [this post](https://stackoverflow.com/questions/2595119/python-glob-and-bracket-characters), I need to replace '[' with '[[]', and ']' with '[]]'. I tried to use s.replace(), but as it's not in place change, I ran as follows to get a wrong anwser. ``` path1 = "/Users/smcho/Desktop/bracket/[10,20]" path2 = path1.replace('[','[[]') path3 = path2.replace(']','[]]') pathName = os.path.join(path3, "*.txt") print pathName --> /Users/smcho/Desktop/bracket/[[[]]10,20[]]/*.txt ``` * How can I do the multiple replace in python? * Or how can I replace '[' and ']' at the same time?
2010/04/12
[ "https://Stackoverflow.com/questions/2623524", "https://Stackoverflow.com", "https://Stackoverflow.com/users/260127/" ]
I would use code like ``` path = "/Users/smcho/Desktop/bracket/[10,20]" replacements = {"[": "[[]", "]": "[]]"} new_path = "".join(replacements.get(c, c) for c in path) ```
Or, to avoid regex, I would replace the opening bracket with a unique string, then replace the closing bracket and then replace the unique string - maybe a round about way, but to my mind it looks simpler - only a test would say if it is faster. Also, I'd tend to reuse the same name. i.e. ``` path1 = "/Users/smcho/Desktop/bracket/[10,20]" path1 = path1.replace('[','*UNIQUE*') path1 = path1.replace(']','[]]') path1 = path1.replace('*UNIQUE*','[[]') pathName = os.path.join(path1, "*.txt") ```
2,623,524
As asked and answered in [this post](https://stackoverflow.com/questions/2595119/python-glob-and-bracket-characters), I need to replace '[' with '[[]', and ']' with '[]]'. I tried to use s.replace(), but as it's not in place change, I ran as follows to get a wrong anwser. ``` path1 = "/Users/smcho/Desktop/bracket/[10,20]" path2 = path1.replace('[','[[]') path3 = path2.replace(']','[]]') pathName = os.path.join(path3, "*.txt") print pathName --> /Users/smcho/Desktop/bracket/[[[]]10,20[]]/*.txt ``` * How can I do the multiple replace in python? * Or how can I replace '[' and ']' at the same time?
2010/04/12
[ "https://Stackoverflow.com/questions/2623524", "https://Stackoverflow.com", "https://Stackoverflow.com/users/260127/" ]
``` import re path2 = re.sub(r'(\[|])', r'[\1]', path) ``` Explanation: `\[|]` will match a bracket (opening or closing). Placing it in the parentheses will make it capture into a group. Then in the replacement string, `\1` will be substituted with the content of the group.
X = TE$%ST C@"DE specialChars = "@#$%&" for specialChar in specialChars: ``` X = X.replace(specialChar, '') ``` Y = appname1.replace(" ", "") print(Y) TESTCODE
2,623,524
As asked and answered in [this post](https://stackoverflow.com/questions/2595119/python-glob-and-bracket-characters), I need to replace '[' with '[[]', and ']' with '[]]'. I tried to use s.replace(), but as it's not in place change, I ran as follows to get a wrong anwser. ``` path1 = "/Users/smcho/Desktop/bracket/[10,20]" path2 = path1.replace('[','[[]') path3 = path2.replace(']','[]]') pathName = os.path.join(path3, "*.txt") print pathName --> /Users/smcho/Desktop/bracket/[[[]]10,20[]]/*.txt ``` * How can I do the multiple replace in python? * Or how can I replace '[' and ']' at the same time?
2010/04/12
[ "https://Stackoverflow.com/questions/2623524", "https://Stackoverflow.com", "https://Stackoverflow.com/users/260127/" ]
There is also this generic python multiple replace recipe: [Single pass multiple replace](http://code.activestate.com/recipes/81330-single-pass-multiple-replace/)
``` import re path2 = re.sub(r'(\[|\])', r'[\1]', path1) ```
41,186,818
The [uuid4()](https://docs.python.org/2/library/uuid.html#uuid.uuid4) function of Python's module `uuid` generates a random UUID, and seems to generate a different one every time: ``` In [1]: import uuid In [2]: uuid.uuid4() Out[2]: UUID('f6c9ad6c-eea0-4049-a7c5-56253bc3e9c0') In [3]: uuid.uuid4() Out[3]: UUID('2fc1b6f9-9052-4564-9be0-777e790af58f') ``` I would like to be able to generate the same random UUID every time I run a script - that is, I'd like to seed the random generator in `uuid4()`. Is there a way to do this? (Or achieve this by some other means)? ### What I've tried so far I've to generate a UUID using the `uuid.UUID()` method with a random 128-bit integer (from a seeded instance of `random.Random()`) as input: ``` import uuid import random rd = random.Random() rd.seed(0) uuid.UUID(rd.getrandbits(128)) ``` However, `UUID()` seems not to accept this as input: ``` Traceback (most recent call last): File "uuid_gen_seed.py", line 6, in <module> uuid.UUID(rd.getrandbits(128)) File "/usr/lib/python2.7/uuid.py", line 133, in __init__ hex = hex.replace('urn:', '').replace('uuid:', '') AttributeError: 'long' object has no attribute 'replace' ``` Any other suggestions?
2016/12/16
[ "https://Stackoverflow.com/questions/41186818", "https://Stackoverflow.com", "https://Stackoverflow.com/users/995862/" ]
[Faker](https://github.com/joke2k/faker "Faker") makes this easy ``` >>> from faker import Faker >>> f1 = Faker() >>> f1.seed(4321) >>> print(f1.uuid4()) cc733c92-6853-15f6-0e49-bec741188ebb >>> print(f1.uuid4()) a41f020c-2d4d-333f-f1d3-979f1043fae0 >>> f1.seed(4321) >>> print(f1.uuid4()) cc733c92-6853-15f6-0e49-bec741188ebb ```
Simple solution based on the answer of @user10229295, with a comment about the seed. The Edit queue was full, so I opened a new answer: ``` import hashlib import uuid seed = 'Type your seed_string here' #Read comment below m = hashlib.md5() m.update(seed.encode('utf-8')) new_uuid = uuid.UUID(m.hexdigest()) ``` **Comment about the string *'seed'***: It will be the seed from which the UUID will be generated: from the same seed string will be always generated the same UUID. You can convert integer with some significance as string, concatenate different strings and use the result as your seed. With this you will have control on the UUID generated, which means you will be able to reproduce your UUID knowing the seed you used: with the same seed, the UUID generated from it will be the same.
41,186,818
The [uuid4()](https://docs.python.org/2/library/uuid.html#uuid.uuid4) function of Python's module `uuid` generates a random UUID, and seems to generate a different one every time: ``` In [1]: import uuid In [2]: uuid.uuid4() Out[2]: UUID('f6c9ad6c-eea0-4049-a7c5-56253bc3e9c0') In [3]: uuid.uuid4() Out[3]: UUID('2fc1b6f9-9052-4564-9be0-777e790af58f') ``` I would like to be able to generate the same random UUID every time I run a script - that is, I'd like to seed the random generator in `uuid4()`. Is there a way to do this? (Or achieve this by some other means)? ### What I've tried so far I've to generate a UUID using the `uuid.UUID()` method with a random 128-bit integer (from a seeded instance of `random.Random()`) as input: ``` import uuid import random rd = random.Random() rd.seed(0) uuid.UUID(rd.getrandbits(128)) ``` However, `UUID()` seems not to accept this as input: ``` Traceback (most recent call last): File "uuid_gen_seed.py", line 6, in <module> uuid.UUID(rd.getrandbits(128)) File "/usr/lib/python2.7/uuid.py", line 133, in __init__ hex = hex.replace('urn:', '').replace('uuid:', '') AttributeError: 'long' object has no attribute 'replace' ``` Any other suggestions?
2016/12/16
[ "https://Stackoverflow.com/questions/41186818", "https://Stackoverflow.com", "https://Stackoverflow.com/users/995862/" ]
[Faker](https://github.com/joke2k/faker "Faker") makes this easy ``` >>> from faker import Faker >>> f1 = Faker() >>> f1.seed(4321) >>> print(f1.uuid4()) cc733c92-6853-15f6-0e49-bec741188ebb >>> print(f1.uuid4()) a41f020c-2d4d-333f-f1d3-979f1043fae0 >>> f1.seed(4321) >>> print(f1.uuid4()) cc733c92-6853-15f6-0e49-bec741188ebb ```
Since the straight-forward solution hasn't been posted yet to generate consistent version 4 UUIDs: ```py import random import uuid rnd = random.Random() rnd.seed(123) # NOTE: Of course don't use a static seed in production random_uuid = uuid.UUID(int=rnd.getrandbits(128), version=4) ``` where you can see then: ``` >>> random_uuid.version 4 ``` This doesn't just "mock" the version information. It creates a proper UUIDv4: > > The version argument is optional; if given, the resulting UUID will have its variant and version number set according to RFC 4122, overriding bits in the given hex, bytes, bytes\_le, fields, or int. > > > [Python 3.8 docs](https://docs.python.org/3/library/uuid.html?highlight=uuid#uuid.UUID)
41,186,818
The [uuid4()](https://docs.python.org/2/library/uuid.html#uuid.uuid4) function of Python's module `uuid` generates a random UUID, and seems to generate a different one every time: ``` In [1]: import uuid In [2]: uuid.uuid4() Out[2]: UUID('f6c9ad6c-eea0-4049-a7c5-56253bc3e9c0') In [3]: uuid.uuid4() Out[3]: UUID('2fc1b6f9-9052-4564-9be0-777e790af58f') ``` I would like to be able to generate the same random UUID every time I run a script - that is, I'd like to seed the random generator in `uuid4()`. Is there a way to do this? (Or achieve this by some other means)? ### What I've tried so far I've to generate a UUID using the `uuid.UUID()` method with a random 128-bit integer (from a seeded instance of `random.Random()`) as input: ``` import uuid import random rd = random.Random() rd.seed(0) uuid.UUID(rd.getrandbits(128)) ``` However, `UUID()` seems not to accept this as input: ``` Traceback (most recent call last): File "uuid_gen_seed.py", line 6, in <module> uuid.UUID(rd.getrandbits(128)) File "/usr/lib/python2.7/uuid.py", line 133, in __init__ hex = hex.replace('urn:', '').replace('uuid:', '') AttributeError: 'long' object has no attribute 'replace' ``` Any other suggestions?
2016/12/16
[ "https://Stackoverflow.com/questions/41186818", "https://Stackoverflow.com", "https://Stackoverflow.com/users/995862/" ]
This is based on a solution used [here](https://github.com/ping/instagram_private_api): ``` import hashlib import uuid m = hashlib.md5() m.update(seed.encode('utf-8')) new_uuid = uuid.UUID(m.hexdigest()) ```
Gonna add this here if anyone needs to monkey patch in a seeded UUID. My code uses `uuid.uuid4()` but for testing I wanted consistent UUIDs. The following code is how I did that: ``` import uuid import random # ------------------------------------------- # Remove this block to generate different # UUIDs everytime you run this code. # This block should be right below the uuid # import. rd = random.Random() rd.seed(0) uuid.uuid4 = lambda: uuid.UUID(int=rd.getrandbits(128)) # ------------------------------------------- # Then normal code: print(uuid.uuid4().hex) print(uuid.uuid4().hex) print(uuid.uuid4().hex) print(uuid.uuid4().hex) ```
41,186,818
The [uuid4()](https://docs.python.org/2/library/uuid.html#uuid.uuid4) function of Python's module `uuid` generates a random UUID, and seems to generate a different one every time: ``` In [1]: import uuid In [2]: uuid.uuid4() Out[2]: UUID('f6c9ad6c-eea0-4049-a7c5-56253bc3e9c0') In [3]: uuid.uuid4() Out[3]: UUID('2fc1b6f9-9052-4564-9be0-777e790af58f') ``` I would like to be able to generate the same random UUID every time I run a script - that is, I'd like to seed the random generator in `uuid4()`. Is there a way to do this? (Or achieve this by some other means)? ### What I've tried so far I've to generate a UUID using the `uuid.UUID()` method with a random 128-bit integer (from a seeded instance of `random.Random()`) as input: ``` import uuid import random rd = random.Random() rd.seed(0) uuid.UUID(rd.getrandbits(128)) ``` However, `UUID()` seems not to accept this as input: ``` Traceback (most recent call last): File "uuid_gen_seed.py", line 6, in <module> uuid.UUID(rd.getrandbits(128)) File "/usr/lib/python2.7/uuid.py", line 133, in __init__ hex = hex.replace('urn:', '').replace('uuid:', '') AttributeError: 'long' object has no attribute 'replace' ``` Any other suggestions?
2016/12/16
[ "https://Stackoverflow.com/questions/41186818", "https://Stackoverflow.com", "https://Stackoverflow.com/users/995862/" ]
Almost there: ``` uuid.UUID(int=rd.getrandbits(128)) ``` This was determined with the help of `help`: ``` >>> help(uuid.UUID.__init__) Help on method __init__ in module uuid: __init__(self, hex=None, bytes=None, bytes_le=None, fields=None, int=None, version=None) unbound uuid.UUID method Create a UUID from either a string of 32 hexadecimal digits, a string of 16 bytes as the 'bytes' argument, a string of 16 bytes in little-endian order as the 'bytes_le' argument, a tuple of six integers (32-bit time_low, 16-bit time_mid, 16-bit time_hi_version, 8-bit clock_seq_hi_variant, 8-bit clock_seq_low, 48-bit node) as the 'fields' argument, or a single 128-bit integer as the 'int' argument. When a string of hex digits is given, curly braces, hyphens, and a URN prefix are all optional. For example, these expressions all yield the same UUID: UUID('{12345678-1234-5678-1234-567812345678}') UUID('12345678123456781234567812345678') UUID('urn:uuid:12345678-1234-5678-1234-567812345678') UUID(bytes='\x12\x34\x56\x78'*4) UUID(bytes_le='\x78\x56\x34\x12\x34\x12\x78\x56' + '\x12\x34\x56\x78\x12\x34\x56\x78') UUID(fields=(0x12345678, 0x1234, 0x5678, 0x12, 0x34, 0x567812345678)) UUID(int=0x12345678123456781234567812345678) Exactly one of 'hex', 'bytes', 'bytes_le', 'fields', or 'int' must be given. The 'version' argument is optional; if given, the resulting UUID will have its variant and version set according to RFC 4122, overriding the given 'hex', 'bytes', 'bytes_le', 'fields', or 'int'. ```
Simple solution based on the answer of @user10229295, with a comment about the seed. The Edit queue was full, so I opened a new answer: ``` import hashlib import uuid seed = 'Type your seed_string here' #Read comment below m = hashlib.md5() m.update(seed.encode('utf-8')) new_uuid = uuid.UUID(m.hexdigest()) ``` **Comment about the string *'seed'***: It will be the seed from which the UUID will be generated: from the same seed string will be always generated the same UUID. You can convert integer with some significance as string, concatenate different strings and use the result as your seed. With this you will have control on the UUID generated, which means you will be able to reproduce your UUID knowing the seed you used: with the same seed, the UUID generated from it will be the same.
41,186,818
The [uuid4()](https://docs.python.org/2/library/uuid.html#uuid.uuid4) function of Python's module `uuid` generates a random UUID, and seems to generate a different one every time: ``` In [1]: import uuid In [2]: uuid.uuid4() Out[2]: UUID('f6c9ad6c-eea0-4049-a7c5-56253bc3e9c0') In [3]: uuid.uuid4() Out[3]: UUID('2fc1b6f9-9052-4564-9be0-777e790af58f') ``` I would like to be able to generate the same random UUID every time I run a script - that is, I'd like to seed the random generator in `uuid4()`. Is there a way to do this? (Or achieve this by some other means)? ### What I've tried so far I've to generate a UUID using the `uuid.UUID()` method with a random 128-bit integer (from a seeded instance of `random.Random()`) as input: ``` import uuid import random rd = random.Random() rd.seed(0) uuid.UUID(rd.getrandbits(128)) ``` However, `UUID()` seems not to accept this as input: ``` Traceback (most recent call last): File "uuid_gen_seed.py", line 6, in <module> uuid.UUID(rd.getrandbits(128)) File "/usr/lib/python2.7/uuid.py", line 133, in __init__ hex = hex.replace('urn:', '').replace('uuid:', '') AttributeError: 'long' object has no attribute 'replace' ``` Any other suggestions?
2016/12/16
[ "https://Stackoverflow.com/questions/41186818", "https://Stackoverflow.com", "https://Stackoverflow.com/users/995862/" ]
Gonna add this here if anyone needs to monkey patch in a seeded UUID. My code uses `uuid.uuid4()` but for testing I wanted consistent UUIDs. The following code is how I did that: ``` import uuid import random # ------------------------------------------- # Remove this block to generate different # UUIDs everytime you run this code. # This block should be right below the uuid # import. rd = random.Random() rd.seed(0) uuid.uuid4 = lambda: uuid.UUID(int=rd.getrandbits(128)) # ------------------------------------------- # Then normal code: print(uuid.uuid4().hex) print(uuid.uuid4().hex) print(uuid.uuid4().hex) print(uuid.uuid4().hex) ```
Based on alex's solution, the following would provide a proper UUID4: ``` random.seed(123210912) a = "%32x" % random.getrandbits(128) rd = a[:12] + '4' + a[13:16] + 'a' + a[17:] uuid4 = uuid.UUID(rd) ```
41,186,818
The [uuid4()](https://docs.python.org/2/library/uuid.html#uuid.uuid4) function of Python's module `uuid` generates a random UUID, and seems to generate a different one every time: ``` In [1]: import uuid In [2]: uuid.uuid4() Out[2]: UUID('f6c9ad6c-eea0-4049-a7c5-56253bc3e9c0') In [3]: uuid.uuid4() Out[3]: UUID('2fc1b6f9-9052-4564-9be0-777e790af58f') ``` I would like to be able to generate the same random UUID every time I run a script - that is, I'd like to seed the random generator in `uuid4()`. Is there a way to do this? (Or achieve this by some other means)? ### What I've tried so far I've to generate a UUID using the `uuid.UUID()` method with a random 128-bit integer (from a seeded instance of `random.Random()`) as input: ``` import uuid import random rd = random.Random() rd.seed(0) uuid.UUID(rd.getrandbits(128)) ``` However, `UUID()` seems not to accept this as input: ``` Traceback (most recent call last): File "uuid_gen_seed.py", line 6, in <module> uuid.UUID(rd.getrandbits(128)) File "/usr/lib/python2.7/uuid.py", line 133, in __init__ hex = hex.replace('urn:', '').replace('uuid:', '') AttributeError: 'long' object has no attribute 'replace' ``` Any other suggestions?
2016/12/16
[ "https://Stackoverflow.com/questions/41186818", "https://Stackoverflow.com", "https://Stackoverflow.com/users/995862/" ]
[Faker](https://github.com/joke2k/faker "Faker") makes this easy ``` >>> from faker import Faker >>> f1 = Faker() >>> f1.seed(4321) >>> print(f1.uuid4()) cc733c92-6853-15f6-0e49-bec741188ebb >>> print(f1.uuid4()) a41f020c-2d4d-333f-f1d3-979f1043fae0 >>> f1.seed(4321) >>> print(f1.uuid4()) cc733c92-6853-15f6-0e49-bec741188ebb ```
Gonna add this here if anyone needs to monkey patch in a seeded UUID. My code uses `uuid.uuid4()` but for testing I wanted consistent UUIDs. The following code is how I did that: ``` import uuid import random # ------------------------------------------- # Remove this block to generate different # UUIDs everytime you run this code. # This block should be right below the uuid # import. rd = random.Random() rd.seed(0) uuid.uuid4 = lambda: uuid.UUID(int=rd.getrandbits(128)) # ------------------------------------------- # Then normal code: print(uuid.uuid4().hex) print(uuid.uuid4().hex) print(uuid.uuid4().hex) print(uuid.uuid4().hex) ```
41,186,818
The [uuid4()](https://docs.python.org/2/library/uuid.html#uuid.uuid4) function of Python's module `uuid` generates a random UUID, and seems to generate a different one every time: ``` In [1]: import uuid In [2]: uuid.uuid4() Out[2]: UUID('f6c9ad6c-eea0-4049-a7c5-56253bc3e9c0') In [3]: uuid.uuid4() Out[3]: UUID('2fc1b6f9-9052-4564-9be0-777e790af58f') ``` I would like to be able to generate the same random UUID every time I run a script - that is, I'd like to seed the random generator in `uuid4()`. Is there a way to do this? (Or achieve this by some other means)? ### What I've tried so far I've to generate a UUID using the `uuid.UUID()` method with a random 128-bit integer (from a seeded instance of `random.Random()`) as input: ``` import uuid import random rd = random.Random() rd.seed(0) uuid.UUID(rd.getrandbits(128)) ``` However, `UUID()` seems not to accept this as input: ``` Traceback (most recent call last): File "uuid_gen_seed.py", line 6, in <module> uuid.UUID(rd.getrandbits(128)) File "/usr/lib/python2.7/uuid.py", line 133, in __init__ hex = hex.replace('urn:', '').replace('uuid:', '') AttributeError: 'long' object has no attribute 'replace' ``` Any other suggestions?
2016/12/16
[ "https://Stackoverflow.com/questions/41186818", "https://Stackoverflow.com", "https://Stackoverflow.com/users/995862/" ]
Almost there: ``` uuid.UUID(int=rd.getrandbits(128)) ``` This was determined with the help of `help`: ``` >>> help(uuid.UUID.__init__) Help on method __init__ in module uuid: __init__(self, hex=None, bytes=None, bytes_le=None, fields=None, int=None, version=None) unbound uuid.UUID method Create a UUID from either a string of 32 hexadecimal digits, a string of 16 bytes as the 'bytes' argument, a string of 16 bytes in little-endian order as the 'bytes_le' argument, a tuple of six integers (32-bit time_low, 16-bit time_mid, 16-bit time_hi_version, 8-bit clock_seq_hi_variant, 8-bit clock_seq_low, 48-bit node) as the 'fields' argument, or a single 128-bit integer as the 'int' argument. When a string of hex digits is given, curly braces, hyphens, and a URN prefix are all optional. For example, these expressions all yield the same UUID: UUID('{12345678-1234-5678-1234-567812345678}') UUID('12345678123456781234567812345678') UUID('urn:uuid:12345678-1234-5678-1234-567812345678') UUID(bytes='\x12\x34\x56\x78'*4) UUID(bytes_le='\x78\x56\x34\x12\x34\x12\x78\x56' + '\x12\x34\x56\x78\x12\x34\x56\x78') UUID(fields=(0x12345678, 0x1234, 0x5678, 0x12, 0x34, 0x567812345678)) UUID(int=0x12345678123456781234567812345678) Exactly one of 'hex', 'bytes', 'bytes_le', 'fields', or 'int' must be given. The 'version' argument is optional; if given, the resulting UUID will have its variant and version set according to RFC 4122, overriding the given 'hex', 'bytes', 'bytes_le', 'fields', or 'int'. ```
Since the straight-forward solution hasn't been posted yet to generate consistent version 4 UUIDs: ```py import random import uuid rnd = random.Random() rnd.seed(123) # NOTE: Of course don't use a static seed in production random_uuid = uuid.UUID(int=rnd.getrandbits(128), version=4) ``` where you can see then: ``` >>> random_uuid.version 4 ``` This doesn't just "mock" the version information. It creates a proper UUIDv4: > > The version argument is optional; if given, the resulting UUID will have its variant and version number set according to RFC 4122, overriding bits in the given hex, bytes, bytes\_le, fields, or int. > > > [Python 3.8 docs](https://docs.python.org/3/library/uuid.html?highlight=uuid#uuid.UUID)
41,186,818
The [uuid4()](https://docs.python.org/2/library/uuid.html#uuid.uuid4) function of Python's module `uuid` generates a random UUID, and seems to generate a different one every time: ``` In [1]: import uuid In [2]: uuid.uuid4() Out[2]: UUID('f6c9ad6c-eea0-4049-a7c5-56253bc3e9c0') In [3]: uuid.uuid4() Out[3]: UUID('2fc1b6f9-9052-4564-9be0-777e790af58f') ``` I would like to be able to generate the same random UUID every time I run a script - that is, I'd like to seed the random generator in `uuid4()`. Is there a way to do this? (Or achieve this by some other means)? ### What I've tried so far I've to generate a UUID using the `uuid.UUID()` method with a random 128-bit integer (from a seeded instance of `random.Random()`) as input: ``` import uuid import random rd = random.Random() rd.seed(0) uuid.UUID(rd.getrandbits(128)) ``` However, `UUID()` seems not to accept this as input: ``` Traceback (most recent call last): File "uuid_gen_seed.py", line 6, in <module> uuid.UUID(rd.getrandbits(128)) File "/usr/lib/python2.7/uuid.py", line 133, in __init__ hex = hex.replace('urn:', '').replace('uuid:', '') AttributeError: 'long' object has no attribute 'replace' ``` Any other suggestions?
2016/12/16
[ "https://Stackoverflow.com/questions/41186818", "https://Stackoverflow.com", "https://Stackoverflow.com/users/995862/" ]
This is based on a solution used [here](https://github.com/ping/instagram_private_api): ``` import hashlib import uuid m = hashlib.md5() m.update(seed.encode('utf-8')) new_uuid = uuid.UUID(m.hexdigest()) ```
Since the straight-forward solution hasn't been posted yet to generate consistent version 4 UUIDs: ```py import random import uuid rnd = random.Random() rnd.seed(123) # NOTE: Of course don't use a static seed in production random_uuid = uuid.UUID(int=rnd.getrandbits(128), version=4) ``` where you can see then: ``` >>> random_uuid.version 4 ``` This doesn't just "mock" the version information. It creates a proper UUIDv4: > > The version argument is optional; if given, the resulting UUID will have its variant and version number set according to RFC 4122, overriding bits in the given hex, bytes, bytes\_le, fields, or int. > > > [Python 3.8 docs](https://docs.python.org/3/library/uuid.html?highlight=uuid#uuid.UUID)
41,186,818
The [uuid4()](https://docs.python.org/2/library/uuid.html#uuid.uuid4) function of Python's module `uuid` generates a random UUID, and seems to generate a different one every time: ``` In [1]: import uuid In [2]: uuid.uuid4() Out[2]: UUID('f6c9ad6c-eea0-4049-a7c5-56253bc3e9c0') In [3]: uuid.uuid4() Out[3]: UUID('2fc1b6f9-9052-4564-9be0-777e790af58f') ``` I would like to be able to generate the same random UUID every time I run a script - that is, I'd like to seed the random generator in `uuid4()`. Is there a way to do this? (Or achieve this by some other means)? ### What I've tried so far I've to generate a UUID using the `uuid.UUID()` method with a random 128-bit integer (from a seeded instance of `random.Random()`) as input: ``` import uuid import random rd = random.Random() rd.seed(0) uuid.UUID(rd.getrandbits(128)) ``` However, `UUID()` seems not to accept this as input: ``` Traceback (most recent call last): File "uuid_gen_seed.py", line 6, in <module> uuid.UUID(rd.getrandbits(128)) File "/usr/lib/python2.7/uuid.py", line 133, in __init__ hex = hex.replace('urn:', '').replace('uuid:', '') AttributeError: 'long' object has no attribute 'replace' ``` Any other suggestions?
2016/12/16
[ "https://Stackoverflow.com/questions/41186818", "https://Stackoverflow.com", "https://Stackoverflow.com/users/995862/" ]
Almost there: ``` uuid.UUID(int=rd.getrandbits(128)) ``` This was determined with the help of `help`: ``` >>> help(uuid.UUID.__init__) Help on method __init__ in module uuid: __init__(self, hex=None, bytes=None, bytes_le=None, fields=None, int=None, version=None) unbound uuid.UUID method Create a UUID from either a string of 32 hexadecimal digits, a string of 16 bytes as the 'bytes' argument, a string of 16 bytes in little-endian order as the 'bytes_le' argument, a tuple of six integers (32-bit time_low, 16-bit time_mid, 16-bit time_hi_version, 8-bit clock_seq_hi_variant, 8-bit clock_seq_low, 48-bit node) as the 'fields' argument, or a single 128-bit integer as the 'int' argument. When a string of hex digits is given, curly braces, hyphens, and a URN prefix are all optional. For example, these expressions all yield the same UUID: UUID('{12345678-1234-5678-1234-567812345678}') UUID('12345678123456781234567812345678') UUID('urn:uuid:12345678-1234-5678-1234-567812345678') UUID(bytes='\x12\x34\x56\x78'*4) UUID(bytes_le='\x78\x56\x34\x12\x34\x12\x78\x56' + '\x12\x34\x56\x78\x12\x34\x56\x78') UUID(fields=(0x12345678, 0x1234, 0x5678, 0x12, 0x34, 0x567812345678)) UUID(int=0x12345678123456781234567812345678) Exactly one of 'hex', 'bytes', 'bytes_le', 'fields', or 'int' must be given. The 'version' argument is optional; if given, the resulting UUID will have its variant and version set according to RFC 4122, overriding the given 'hex', 'bytes', 'bytes_le', 'fields', or 'int'. ```
[Faker](https://github.com/joke2k/faker "Faker") makes this easy ``` >>> from faker import Faker >>> f1 = Faker() >>> f1.seed(4321) >>> print(f1.uuid4()) cc733c92-6853-15f6-0e49-bec741188ebb >>> print(f1.uuid4()) a41f020c-2d4d-333f-f1d3-979f1043fae0 >>> f1.seed(4321) >>> print(f1.uuid4()) cc733c92-6853-15f6-0e49-bec741188ebb ```
41,186,818
The [uuid4()](https://docs.python.org/2/library/uuid.html#uuid.uuid4) function of Python's module `uuid` generates a random UUID, and seems to generate a different one every time: ``` In [1]: import uuid In [2]: uuid.uuid4() Out[2]: UUID('f6c9ad6c-eea0-4049-a7c5-56253bc3e9c0') In [3]: uuid.uuid4() Out[3]: UUID('2fc1b6f9-9052-4564-9be0-777e790af58f') ``` I would like to be able to generate the same random UUID every time I run a script - that is, I'd like to seed the random generator in `uuid4()`. Is there a way to do this? (Or achieve this by some other means)? ### What I've tried so far I've to generate a UUID using the `uuid.UUID()` method with a random 128-bit integer (from a seeded instance of `random.Random()`) as input: ``` import uuid import random rd = random.Random() rd.seed(0) uuid.UUID(rd.getrandbits(128)) ``` However, `UUID()` seems not to accept this as input: ``` Traceback (most recent call last): File "uuid_gen_seed.py", line 6, in <module> uuid.UUID(rd.getrandbits(128)) File "/usr/lib/python2.7/uuid.py", line 133, in __init__ hex = hex.replace('urn:', '').replace('uuid:', '') AttributeError: 'long' object has no attribute 'replace' ``` Any other suggestions?
2016/12/16
[ "https://Stackoverflow.com/questions/41186818", "https://Stackoverflow.com", "https://Stackoverflow.com/users/995862/" ]
Almost there: ``` uuid.UUID(int=rd.getrandbits(128)) ``` This was determined with the help of `help`: ``` >>> help(uuid.UUID.__init__) Help on method __init__ in module uuid: __init__(self, hex=None, bytes=None, bytes_le=None, fields=None, int=None, version=None) unbound uuid.UUID method Create a UUID from either a string of 32 hexadecimal digits, a string of 16 bytes as the 'bytes' argument, a string of 16 bytes in little-endian order as the 'bytes_le' argument, a tuple of six integers (32-bit time_low, 16-bit time_mid, 16-bit time_hi_version, 8-bit clock_seq_hi_variant, 8-bit clock_seq_low, 48-bit node) as the 'fields' argument, or a single 128-bit integer as the 'int' argument. When a string of hex digits is given, curly braces, hyphens, and a URN prefix are all optional. For example, these expressions all yield the same UUID: UUID('{12345678-1234-5678-1234-567812345678}') UUID('12345678123456781234567812345678') UUID('urn:uuid:12345678-1234-5678-1234-567812345678') UUID(bytes='\x12\x34\x56\x78'*4) UUID(bytes_le='\x78\x56\x34\x12\x34\x12\x78\x56' + '\x12\x34\x56\x78\x12\x34\x56\x78') UUID(fields=(0x12345678, 0x1234, 0x5678, 0x12, 0x34, 0x567812345678)) UUID(int=0x12345678123456781234567812345678) Exactly one of 'hex', 'bytes', 'bytes_le', 'fields', or 'int' must be given. The 'version' argument is optional; if given, the resulting UUID will have its variant and version set according to RFC 4122, overriding the given 'hex', 'bytes', 'bytes_le', 'fields', or 'int'. ```
Based on alex's solution, the following would provide a proper UUID4: ``` random.seed(123210912) a = "%32x" % random.getrandbits(128) rd = a[:12] + '4' + a[13:16] + 'a' + a[17:] uuid4 = uuid.UUID(rd) ```
14,946,639
Say I have the following code: ``` if request.POST: id = request.POST.get('id') # block of code to use variable id do_work(id) do_other_work(id) ``` is there a shortcut (one line of code) that will test if it's request.POST for the conditional block and also assign variable id for the conditional block to use the id variable? I read this [Is there a Python shortcut for variable checking and assignment?](https://stackoverflow.com/questions/1207333/is-there-a-python-shortcut-for-variable-checking-and-assignment) but doesn't really answer my question.
2013/02/18
[ "https://Stackoverflow.com/questions/14946639", "https://Stackoverflow.com", "https://Stackoverflow.com/users/342553/" ]
No, you can't assign anything in an `if` test expression. If you didn't have the rest of the `if` block, ``` id = request.POST and request.POST.get('id') ``` would work. It doesn't make much sense, to do it, though, because `id = request.POST.get('id')` works just fine with empty `request.POST`. Please remember that `request.POST` can be empty, even if the method was `POST`. This is what most people would write: ``` if request.method == 'POST': id = request.POST.get('id') # rest of block ```
I like this: ``` id = request.POST.get('id', False) if id is not False: # do something ```
66,534,294
I am using python 3.7 and have intalled IPython I am using ipython shell in django like ``` python manage.py shell_plus ``` and then ``` [1]: %load_ext autoreload [2]: %autoreload 2 ``` and then i am doing ``` [1]: from boiler.tasks import add [2]: add(1,2) "testing" ``` `change add function` ``` def add(x,y): print("testing2") ``` and then i am doing ``` [1]: from boiler.tasks import add [2]: add(1,2) "testing" ``` so here i found its not updating
2021/03/08
[ "https://Stackoverflow.com/questions/66534294", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2897115/" ]
> > Will this cause issues on the memory side? > > > Which side of what, and which side of it is the memory side? It may use more memory than necessary. > > What happens to that extra memory? > > > It remains unused. > > Does it have to be manually freed or is there a way to do it automatically? > > > In a general-purpose operating system, the system will recover memory when your process terminates. If you want allocated memory to be available for reuse before that, you must free it. > > Should I just not bother messing around and just figure out the right size beforehand? > > > Appropriate strategies depend on circumstances. Some possibilities are: * You allocate a large amount of memory, perform the operations to get data into it and then, having learned the size of the data, use `realloc` to release the excess memory. * You make a fair estimate of the amount of memory needed, being sure to be at or over the requirement, not under, allocate that memory, and let the small excess be wasted. * You allocate some memory and start operations to put data into it. As you acquire data, you watch for it filling the allocated amount. When more is needed, you use `realloc` to get more.
For your purposes, the memory allocator doesn't know, nor does it really care about how much memory you actually use in a block you malloc. The key here is to never use *more* memory than you malloc. The extra memory just sits there, available for your use if you want it. Note that allocating 10 bytes vs 4 bytes won't make much, if any difference for you, assuming you're not performing this allocation thousands of times. The only validation / size calculation I'd recommend you never skip is ensuring that you never allocate too little memory for the item you're placing in the allocated space. You don't technically have to free the memory (as the OS will clean up the mess you've made after your application exits), but you absolutely should. If you don't free memory after you're done using it, this is called a memory leak and will cause your application to use more RAM than it has to. Additionally, be very careful never to use memory again after you've freed it. That's called a use-after-free, and can be a dangerous bug. Memory management in C is very much something you have to do manually, as opposed to some other languages.
26,953,153
Beginner python coder here, keep things simple, please. So, I need this code below to scramble two letters without scrambling the first or last letters. Everything seems to work right up until the `scrambler()` function. ``` from random import randint def wordScramble(string): stringArray = string.split() for word in stringArray: if len(word) >= 4: letter = randint(1,len(word)-2) point = letter while point == letter: point = randint(1, len(word)-2) word = switcher(word,letter,point) ' '.join(stringArray) return stringArray def switcher(word,letter,point): word = list(word) word[letter],word[point]=word[point],word[letter] return word print(wordScramble("I can't wait to see how this turns itself out")) ``` The outcome is always: `I can't wait to see how this turns itself out`
2014/11/16
[ "https://Stackoverflow.com/questions/26953153", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4257122/" ]
If the labels 0, 100, 200 belong to one axis and the texts "Day One", ... to the other one you can set the colors of the labels of the first axis to transparent like this ``` axis.TextColor = OxyColors.Transparent; ``` Hope this helps.
If XAML use this ``` <oxy:Plot.Axes> <oxy:LinearAxis Position="Left" TextColor = OxyColors.Transparent/> </oxy:Plot.Axes> ``` If code ``` // Create a plot model PlotModel = new PlotModel { Title = "Updating by task running on the UI thread" }; // Add the axes, note that MinimumPadding and AbsoluteMinimum should be set on the value axis. PlotModel.Axes.Add(new LinearAxis { Position = AxisPosition.Bottom, TextColor = OxyColors.Transparent}); ```
18,782,584
How can I perform post processing on my SQL3 database via python? The following code doesn't work, but what I am trying to do is first create a new database if not exists already, then insert some data, and finally execute the query and close the connection. But I what to do so separately, so as to add additional functionality later on, such as delete / updater / etc... Any ideas? ``` class TitlesDB: # initiate global variables conn = None c = None # perform pre - processing def __init__(self, name): import os os.chdir('/../../') import sqlite3 conn = sqlite3.connect(name) c = conn.cursor() c.execute('CREATE TABLE IF NOT EXISTS titles (title VARCHAR(100) UNIQUE)') # insert a bunch of new titles def InsertTitles(self, list): c.executemany('INSERT OR IGNORE INTO titles VALUES (?)', list) # perform post - processing def __fina__(self): conn.commit() conn.close() ```
2013/09/13
[ "https://Stackoverflow.com/questions/18782584", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2295350/" ]
It would seem that FB has made some changes to its redirection script, when it detects a Windows Phone webbrowser control. What the C# SDK does, is generate the login page as "<http://www.facebook.com>....". When you open this URL on the webbrowser control, it gets redirected to "<http://m.facebook.com>..." which displays the mobile version of the FB login page. This previously has no issue, but recently, when FB does the redirection, it also strips the parameter "display=page" from the URL. What happens then is that when a successful FB login is made, the "login\_success.html" page is opened without this parameter. Without the "display=page" parameter passed in, it defaults to "display=touch". This URL unfortunately, does not append the token string in the URL, hence the page shown in the very first thread is displayed. The solution to this is, instead of using the below code to generate the login URL, ammend it to original: ``` Browser.Navigate(_fb.GetLoginUrl(parameters)); ``` ammended: ``` var URI = _fb.GetLoginUrl(parameters).toString().replace("www.facebook.com","m.facebook.com"); Browser.Navigate(new Uri(URI)); ```
In my project I just listened for the WebView's navigated event. If it happens, it means that user did something on the login page (i.e. pressed login button). Then I parsed the uri of the page you mentioned which should contain OAuth callback url, if it is correct and the result is success I redirect manually to the correct page: ``` //somewhere in the app private readonly FacebookClient _fb = new FacebookClient(); private void webBrowser1_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e) { FacebookOAuthResult oauthResult; if (!_fb.TryParseOAuthCallbackUrl(e.Uri, out oauthResult)) { return; } if (oauthResult.IsSuccess) { var accessToken = oauthResult.AccessToken; //you have an access token, you can proceed further FBLoginSucceded(accessToken); } else { // errors when logging in MessageBox.Show(oauthResult.ErrorDescription); } } ``` If you abstract logging in an async function, you expect it to behave asynchronously, so events are ok. Sorry for my English. The code for the full page: ``` public partial class LoginPageFacebook : PhoneApplicationPage { private readonly string AppId = Constants.FacebookAppId; private const string ExtendedPermissions = "user_birthday,email,user_photos"; private readonly FacebookClient _fb = new FacebookClient(); private Dictionary<string, object> facebookData = new Dictionary<string, object>(); UserIdentity userIdentity = App.Current.Resources["userIdentity"] as UserIdentity; public LoginPageFacebook() { InitializeComponent(); } private void webBrowser1_Loaded(object sender, RoutedEventArgs e) { var loginUrl = GetFacebookLoginUrl(AppId, ExtendedPermissions); webBrowser1.Navigate(loginUrl); } private Uri GetFacebookLoginUrl(string appId, string extendedPermissions) { var parameters = new Dictionary<string, object>(); parameters["client_id"] = appId; parameters["redirect_uri"] = "https://www.facebook.com/connect/login_success.html"; parameters["response_type"] = "token"; parameters["display"] = "touch"; // add the 'scope' only if we have extendedPermissions. if (!string.IsNullOrEmpty(extendedPermissions)) { // A comma-delimited list of permissions parameters["scope"] = extendedPermissions; } return _fb.GetLoginUrl(parameters); } private void webBrowser1_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e) { if (waitPanel.Visibility == Visibility.Visible) { waitPanel.Visibility = Visibility.Collapsed; webBrowser1.Visibility = Visibility.Visible; } FacebookOAuthResult oauthResult; if (!_fb.TryParseOAuthCallbackUrl(e.Uri, out oauthResult)) { return; } if (oauthResult.IsSuccess) { var accessToken = oauthResult.AccessToken; FBLoginSucceded(accessToken); } else { // user cancelled MessageBox.Show(oauthResult.ErrorDescription); } } private void FBLoginSucceded(string accessToken) { var fb = new FacebookClient(accessToken); fb.GetCompleted += (o, e) => { if (e.Error != null) { Dispatcher.BeginInvoke(() => MessageBox.Show(e.Error.Message)); return; } var result = (IDictionary<string, object>)e.GetResultData(); var id = (string)result["id"]; userIdentity.FBAccessToken = accessToken; userIdentity.FBID = id; facebookData["Name"] = result["first_name"]; facebookData["Surname"] = result["last_name"]; facebookData["Email"] = result["email"]; facebookData["Birthday"] = DateTime.Parse((string)result["birthday"]); facebookData["Country"] = result["locale"]; Dispatcher.BeginInvoke(() => { BitmapImage profilePicture = new BitmapImage(new Uri(string.Format("https://graph.facebook.com/{0}/picture?type={1}&access_token={2}", id, "square", accessToken))); facebookData["ProfilePicture"] = profilePicture; userIdentity.FBData = facebookData; userIdentity.ProfilePicture = profilePicture; ARLoginOrRegister(); }); }; fb.GetAsync("me"); } private void ARLoginOrRegister() { WebService.ARServiceClient client = new WebService.ARServiceClient(); client.GetUserCompleted += client_GetUserCompleted; client.GetUserAsync((string)facebookData["Email"]); client.CloseAsync(); } void client_GetUserCompleted(object sender, WebService.GetUserCompletedEventArgs e) { if (e.Result == null) NavigationService.Navigate(new Uri("/RegisterPageFacebook.xaml", UriKind.RelativeOrAbsolute)); else if (e.Result.AccountType != (int)AccountType.Facebook) { MessageBox.Show("This account is not registered with facebook!"); NavigationService.Navigate(new Uri("/LoginPage.xaml", UriKind.RelativeOrAbsolute)); } else { userIdentity.Authenticated += userIdentity_Authenticated; userIdentity.FetchARSocialData((string)facebookData["Email"]); } } void userIdentity_Authenticated(bool success) { NavigationService.Navigate(new Uri("/MenuPage.xaml", UriKind.RelativeOrAbsolute)); } } ```
18,782,584
How can I perform post processing on my SQL3 database via python? The following code doesn't work, but what I am trying to do is first create a new database if not exists already, then insert some data, and finally execute the query and close the connection. But I what to do so separately, so as to add additional functionality later on, such as delete / updater / etc... Any ideas? ``` class TitlesDB: # initiate global variables conn = None c = None # perform pre - processing def __init__(self, name): import os os.chdir('/../../') import sqlite3 conn = sqlite3.connect(name) c = conn.cursor() c.execute('CREATE TABLE IF NOT EXISTS titles (title VARCHAR(100) UNIQUE)') # insert a bunch of new titles def InsertTitles(self, list): c.executemany('INSERT OR IGNORE INTO titles VALUES (?)', list) # perform post - processing def __fina__(self): conn.commit() conn.close() ```
2013/09/13
[ "https://Stackoverflow.com/questions/18782584", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2295350/" ]
It would seem that FB has made some changes to its redirection script, when it detects a Windows Phone webbrowser control. What the C# SDK does, is generate the login page as "<http://www.facebook.com>....". When you open this URL on the webbrowser control, it gets redirected to "<http://m.facebook.com>..." which displays the mobile version of the FB login page. This previously has no issue, but recently, when FB does the redirection, it also strips the parameter "display=page" from the URL. What happens then is that when a successful FB login is made, the "login\_success.html" page is opened without this parameter. Without the "display=page" parameter passed in, it defaults to "display=touch". This URL unfortunately, does not append the token string in the URL, hence the page shown in the very first thread is displayed. The solution to this is, instead of using the below code to generate the login URL, ammend it to original: ``` Browser.Navigate(_fb.GetLoginUrl(parameters)); ``` ammended: ``` var URI = _fb.GetLoginUrl(parameters).toString().replace("www.facebook.com","m.facebook.com"); Browser.Navigate(new Uri(URI)); ```
Before trying to do all the proposed changes, please check that your Facebook App is not on Sandbox mode. This will eventually resolve your issue. ![enter image description here](https://i.stack.imgur.com/CElH5.png) If your facebook app is in sandbox mode, only the developer can login, using his email address. Any other fb user will get the white page.
809,859
Personal preferences aside, is there an optimal tab size (2 spaces? 3 spaces? 8 spaces?) for code readability? In the different projects I've worked on, people seem to have vastly different standards. I can't seem to read 2 space indents, but companies like Google use it as a standard. Can anyone point to documentation, studies, or well-reasoned arguments for the optimal size of a tab? If we want to get specific, I work mostly in python. The goal of this question is to pick a standard for the team I work on.
2009/05/01
[ "https://Stackoverflow.com/questions/809859", "https://Stackoverflow.com", "https://Stackoverflow.com/users/85271/" ]
[Four spaces and no hard tabs](https://david.goodger.org/projects/pycon/2007/idiomatic/handout.html#whitespace-1), if you're a Pythonista.
``` 2 space 4 busy coder 3 space for heavy if statement using script kiddies 4 space for those who make real money pressing space 4 times 8 space for the man in ties and suit who doesn't need to code ```
809,859
Personal preferences aside, is there an optimal tab size (2 spaces? 3 spaces? 8 spaces?) for code readability? In the different projects I've worked on, people seem to have vastly different standards. I can't seem to read 2 space indents, but companies like Google use it as a standard. Can anyone point to documentation, studies, or well-reasoned arguments for the optimal size of a tab? If we want to get specific, I work mostly in python. The goal of this question is to pick a standard for the team I work on.
2009/05/01
[ "https://Stackoverflow.com/questions/809859", "https://Stackoverflow.com", "https://Stackoverflow.com/users/85271/" ]
[Four spaces and no hard tabs](https://david.goodger.org/projects/pycon/2007/idiomatic/handout.html#whitespace-1), if you're a Pythonista.
In the past I used 3 spaces. And that's still my preference. But 4 spaces seems to be the standard in the VB world. So I have switched to 4 to be in line with most code examples I see, and with the rest of my team.
809,859
Personal preferences aside, is there an optimal tab size (2 spaces? 3 spaces? 8 spaces?) for code readability? In the different projects I've worked on, people seem to have vastly different standards. I can't seem to read 2 space indents, but companies like Google use it as a standard. Can anyone point to documentation, studies, or well-reasoned arguments for the optimal size of a tab? If we want to get specific, I work mostly in python. The goal of this question is to pick a standard for the team I work on.
2009/05/01
[ "https://Stackoverflow.com/questions/809859", "https://Stackoverflow.com", "https://Stackoverflow.com/users/85271/" ]
I like 8 spaces (I know, right?). It makes the start/ end of blocks really obvious. As to your question, a formal usability study would be required. Let's look at limits though: **0 spaces** ``` function test(){ var x = 1; for (i=0; i<=5; i++){ doSomething(); } } ``` No indentation is obviously bad. You can't tell where anything begins or ends. **19 Spaces** ``` function test(){ var x = 1; for (i=0; i<=5; i++){ doSomething(); } } ``` Loads of indentation is obviously bad too, because you can't visually link code to its parent function or loop (or what have you) as your peripheral vision doesn't extend that far. Your eyes have to flick too far back and forth to facilitate reading. **8 spaces** ``` function test(){ var x = 1; for (i=0; i<=5; i++){ doSomething(); } } ``` I think I decided on 8 spaces because the word 'function' is 8 characters long. But it just seems so useful for readability. All the code is in my peripheral vision, and there's no way I can miss the start of a new block of code if I'm quickly scanning.
I read that 2 spaces is actually optimal, based on a study where programmers were asked to estimate the level of nesting based on indentation, but that when asked, programmers thought 4 would be optimal. Citation needed, but can't find it.
809,859
Personal preferences aside, is there an optimal tab size (2 spaces? 3 spaces? 8 spaces?) for code readability? In the different projects I've worked on, people seem to have vastly different standards. I can't seem to read 2 space indents, but companies like Google use it as a standard. Can anyone point to documentation, studies, or well-reasoned arguments for the optimal size of a tab? If we want to get specific, I work mostly in python. The goal of this question is to pick a standard for the team I work on.
2009/05/01
[ "https://Stackoverflow.com/questions/809859", "https://Stackoverflow.com", "https://Stackoverflow.com/users/85271/" ]
``` 2 space 4 busy coder 3 space for heavy if statement using script kiddies 4 space for those who make real money pressing space 4 times 8 space for the man in ties and suit who doesn't need to code ```
I read that 2 spaces is actually optimal, based on a study where programmers were asked to estimate the level of nesting based on indentation, but that when asked, programmers thought 4 would be optimal. Citation needed, but can't find it.
809,859
Personal preferences aside, is there an optimal tab size (2 spaces? 3 spaces? 8 spaces?) for code readability? In the different projects I've worked on, people seem to have vastly different standards. I can't seem to read 2 space indents, but companies like Google use it as a standard. Can anyone point to documentation, studies, or well-reasoned arguments for the optimal size of a tab? If we want to get specific, I work mostly in python. The goal of this question is to pick a standard for the team I work on.
2009/05/01
[ "https://Stackoverflow.com/questions/809859", "https://Stackoverflow.com", "https://Stackoverflow.com/users/85271/" ]
No one have mentioned this so far so I feel I am obligated to post one. The choice of indent size (which I think what OP meant), affects not just how codes are indented but also affects how much code you can fit in a line and how they align. A development team needs to eventually come to some sort of agreement on the length of a line. I started off with 80 columns and to this day I still stick to 80 columns. AFAIK, stackoverflow uses 80 columns in source code markdown as well. When you use an indent level of 8, with a typical function that is nested 3 levels deep, your code will start at column 24. That lefts me with just 56 characters to write a line of code. Here is what some code in VLC looks like with indent=4: ``` msg_Dbg( p_libvlc, "Adds %s to the running media player", mrl ); free( mrl ); /* send message and get a handle for a reply */ DBusMessage *reply = dbus_connection_send_with_reply_and_block( conn, msg, -1, &err ); dbus_message_unref( msg ); ``` Here is what it looks like with indent=8 ``` msg_Dbg( p_libvlc, "Adds %s to the running media player", mrl ); free( mrl ); /* send message and get a handle for a reply */ DBusMessage *reply = dbus_connection_send_with_reply_and_block( conn, msg, -1, &err ); dbus_message_unref( msg ); ``` While large indents make code easier to read, it also gives you less room to write nested code before they wrap around. It is really important to keep tab size at 8. tab != indent. While it is temping to make hard tab as indents, it also have very bad consequences. A lot of people also like to align their code. So code like above will look like this with tab = 4: ``` msg_Dbg( p_libvlc, "Adds %s to the running media player", mrl ); free( mrl ); /* send message and get a handle for a reply */ DBusMessage *reply = dbus_connection_send_with_reply_and_block( conn, msg, -1, &err ); dbus_message_unref( msg ); ``` You will see that the line `&err` no longer aligns with `conn` above. The situation gets even worse when multiple comments are added in the end of each line.
I read that 2 spaces is actually optimal, based on a study where programmers were asked to estimate the level of nesting based on indentation, but that when asked, programmers thought 4 would be optimal. Citation needed, but can't find it.
809,859
Personal preferences aside, is there an optimal tab size (2 spaces? 3 spaces? 8 spaces?) for code readability? In the different projects I've worked on, people seem to have vastly different standards. I can't seem to read 2 space indents, but companies like Google use it as a standard. Can anyone point to documentation, studies, or well-reasoned arguments for the optimal size of a tab? If we want to get specific, I work mostly in python. The goal of this question is to pick a standard for the team I work on.
2009/05/01
[ "https://Stackoverflow.com/questions/809859", "https://Stackoverflow.com", "https://Stackoverflow.com/users/85271/" ]
This discussion often involves misunderstandings, because ([as jwz describes](http://www.jwz.org/doc/tabs-vs-spaces.html)) it usually involves **three distinct issues**: * What happens when I press the `Tab` key in my text editor? * What happens when I request my editor to indent one or more lines? * What happens when I view a file containing U+0009 HORIZONTAL TAB characters? My answers: * Pressing the `Tab` key should **indent the current line** (or selected lines) one additional level. As a secondary alternative, I can also tolerate an editor that, like Emacs, uses this key for a context-sensitive fix-my-indentation command. * Indenting one or more lines should follow the reigning convention, if consensus is sufficiently strong; otherwise, I greatly prefer **4-space indentation** at each level. * U+0009 characters should shift subsequent characters to the **next tab stop**. Tab stops begin at column 1 and are 8 columns apart, no exceptions.
Since you're using Python, you could, as said before, take python's style guide ([PEP 8](http://www.python.org/dev/peps/pep-0008/)) advice: > > Indentation > > > > ``` > Use 4 spaces per indentation level. > > ``` > > But the [Linux kernel CodingStyle](http://lxr.linux.no/linux+v2.6.29/Documentation/CodingStyle) says diferent: > > Tabs are 8 characters, and thus > indentations are also 8 characters. > There are heretic movements that try > to make indentations 4 (or even 2!) > characters deep, and that is akin to > trying to define the value of PI to be > 3. Rationale: The whole idea behind indentation is to clearly define where > a block of control starts and ends. > Especially when you've been looking at > your screen for 20 straight hours, > you'll find it a lot easier to see how > the indentation works if you have > large indentations. > > > This document also has some examples of how code should look like, and how identation changes that (it's in C, though)
809,859
Personal preferences aside, is there an optimal tab size (2 spaces? 3 spaces? 8 spaces?) for code readability? In the different projects I've worked on, people seem to have vastly different standards. I can't seem to read 2 space indents, but companies like Google use it as a standard. Can anyone point to documentation, studies, or well-reasoned arguments for the optimal size of a tab? If we want to get specific, I work mostly in python. The goal of this question is to pick a standard for the team I work on.
2009/05/01
[ "https://Stackoverflow.com/questions/809859", "https://Stackoverflow.com", "https://Stackoverflow.com/users/85271/" ]
This discussion often involves misunderstandings, because ([as jwz describes](http://www.jwz.org/doc/tabs-vs-spaces.html)) it usually involves **three distinct issues**: * What happens when I press the `Tab` key in my text editor? * What happens when I request my editor to indent one or more lines? * What happens when I view a file containing U+0009 HORIZONTAL TAB characters? My answers: * Pressing the `Tab` key should **indent the current line** (or selected lines) one additional level. As a secondary alternative, I can also tolerate an editor that, like Emacs, uses this key for a context-sensitive fix-my-indentation command. * Indenting one or more lines should follow the reigning convention, if consensus is sufficiently strong; otherwise, I greatly prefer **4-space indentation** at each level. * U+0009 characters should shift subsequent characters to the **next tab stop**. Tab stops begin at column 1 and are 8 columns apart, no exceptions.
I read that 2 spaces is actually optimal, based on a study where programmers were asked to estimate the level of nesting based on indentation, but that when asked, programmers thought 4 would be optimal. Citation needed, but can't find it.
809,859
Personal preferences aside, is there an optimal tab size (2 spaces? 3 spaces? 8 spaces?) for code readability? In the different projects I've worked on, people seem to have vastly different standards. I can't seem to read 2 space indents, but companies like Google use it as a standard. Can anyone point to documentation, studies, or well-reasoned arguments for the optimal size of a tab? If we want to get specific, I work mostly in python. The goal of this question is to pick a standard for the team I work on.
2009/05/01
[ "https://Stackoverflow.com/questions/809859", "https://Stackoverflow.com", "https://Stackoverflow.com/users/85271/" ]
I like 8 spaces (I know, right?). It makes the start/ end of blocks really obvious. As to your question, a formal usability study would be required. Let's look at limits though: **0 spaces** ``` function test(){ var x = 1; for (i=0; i<=5; i++){ doSomething(); } } ``` No indentation is obviously bad. You can't tell where anything begins or ends. **19 Spaces** ``` function test(){ var x = 1; for (i=0; i<=5; i++){ doSomething(); } } ``` Loads of indentation is obviously bad too, because you can't visually link code to its parent function or loop (or what have you) as your peripheral vision doesn't extend that far. Your eyes have to flick too far back and forth to facilitate reading. **8 spaces** ``` function test(){ var x = 1; for (i=0; i<=5; i++){ doSomething(); } } ``` I think I decided on 8 spaces because the word 'function' is 8 characters long. But it just seems so useful for readability. All the code is in my peripheral vision, and there's no way I can miss the start of a new block of code if I'm quickly scanning.
The argument for tab over spaces is that it allows each person to customize their editor to see whatever level of indentation they want. The argument against tabs is that it's difficult to spot (for the writer) when they've mixed tabs and spaces. Occasionally you will want lines that aren't indented to a tab stop, which causes mixed tabs/spaces. Using 2 spaces has these advantages: it's possible to have more nested blocks (this is important if you also have a line limit), and that using a double indent (ie 4 spaces) is nicely readable way of wrapping long lines. A disadvantage is that it's hard to judge sometimes whether two lines are at the same indent. Using 8 spaces has the opposite advantages and disadvantages to 2 spaces. It's easy to judge indent level, but you deep nesting becomes hard to manage. Many people would judge the latter disadvantage to be an advantage (because it makes deep nesting less desirable). 4 spaces is somewhere between these two extremes. But my personal belief is that it makes no difference what level of indentation you use. The most important thing is to pick some standard and stick to it. As others have said, follow PEP8 if you're writing python, follow Sun's java style guide if you're writing java, and if you're doing linux kernel hacking follow their style guide. Even if there were some small advantage in using one over the other, it's a waste of energy debating which to pick. Make a decision, and move on to the interesting part of software engineering.
809,859
Personal preferences aside, is there an optimal tab size (2 spaces? 3 spaces? 8 spaces?) for code readability? In the different projects I've worked on, people seem to have vastly different standards. I can't seem to read 2 space indents, but companies like Google use it as a standard. Can anyone point to documentation, studies, or well-reasoned arguments for the optimal size of a tab? If we want to get specific, I work mostly in python. The goal of this question is to pick a standard for the team I work on.
2009/05/01
[ "https://Stackoverflow.com/questions/809859", "https://Stackoverflow.com", "https://Stackoverflow.com/users/85271/" ]
[Four spaces and no hard tabs](https://david.goodger.org/projects/pycon/2007/idiomatic/handout.html#whitespace-1), if you're a Pythonista.
I read that 2 spaces is actually optimal, based on a study where programmers were asked to estimate the level of nesting based on indentation, but that when asked, programmers thought 4 would be optimal. Citation needed, but can't find it.
809,859
Personal preferences aside, is there an optimal tab size (2 spaces? 3 spaces? 8 spaces?) for code readability? In the different projects I've worked on, people seem to have vastly different standards. I can't seem to read 2 space indents, but companies like Google use it as a standard. Can anyone point to documentation, studies, or well-reasoned arguments for the optimal size of a tab? If we want to get specific, I work mostly in python. The goal of this question is to pick a standard for the team I work on.
2009/05/01
[ "https://Stackoverflow.com/questions/809859", "https://Stackoverflow.com", "https://Stackoverflow.com/users/85271/" ]
I think I recall that there is a section about indentation in [Code Complete](https://rads.stackoverflow.com/amzn/click/com/0735619670), quoting some studies about which level of identation makes the code most readable, but I do not have a copy of it with me right now, so I can't check it.
I've always used one tab as two spaces.
32,309,177
How do we do a DNS query, expecially MX query, in Python by not installing any third party libs. I want to query the MX record about a domain, however, it seems that `socket.getaddrinfo` can only query the A record. I have tried this: ``` python -c "import socket; print socket.getaddrinfo('baidu.com', 25, socket.AF_INET, socket.SOCK_DGRAM)" ``` This prints ``` [(2, 2, 17, '', ('220.181.57.217', 25)), (2, 2, 17, '', ('123.125.114.144', 25)), (2, 2, 17, '', ('180.149.132.47', 25))] ``` However, we can not telnet it with `telnet 220.181.57.217 25` or `telnet 123.125.114.144 25` or `telnet 180.149.132.47 25`.
2015/08/31
[ "https://Stackoverflow.com/questions/32309177", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1889327/" ]
Here's some rough low-level code for making a dns request using just the standard library if anyone's interested. ``` import secrets import socket # https://datatracker.ietf.org/doc/html/rfc1035 # https://www.iana.org/assignments/dns-parameters/dns-parameters.xhtml#table-dns-parameters-4 def dns_request(name, qtype=1, addr=('127.0.0.53', 53), timeout=1): # A 1, NS 2, CNAME 5, SOA 6, NULL 10, PTR 12, MX 15, TXT 16, AAAA 28, NAPTR 35, * 255 name = name.rstrip('.') queryid = secrets.token_bytes(2) # Header. 1 for Recursion Desired, 1 question, 0 answers, 0 ns, 0 additional request = queryid + b'\1\0\0\1\0\0\0\0\0\0' # Question for label in name.rstrip('.').split('.'): assert len(label) < 64, name request += int.to_bytes(len(label), length=1, byteorder='big') request += label.encode() request += b'\0' # terminates with the zero length octet for the null label of the root. request += int.to_bytes(qtype, length=2, byteorder='big') # QTYPE request += b'\0\1' # QCLASS = 1 with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s: s.sendto(request, addr) s.settimeout(timeout) try: response, serveraddr = s.recvfrom(4096) except socket.timeout: raise TimeoutError(name, timeout) assert serveraddr == addr, (serveraddr, addr) assert response[:2] == queryid, (response[:2], queryid) assert response[2] & 128 # QR = Response assert not response[2] & 4 # No Truncation assert response[3] & 128 # Recursion Available error_code = response[3] % 16 # 0 = no error, 1 = format error, 2 = server failure, 3 = does not exist, 4 = not implemented, 5 = refused qdcount = int.from_bytes(response[4:6], 'big') ancount = int.from_bytes(response[6:8], 'big') assert qdcount <= 1 # parse questions qa = response[12:] for question in range(qdcount): domain, qa = parse_qname(qa, response) qtype, qa = parse_int(qa, 2) qclass, qa = parse_int(qa, 2) # parse answers answers = [] for answer in range(ancount): domain, qa = parse_qname(qa, response) qtype, qa = parse_int(qa, 2) qclass, qa = parse_int(qa, 2) ttl, qa = parse_int(qa, 4) rdlength, qa = parse_int(qa, 2) rdata, qa = qa[:rdlength], qa[rdlength:] if qtype == 1: # IPv4 address rdata = '.'.join(str(x) for x in rdata) if qtype == 15: # MX mx_pref, rdata = parse_int(rdata, 2) if qtype in (2, 5, 12, 15): # NS, CNAME, MX rdata, _ = parse_qname(rdata, response) answer = (qtype, domain, ttl, rdata, mx_pref if qtype == 15 else None) answers.append(answer) return error_code, answers def parse_int(byts, ln): return int.from_bytes(byts[:ln], 'big'), byts[ln:] def parse_qname(byts, full_response): domain_parts = [] while True: if byts[0] // 64: # OFFSET pointer assert byts[0] // 64 == 3, byts[0] offset, byts = parse_int(byts, 2) offset = offset - (128 + 64) * 256 # clear out top 2 bits label, _ = parse_qname(full_response[offset:], full_response) domain_parts.append(label) break else: # regular QNAME ln, byts = parse_int(byts, 1) label, byts = byts[:ln], byts[ln:] if not label: break domain_parts.append(label.decode()) return '.'.join(domain_parts), byts ```
First Install dnspython ``` import dns.resolver answers = dns.resolver.query('dnspython.org', 'MX') for rdata in answers: print 'Host', rdata.exchange, 'has preference', rdata.preference ```
38,414,650
I've recently found this page: [Making PyObject\_HEAD conform to standard C](https://www.python.org/dev/peps/pep-3123/) and I'm curious about this paragraph: > > Standard C has one specific exception to its aliasing rules precisely designed to support the case of Python: a value of a struct type may also be accessed through a pointer to the first field. E.g. **if a struct starts with an int , the struct \* may also be cast to an int \* , allowing to write int values into the first field**. > > > So I wrote this code to check with my compilers: ``` struct with_int { int a; char b; }; int main(void) { struct with_int *i = malloc(sizeof(struct with_int)); i->a = 5; ((int *)&i)->a = 8; } ``` but I'm getting `error: request for member 'a' in something not a struct or union`. Did I get the above paragraph right? If no, what am I doing wrong? Also, if someone knows where C standard is referring to this rule, please point it out here. Thanks.
2016/07/16
[ "https://Stackoverflow.com/questions/38414650", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5960237/" ]
Your interpretation1 is correct, but the code isn't. The pointer `i` already points to the object, and thus to the first element, so you only need to cast it to the correct type: ``` int* n = ( int* )i; ``` then you simply dereference it: ``` *n = 345; ``` Or in one step: ``` *( int* )i = 345; ``` --- 1 (Quoted from: ISO:IEC 9899:201X 6.7.2.1 Structure and union specifiers 15) Within a structure object, the non-bit-field members and the units in which bit-fields reside have addresses that increase in the order in which they are declared. A pointer to a structure object, suitably converted, points to its initial member (or if that member is a bit-field, then to the unit in which it resides), and vice versa. There may be unnamed padding within a structure object, but not at its beginning.
You have a few issues, but this works for me: ``` #include <malloc.h> #include <stdio.h> struct with_int { int a; char b; }; int main(void) { struct with_int *i = (struct with_int *)malloc(sizeof(struct with_int)); i->a = 5; *(int *)i = 8; printf("%d\n", i->a); } ``` Output is: 8
38,414,650
I've recently found this page: [Making PyObject\_HEAD conform to standard C](https://www.python.org/dev/peps/pep-3123/) and I'm curious about this paragraph: > > Standard C has one specific exception to its aliasing rules precisely designed to support the case of Python: a value of a struct type may also be accessed through a pointer to the first field. E.g. **if a struct starts with an int , the struct \* may also be cast to an int \* , allowing to write int values into the first field**. > > > So I wrote this code to check with my compilers: ``` struct with_int { int a; char b; }; int main(void) { struct with_int *i = malloc(sizeof(struct with_int)); i->a = 5; ((int *)&i)->a = 8; } ``` but I'm getting `error: request for member 'a' in something not a struct or union`. Did I get the above paragraph right? If no, what am I doing wrong? Also, if someone knows where C standard is referring to this rule, please point it out here. Thanks.
2016/07/16
[ "https://Stackoverflow.com/questions/38414650", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5960237/" ]
You have a few issues, but this works for me: ``` #include <malloc.h> #include <stdio.h> struct with_int { int a; char b; }; int main(void) { struct with_int *i = (struct with_int *)malloc(sizeof(struct with_int)); i->a = 5; *(int *)i = 8; printf("%d\n", i->a); } ``` Output is: 8
Like other answers have pointed out, I think you meant: ``` // Interpret (struct with_int *) as (int *), then // dereference it to assign the value 8. *((int *) i) = 8; ``` and not: ``` ((int *) &i)->a = 8; ``` However, none of the answers explain specifically why that error makes sense. Let me explain what `((int *) &i)->a` means: `i` is a variable that holds an address to a `(struct with_int)`. `&i` is the address on main() function's stack space. This means `&i` is an address, that contains an address to a `(struct with_int)`. In other words, `&i` is a pointer to a pointer to `(struct with_int)`. Then the cast `(int *)` of this would tell the compiler to interpret this stack address as an `int` pointer, that is, address of an `int`. Finally, with that `->a`, you are asking the compiler to fetch the struct member `a` from this `int` pointer and then assign the value 8 to it. It doesn't make sense to fetch a struct member from an `int` pointer. Hence, you get `error: request for member 'a' in something not a struct or union`. Hope this helps.
38,414,650
I've recently found this page: [Making PyObject\_HEAD conform to standard C](https://www.python.org/dev/peps/pep-3123/) and I'm curious about this paragraph: > > Standard C has one specific exception to its aliasing rules precisely designed to support the case of Python: a value of a struct type may also be accessed through a pointer to the first field. E.g. **if a struct starts with an int , the struct \* may also be cast to an int \* , allowing to write int values into the first field**. > > > So I wrote this code to check with my compilers: ``` struct with_int { int a; char b; }; int main(void) { struct with_int *i = malloc(sizeof(struct with_int)); i->a = 5; ((int *)&i)->a = 8; } ``` but I'm getting `error: request for member 'a' in something not a struct or union`. Did I get the above paragraph right? If no, what am I doing wrong? Also, if someone knows where C standard is referring to this rule, please point it out here. Thanks.
2016/07/16
[ "https://Stackoverflow.com/questions/38414650", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5960237/" ]
Your interpretation1 is correct, but the code isn't. The pointer `i` already points to the object, and thus to the first element, so you only need to cast it to the correct type: ``` int* n = ( int* )i; ``` then you simply dereference it: ``` *n = 345; ``` Or in one step: ``` *( int* )i = 345; ``` --- 1 (Quoted from: ISO:IEC 9899:201X 6.7.2.1 Structure and union specifiers 15) Within a structure object, the non-bit-field members and the units in which bit-fields reside have addresses that increase in the order in which they are declared. A pointer to a structure object, suitably converted, points to its initial member (or if that member is a bit-field, then to the unit in which it resides), and vice versa. There may be unnamed padding within a structure object, but not at its beginning.
Like other answers have pointed out, I think you meant: ``` // Interpret (struct with_int *) as (int *), then // dereference it to assign the value 8. *((int *) i) = 8; ``` and not: ``` ((int *) &i)->a = 8; ``` However, none of the answers explain specifically why that error makes sense. Let me explain what `((int *) &i)->a` means: `i` is a variable that holds an address to a `(struct with_int)`. `&i` is the address on main() function's stack space. This means `&i` is an address, that contains an address to a `(struct with_int)`. In other words, `&i` is a pointer to a pointer to `(struct with_int)`. Then the cast `(int *)` of this would tell the compiler to interpret this stack address as an `int` pointer, that is, address of an `int`. Finally, with that `->a`, you are asking the compiler to fetch the struct member `a` from this `int` pointer and then assign the value 8 to it. It doesn't make sense to fetch a struct member from an `int` pointer. Hence, you get `error: request for member 'a' in something not a struct or union`. Hope this helps.
65,521,446
When typing a word in a dash input I would like to get autosuggestions, an example of what I mean is this CLI app I made in the past. [![enter image description here](https://i.stack.imgur.com/SPzmM.png)](https://i.stack.imgur.com/SPzmM.png) a link to the documentation: <https://python-prompt-toolkit.readthedocs.io/en/master/pages/asking_for_input.html?highlight=suggestions#autocompletion> 3 Thank you in advance!
2020/12/31
[ "https://Stackoverflow.com/questions/65521446", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14008858/" ]
`:` is missing after the third `while` statement, also `except` and `print` statements have the same indentation level. You can use `try-except` without additional `while` loop, check if the input number is less then `11` and append the input the the list and if not break the while loop. ***Example***: ``` while True: try: grade = int(input("Please enter the student grade, enter '11' to quit this program:")) if grade >= 11: break student_list.append(grade) except ValueError: print("Please input integer between 1-10") ```
flows answered your question appropriately. Because I think you would like to ask for pairs of name and grade, I modified your program a little. ``` def student_data(): student_list = [] while True: # Ask for the name of the student student_name = input("Please enter the student name, press 'q' to quit this program: ") # When "q" is entered exit the loop. if student_name.lower() == 'q': break # Keep asking about the student's grade until a valid answer has been entered. while True: try: student_grade = int(input("Please enter a grade between 1-10: ")) # If an error occurs during the conversion, the following lines # are not executed. A direct jump is made to the except block. if 0 < student_grade <= 10: # If the value is within the expected limits add a tuple of # name and grade to the list and exit the nested loop. student_list.append((student_name, student_grade)) break except ValueError: # Ignore errors when converting the string to integer. pass # Return all pairs of name and grade as the result of the function. return student_list for name, grade in student_data(): print('You entered: ', name, grade) ```
67,655,396
I'm trying to migrate my custom user model and I run makemigrations command to make migrations for new models. But when I run migrate command it throws this error : > > conn = \_connect(dsn, connection\_factory=connection\_factory, > \*\*kwasync) django.db.utils.OperationalError > > > **Trace back:** ``` (venv_ruling) C:\Users\enosh\venv_ruling\ruling>python manage.py migrate Traceback (most recent call last): File "C:\Users\enosh\venv_ruling\lib\site-packages\django\db\backends\base\base.py", line 219, in ensure_connection self.connect() File "C:\Users\enosh\venv_ruling\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\enosh\venv_ruling\lib\site-packages\django\db\backends\base\base.py", line 200, in connect self.connection = self.get_new_connection(conn_params) File "C:\Users\enosh\venv_ruling\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\enosh\venv_ruling\lib\site-packages\django\db\backends\postgresql\base.py", line 187, in get_new_connection connection = Database.connect(**conn_params) File "C:\Users\enosh\venv_ruling\lib\site-packages\psycopg2\__init__.py", line 127, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\enosh\venv_ruling\ruling\manage.py", line 22, in <module> main() File "C:\Users\enosh\venv_ruling\ruling\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\enosh\venv_ruling\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "C:\Users\enosh\venv_ruling\lib\site-packages\django\core\management\__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\enosh\venv_ruling\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\enosh\venv_ruling\lib\site-packages\django\core\management\base.py", line 398, in execute output = self.handle(*args, **options) File "C:\Users\enosh\venv_ruling\lib\site-packages\django\core\management\base.py", line 89, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\enosh\venv_ruling\lib\site-packages\django\core\management\commands\migrate.py", line 75, in handle self.check(databases=[database]) File "C:\Users\enosh\venv_ruling\lib\site-packages\django\core\management\base.py", line 419, in check all_issues = checks.run_checks( File "C:\Users\enosh\venv_ruling\lib\site-packages\django\core\checks\registry.py", line 76, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Users\enosh\venv_ruling\lib\site-packages\django\core\checks\model_checks.py", line 34, in check_all_models errors.extend(model.check(**kwargs)) File "C:\Users\enosh\venv_ruling\lib\site-packages\django\db\models\base.py", line 1290, in check *cls._check_indexes(databases), File "C:\Users\enosh\venv_ruling\lib\site-packages\django\db\models\base.py", line 1680, in _check_indexes connection.features.supports_covering_indexes or File "C:\Users\enosh\venv_ruling\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\enosh\venv_ruling\lib\site-packages\django\db\backends\postgresql\features.py", line 93, in is_postgresql_11 return self.connection.pg_version >= 110000 File "C:\Users\enosh\venv_ruling\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\enosh\venv_ruling\lib\site-packages\django\db\backends\postgresql\base.py", line 329, in pg_version with self.temporary_connection(): File "C:\Users\enosh\AppData\Local\Programs\Python\Python39\lib\contextlib.py", line 117, in __enter__ return next(self.gen) File "C:\Users\enosh\venv_ruling\lib\site-packages\django\db\backends\base\base.py", line 603, in temporary_connection with self.cursor() as cursor: File "C:\Users\enosh\venv_ruling\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\enosh\venv_ruling\lib\site-packages\django\db\backends\base\base.py", line 259, in cursor return self._cursor() File "C:\Users\enosh\venv_ruling\lib\site-packages\django\db\backends\base\base.py", line 235, in _cursor self.ensure_connection() File "C:\Users\enosh\venv_ruling\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\enosh\venv_ruling\lib\site-packages\django\db\backends\base\base.py", line 219, in ensure_connection self.connect() File "C:\Users\enosh\venv_ruling\lib\site-packages\django\db\utils.py", line 90, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "C:\Users\enosh\venv_ruling\lib\site-packages\django\db\backends\base\base.py", line 219, in ensure_connection self.connect() File "C:\Users\enosh\venv_ruling\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\enosh\venv_ruling\lib\site-packages\django\db\backends\base\base.py", line 200, in connect self.connection = self.get_new_connection(conn_params) File "C:\Users\enosh\venv_ruling\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\enosh\venv_ruling\lib\site-packages\django\db\backends\postgresql\base.py", line 187, in get_new_connection connection = Database.connect(**conn_params) File "C:\Users\enosh\venv_ruling\lib\site-packages\psycopg2\__init__.py", line 127, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) django.db.utils.OperationalError ``` **models.py** ``` from django.contrib.auth.models import AbstractUser class CustomUser(AbstractUser): """extend usermodel""" class Meta: verbose_name_plural = 'CustomUser' ``` **settings.py** ``` DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'rulings', 'USER': 'xxxxxxx', 'PASSWORD': 'xxxxxxx', 'HOST': '', 'PORT': '', } } AUTH_USER_MODEL = 'accounts.CustomUser' ``` The postgresql's database is empty.(ver.12.6) I just mentioned user model and settings in this question but still if more code is required then tell me I'll update my question with that information. Thank you
2021/05/23
[ "https://Stackoverflow.com/questions/67655396", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14472949/" ]
> > I'm trying to understand Linux OS library dependencies to effectively run python 3.9 and imported pip packages to work. > > > Your questions may have pretty broad answers and depend on a bunch of input factors you haven't mentioned. > > Is there a requirement for GCC to be installed for pip modules with c extention modules to run? > > > It depends how the package is built and shipped. If it is available only as a *source distribution* (`sdist`), then yes. Obviously a compiler is needed to take the `.c` files and produce a laudable binary extension (ELF or DLL). Some packages ship *binary distributions*, where the publisher does the compilation for you. Of course this is more of a burden on the publisher, as they must support many possible target machines. > > What system libraries does Python's interpreter depends on? > > > It depends on a number of things, including which interpreter (there are multiple!) and how it was built and packaged. Even constraining the discussion to CPython (the canonical interpreter), this may vary widely. The simplest thing to do is whatever your Linux distro has decided for you; just `apt install python3` or whatever, and don't think too hard about it. Most distros ship dynamically-linked packages; these will depend on a small number of "common" libraries (e.g. `libc`, `libz`, etc). Some distros will statically-link the Python *library* into the interpreter -- IOW the `python3` executable will *not* depend on `libpython3.so`. Other distros will dynamically link against libpython. What dependencies will external modules (e.g. from PyPI) have? Well that *completely* depends on the package in question! Hopefully this helps you understand the limitations of your question. If you need more specific answers, you'll need to either do your own research, or provide a more specific question.
Python depends on compilers and a lot of other tools if you're going to compile the source (from the repository). This is from the offical repository, telling you what you need to compile it from source, [check it out](https://devguide.python.org/setup/#install-dependencies). > > **1.4. Install dependencies** > This section explains how to install additional extensions (e.g. zlib) on Linux and macOs/OS X. On Windows, extensions are already included and built automatically. > > > **1.4.1. Linux** > > > > > > > For UNIX based systems, we try to use system libraries whenever available. This means optional components will only build if the relevant system headers are available. The best way to obtain the appropriate headers will vary by distribution, but the appropriate commands for some popular distributions are below. > > > > > > > > > However, if you just want to **run python programs**, all you need is the python binary (and the libraries your script wants to use). The binary is usually at `/usr/bin/python3` or `/usr/bin/python3.9` [Python GitHub Repository](https://github.com/python/cpython) For individual packages, it depends on the package. Further reading: * [What is PIP?](https://realpython.com/what-is-pip/) * [Official: Managing application dependencies](https://packaging.python.org/tutorials/managing-dependencies/)
51,346,677
``` ERROR: build step 1 "gcr.io/gae-runtimes/nodejs8_app_builder:nodejs8_20180618_RC02" failed: exit status 1 ERROR Finished Step #1 - "builder" Step #1 - "builder": Permission denied for "be8392bdf4a2c92301391a124a5b72078453db3c15fcfc71f923e3c63d1bd8ea" from request "/v2/PROJECT_ID/app-engine-build-cache/node-cache/manifests/be8392bdf4a2c92301391a124a5b72078453db3c15fcfc71f923e3c63d1bd8ea". : None Step #1 - "builder": containerregistry.client.v2_2.docker_http_.V2DiagnosticException: response: {'status': '403', 'content-length': '291', 'x-xss-protection': '1; mode=block', 'transfer-encoding': 'chunked', 'server': 'Docker Registry', '-content-encoding': 'gzip', 'docker-distribution-api-version': 'registry/2.0', 'cache-control': 'private', 'date': 'Sun, 15 Jul 2018 08:26:14 GMT', 'x-frame-options': 'SAMEORIGIN', 'content-type': 'application/json'} Step #1 - "builder": File "/ftl-v0.4.0.par/containerregistry/client/v2_2/docker_http_.py", line 364, in Request Step #1 - "builder": File "/ftl-v0.4.0.par/containerregistry/client/v2_2/docker_image_.py", line 250, in _content Step #1 - "builder": File "/ftl-v0.4.0.par/containerregistry/client/v2_2/docker_image_.py", line 293, in manifest Step #1 - "builder": File "/ftl-v0.4.0.par/containerregistry/client/v2_2/docker_image_.py", line 279, in exists Step #1 - "builder": File "/ftl-v0.4.0.par/__main__/ftl/common/cache.py", line 166, in getEntryFromCreds Step #1 - "builder": File "/ftl-v0.4.0.par/__main__/ftl/common/cache.py", line 143, in _getLocalEntry Step #1 - "builder": File "/ftl-v0.4.0.par/__main__/ftl/common/cache.py", line 128, in _getEntry Step #1 - "builder": File "/ftl-v0.4.0.par/__main__/ftl/common/cache.py", line 110, in Get Step #1 - "builder": File "/ftl-v0.4.0.par/__main__/ftl/node/layer_builder.py", line 55, in BuildLayer Step #1 - "builder": File "/ftl-v0.4.0.par/__main__/ftl/node/builder.py", line 38, in Build Step #1 - "builder": File "/ftl-v0.4.0.par/__main__.py", line 52, in main Step #1 - "builder": File "/ftl-v0.4.0.par/__main__.py", line 61, in Step #1 - "builder": exec code in run_globals Step #1 - "builder": File "/usr/lib/python2.7/runpy.py", line 72, in _run_code Step #1 - "builder": "__main__", fname, loader, pkg_name) Step #1 - "builder": File "/usr/lib/python2.7/runpy.py", line 174, in _run_module_as_main Step #1 - "builder": Traceback (most recent call last): Step #1 - "builder": INFO full build took 0 seconds Step #1 - "builder": INFO build process for FTL image took 0 seconds Step #1 - "builder": INFO checking_cached_packages_json_layer took 0 seconds Step #1 - "builder": DEBUG Checking cache for cache_key be8392bdf4a2c92301391a124a5b72078453db3c15fcfc71f923e3c63d1bd8ea Step #1 - "builder": INFO starting: checking_cached_packages_json_layer Step #1 - "builder": INFO starting: build process for FTL image Step #1 - "builder": INFO builder initialization took 0 seconds Step #1 - "builder": INFO Loading Docker credentials for repository 'asia.gcr.io/PROJECT_ID/app-engine/default/20180715t135547:6382e88f-f9db-4087-9eca-2a1aee5881d6' Step #1 - "builder": INFO Loading Docker credentials for repository 'gcr.io/gae-runtimes/nodejs8:nodejs8_20180618_RC02' Step #1 - "builder": INFO starting: builder initialization Step #1 - "builder": INFO starting: full build Step #1 - "builder": INFO FTL arg passed: verbosity NOTSET Step #1 - "builder": INFO FTL arg passed: destination_path /srv Step #1 - "builder": INFO FTL arg passed: entrypoint None Step #1 - "builder": INFO FTL arg passed: directory /workspace Step #1 - "builder": INFO FTL arg passed: output_path None Step #1 - "builder": INFO FTL arg passed: base gcr.io/gae-runtimes/nodejs8:nodejs8_20180618_RC02 Step #1 - "builder": INFO FTL arg passed: upload True Step #1 - "builder": INFO FTL arg passed: cache True Step #1 - "builder": INFO FTL arg passed: global_cache False Step #1 - "builder": INFO FTL arg passed: name asia.gcr.io/PROJECT_ID/app-engine/default/20180715t135547:6382e88f-f9db-4087-9eca-2a1aee5881d6 Step #1 - "builder": INFO FTL arg passed: builder_output_path /builder/outputs Step #1 - "builder": INFO FTL arg passed: tar_base_image_path None Step #1 - "builder": INFO FTL arg passed: cache_repository asia.gcr.io/PROJECT_ID/app-engine-build-cache Step #1 - "builder": INFO FTL arg passed: exposed_ports None Step #1 - "builder": INFO Beginning FTL build for node Step #1 - "builder": INFO FTL version node-v0.4.0 Step #1 - "builder": Status: Downloaded newer image for gcr.io/gae-runtimes/nodejs8_app_builder:nodejs8_20180618_RC02 Step #1 - "builder": Digest: sha256:f937017daa12ccde31d70836e640ef0eaf327436695d05da38e4290c2eb2eb70 Step #1 - "builder": nodejs8_20180618_RC02: Pulling from gae-runtimes/nodejs8_app_builder Step #1 - "builder": Pulling image: gcr.io/gae-runtimes/nodejs8_app_builder:nodejs8_20180618_RC02 Starting Step #1 - "builder" Finished Step #0 - "fetcher" Step #0 - "fetcher": 2018/07/15 08:26:12 ****************************************************** Step #0 - "fetcher": 2018/07/15 08:26:12 Total time: 2.04 s Step #0 - "fetcher": 2018/07/15 08:26:12 Time for manifest: 888.14 ms Step #0 - "fetcher": 2018/07/15 08:26:12 MiB/s throughput: 0.28 MiB/s Step #0 - "fetcher": 2018/07/15 08:26:12 MiB downloaded: 0.33 MiB Step #0 - "fetcher": 2018/07/15 08:26:12 GCS timeouts: 0 Step #0 - "fetcher": 2018/07/15 08:26:12 Total retries: 0 Step #0 - "fetcher": 2018/07/15 08:26:12 Total files: 16 Step #0 - "fetcher": 2018/07/15 08:26:12 Actual workers: 16 Step #0 - "fetcher": 2018/07/15 08:26:12 Requested workers: 200 Step #0 - "fetcher": 2018/07/15 08:26:12 Completed: 2018-07-15T08:26:12Z Step #0 - "fetcher": 2018/07/15 08:26:12 Started: 2018-07-15T08:26:10Z Step #0 - "fetcher": 2018/07/15 08:26:12 Status: SUCCESS Step #0 - "fetcher": 2018/07/15 08:26:12 ****************************************************** Step #0 - "fetcher": 2018/07/15 08:26:12 Fetched gs://staging.PROJECT_ID.appspot.com/5e9210875e15a2eb7d50c666136266837638eb03 (322831B in 1.145458029s, 0.27MiB/s) Step #0 - "fetcher": 2018/07/15 08:26:12 Fetched gs://staging.PROJECT_ID.appspot.com/058b7e502bf6750c6f01453ef947d5dd7e854e07 (1279B in 861.521735ms, 0.00MiB/s) Step #0 - "fetcher": 2018/07/15 08:26:12 Fetched gs://staging.PROJECT_ID.appspot.com/5d87534d139519ba7cec4d48d2c3ba27b99e80b0 (319B in 846.233597ms, 0.00MiB/s) Step #0 - "fetcher": 2018/07/15 08:26:12 Fetched gs://staging.PROJECT_ID.appspot.com/668461d157d199b783be12fd2f2ba9c6d154130c (1271B in 838.8342ms, 0.00MiB/s) Step #0 - "fetcher": 2018/07/15 08:26:11 Fetched gs://staging.PROJECT_ID.appspot.com/8dd0bca621558e6ce972f38d8aa9765e49436172 (327B in 589.603096ms, 0.00MiB/s) Step #0 - "fetcher": 2018/07/15 08:26:11 Fetched gs://staging.PROJECT_ID.appspot.com/c6b4f62664bbe2779fdff10261bc384708e73e7d (36B in 588.36617ms, 0.00MiB/s) Step #0 - "fetcher": 2018/07/15 08:26:11 Fetched gs://staging.PROJECT_ID.appspot.com/c271c61f49150008a5eeae99a9bd09570bd5d549 (2558B in 588.802856ms, 0.00MiB/s) Step #0 - "fetcher": 2018/07/15 08:26:11 Fetched gs://staging.PROJECT_ID.appspot.com/f293a6701e6de41513ba08b50bbbacb58ffbc19a (119B in 586.215815ms, 0.00MiB/s) Step #0 - "fetcher": 2018/07/15 08:26:11 Fetched gs://staging.PROJECT_ID.appspot.com/88ef0fc94347f5e38160bdacef44fedc51b85877 (2305B in 584.714922ms, 0.00MiB/s) Step #0 - "fetcher": 2018/07/15 08:26:11 Fetched gs://staging.PROJECT_ID.appspot.com/73c3a01c14c7b696454020d6dc917ea32a50872c (53B in 584.291891ms, 0.00MiB/s) Step #0 - "fetcher": 2018/07/15 08:26:11 Fetched gs://staging.PROJECT_ID.appspot.com/757cebb200f220928061cdabddd6126d67a46984 (1683B in 583.3675ms, 0.00MiB/s) Step #0 - "fetcher": 2018/07/15 08:26:11 Fetched gs://staging.PROJECT_ID.appspot.com/1bbf5d56ff53e82b6444cab2a87d43b14d23a8b3 (217B in 584.334096ms, 0.00MiB/s) Step #0 - "fetcher": 2018/07/15 08:26:11 Fetched gs://staging.PROJECT_ID.appspot.com/42a994f47562d763d59a4b64822554d24f0ffce7 (28B in 577.748008ms, 0.00MiB/s) Step #0 - "fetcher": 2018/07/15 08:26:11 Fetched gs://staging.PROJECT_ID.appspot.com/f9185bdfc5b57bef24b52a9bbeb09cdf981f279f (2495B in 579.458821ms, 0.00MiB/s) Step #0 - "fetcher": 2018/07/15 08:26:11 Fetched gs://staging.PROJECT_ID.appspot.com/0c676a042d5ad4e493046f23965ed648293225be (3162B in 577.802151ms, 0.01MiB/s) Step #0 - "fetcher": 2018/07/15 08:26:11 Fetched gs://staging.PROJECT_ID.appspot.com/5bf6fe209f6ec1a459ae628d8f94e6aedbf3abae (2675B in 571.413697ms, 0.00MiB/s) Step #0 - "fetcher": 2018/07/15 08:26:11 Processing 16 files. Step #0 - "fetcher": 2018/07/15 08:26:11 Fetched gs://staging.PROJECT_ID.appspot.com/ae/6382e88f-f9db-4087-9eca-2a1aee5881d6/manifest.json (3576B in 888.138003ms, 0.00MiB/s) Step #0 - "fetcher": 2018/07/15 08:26:10 Fetching manifest gs://staging.PROJECT_ID.appspot.com/ae/6382e88f-f9db-4087-9eca-2a1aee5881d6/manifest.json. Step #0 - "fetcher": Already have image (with digest): gcr.io/cloud-builders/gcs-fetcher Starting Step #0 - "fetcher" BUILD FETCHSOURCE starting build "88e0cc7f-62b7-496a-aa31-230e793b5ea1" ```
2018/07/15
[ "https://Stackoverflow.com/questions/51346677", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8025518/" ]
> > ### Troubleshooting > > > If you find 403 (access denied) errors in your build logs, try the following steps: > > > Disable the Cloud Build API and re-enable it. Doing so should give your service account access to your project again. > > > Fixed an issue for me.
It shows in the 1st few lines of the log that image couldnt be pulled from registry due to unauthorized user credentials accessing the registry. Did you check the credentials? If you have a token based login, check if the token is not expired.
51,346,677
``` ERROR: build step 1 "gcr.io/gae-runtimes/nodejs8_app_builder:nodejs8_20180618_RC02" failed: exit status 1 ERROR Finished Step #1 - "builder" Step #1 - "builder": Permission denied for "be8392bdf4a2c92301391a124a5b72078453db3c15fcfc71f923e3c63d1bd8ea" from request "/v2/PROJECT_ID/app-engine-build-cache/node-cache/manifests/be8392bdf4a2c92301391a124a5b72078453db3c15fcfc71f923e3c63d1bd8ea". : None Step #1 - "builder": containerregistry.client.v2_2.docker_http_.V2DiagnosticException: response: {'status': '403', 'content-length': '291', 'x-xss-protection': '1; mode=block', 'transfer-encoding': 'chunked', 'server': 'Docker Registry', '-content-encoding': 'gzip', 'docker-distribution-api-version': 'registry/2.0', 'cache-control': 'private', 'date': 'Sun, 15 Jul 2018 08:26:14 GMT', 'x-frame-options': 'SAMEORIGIN', 'content-type': 'application/json'} Step #1 - "builder": File "/ftl-v0.4.0.par/containerregistry/client/v2_2/docker_http_.py", line 364, in Request Step #1 - "builder": File "/ftl-v0.4.0.par/containerregistry/client/v2_2/docker_image_.py", line 250, in _content Step #1 - "builder": File "/ftl-v0.4.0.par/containerregistry/client/v2_2/docker_image_.py", line 293, in manifest Step #1 - "builder": File "/ftl-v0.4.0.par/containerregistry/client/v2_2/docker_image_.py", line 279, in exists Step #1 - "builder": File "/ftl-v0.4.0.par/__main__/ftl/common/cache.py", line 166, in getEntryFromCreds Step #1 - "builder": File "/ftl-v0.4.0.par/__main__/ftl/common/cache.py", line 143, in _getLocalEntry Step #1 - "builder": File "/ftl-v0.4.0.par/__main__/ftl/common/cache.py", line 128, in _getEntry Step #1 - "builder": File "/ftl-v0.4.0.par/__main__/ftl/common/cache.py", line 110, in Get Step #1 - "builder": File "/ftl-v0.4.0.par/__main__/ftl/node/layer_builder.py", line 55, in BuildLayer Step #1 - "builder": File "/ftl-v0.4.0.par/__main__/ftl/node/builder.py", line 38, in Build Step #1 - "builder": File "/ftl-v0.4.0.par/__main__.py", line 52, in main Step #1 - "builder": File "/ftl-v0.4.0.par/__main__.py", line 61, in Step #1 - "builder": exec code in run_globals Step #1 - "builder": File "/usr/lib/python2.7/runpy.py", line 72, in _run_code Step #1 - "builder": "__main__", fname, loader, pkg_name) Step #1 - "builder": File "/usr/lib/python2.7/runpy.py", line 174, in _run_module_as_main Step #1 - "builder": Traceback (most recent call last): Step #1 - "builder": INFO full build took 0 seconds Step #1 - "builder": INFO build process for FTL image took 0 seconds Step #1 - "builder": INFO checking_cached_packages_json_layer took 0 seconds Step #1 - "builder": DEBUG Checking cache for cache_key be8392bdf4a2c92301391a124a5b72078453db3c15fcfc71f923e3c63d1bd8ea Step #1 - "builder": INFO starting: checking_cached_packages_json_layer Step #1 - "builder": INFO starting: build process for FTL image Step #1 - "builder": INFO builder initialization took 0 seconds Step #1 - "builder": INFO Loading Docker credentials for repository 'asia.gcr.io/PROJECT_ID/app-engine/default/20180715t135547:6382e88f-f9db-4087-9eca-2a1aee5881d6' Step #1 - "builder": INFO Loading Docker credentials for repository 'gcr.io/gae-runtimes/nodejs8:nodejs8_20180618_RC02' Step #1 - "builder": INFO starting: builder initialization Step #1 - "builder": INFO starting: full build Step #1 - "builder": INFO FTL arg passed: verbosity NOTSET Step #1 - "builder": INFO FTL arg passed: destination_path /srv Step #1 - "builder": INFO FTL arg passed: entrypoint None Step #1 - "builder": INFO FTL arg passed: directory /workspace Step #1 - "builder": INFO FTL arg passed: output_path None Step #1 - "builder": INFO FTL arg passed: base gcr.io/gae-runtimes/nodejs8:nodejs8_20180618_RC02 Step #1 - "builder": INFO FTL arg passed: upload True Step #1 - "builder": INFO FTL arg passed: cache True Step #1 - "builder": INFO FTL arg passed: global_cache False Step #1 - "builder": INFO FTL arg passed: name asia.gcr.io/PROJECT_ID/app-engine/default/20180715t135547:6382e88f-f9db-4087-9eca-2a1aee5881d6 Step #1 - "builder": INFO FTL arg passed: builder_output_path /builder/outputs Step #1 - "builder": INFO FTL arg passed: tar_base_image_path None Step #1 - "builder": INFO FTL arg passed: cache_repository asia.gcr.io/PROJECT_ID/app-engine-build-cache Step #1 - "builder": INFO FTL arg passed: exposed_ports None Step #1 - "builder": INFO Beginning FTL build for node Step #1 - "builder": INFO FTL version node-v0.4.0 Step #1 - "builder": Status: Downloaded newer image for gcr.io/gae-runtimes/nodejs8_app_builder:nodejs8_20180618_RC02 Step #1 - "builder": Digest: sha256:f937017daa12ccde31d70836e640ef0eaf327436695d05da38e4290c2eb2eb70 Step #1 - "builder": nodejs8_20180618_RC02: Pulling from gae-runtimes/nodejs8_app_builder Step #1 - "builder": Pulling image: gcr.io/gae-runtimes/nodejs8_app_builder:nodejs8_20180618_RC02 Starting Step #1 - "builder" Finished Step #0 - "fetcher" Step #0 - "fetcher": 2018/07/15 08:26:12 ****************************************************** Step #0 - "fetcher": 2018/07/15 08:26:12 Total time: 2.04 s Step #0 - "fetcher": 2018/07/15 08:26:12 Time for manifest: 888.14 ms Step #0 - "fetcher": 2018/07/15 08:26:12 MiB/s throughput: 0.28 MiB/s Step #0 - "fetcher": 2018/07/15 08:26:12 MiB downloaded: 0.33 MiB Step #0 - "fetcher": 2018/07/15 08:26:12 GCS timeouts: 0 Step #0 - "fetcher": 2018/07/15 08:26:12 Total retries: 0 Step #0 - "fetcher": 2018/07/15 08:26:12 Total files: 16 Step #0 - "fetcher": 2018/07/15 08:26:12 Actual workers: 16 Step #0 - "fetcher": 2018/07/15 08:26:12 Requested workers: 200 Step #0 - "fetcher": 2018/07/15 08:26:12 Completed: 2018-07-15T08:26:12Z Step #0 - "fetcher": 2018/07/15 08:26:12 Started: 2018-07-15T08:26:10Z Step #0 - "fetcher": 2018/07/15 08:26:12 Status: SUCCESS Step #0 - "fetcher": 2018/07/15 08:26:12 ****************************************************** Step #0 - "fetcher": 2018/07/15 08:26:12 Fetched gs://staging.PROJECT_ID.appspot.com/5e9210875e15a2eb7d50c666136266837638eb03 (322831B in 1.145458029s, 0.27MiB/s) Step #0 - "fetcher": 2018/07/15 08:26:12 Fetched gs://staging.PROJECT_ID.appspot.com/058b7e502bf6750c6f01453ef947d5dd7e854e07 (1279B in 861.521735ms, 0.00MiB/s) Step #0 - "fetcher": 2018/07/15 08:26:12 Fetched gs://staging.PROJECT_ID.appspot.com/5d87534d139519ba7cec4d48d2c3ba27b99e80b0 (319B in 846.233597ms, 0.00MiB/s) Step #0 - "fetcher": 2018/07/15 08:26:12 Fetched gs://staging.PROJECT_ID.appspot.com/668461d157d199b783be12fd2f2ba9c6d154130c (1271B in 838.8342ms, 0.00MiB/s) Step #0 - "fetcher": 2018/07/15 08:26:11 Fetched gs://staging.PROJECT_ID.appspot.com/8dd0bca621558e6ce972f38d8aa9765e49436172 (327B in 589.603096ms, 0.00MiB/s) Step #0 - "fetcher": 2018/07/15 08:26:11 Fetched gs://staging.PROJECT_ID.appspot.com/c6b4f62664bbe2779fdff10261bc384708e73e7d (36B in 588.36617ms, 0.00MiB/s) Step #0 - "fetcher": 2018/07/15 08:26:11 Fetched gs://staging.PROJECT_ID.appspot.com/c271c61f49150008a5eeae99a9bd09570bd5d549 (2558B in 588.802856ms, 0.00MiB/s) Step #0 - "fetcher": 2018/07/15 08:26:11 Fetched gs://staging.PROJECT_ID.appspot.com/f293a6701e6de41513ba08b50bbbacb58ffbc19a (119B in 586.215815ms, 0.00MiB/s) Step #0 - "fetcher": 2018/07/15 08:26:11 Fetched gs://staging.PROJECT_ID.appspot.com/88ef0fc94347f5e38160bdacef44fedc51b85877 (2305B in 584.714922ms, 0.00MiB/s) Step #0 - "fetcher": 2018/07/15 08:26:11 Fetched gs://staging.PROJECT_ID.appspot.com/73c3a01c14c7b696454020d6dc917ea32a50872c (53B in 584.291891ms, 0.00MiB/s) Step #0 - "fetcher": 2018/07/15 08:26:11 Fetched gs://staging.PROJECT_ID.appspot.com/757cebb200f220928061cdabddd6126d67a46984 (1683B in 583.3675ms, 0.00MiB/s) Step #0 - "fetcher": 2018/07/15 08:26:11 Fetched gs://staging.PROJECT_ID.appspot.com/1bbf5d56ff53e82b6444cab2a87d43b14d23a8b3 (217B in 584.334096ms, 0.00MiB/s) Step #0 - "fetcher": 2018/07/15 08:26:11 Fetched gs://staging.PROJECT_ID.appspot.com/42a994f47562d763d59a4b64822554d24f0ffce7 (28B in 577.748008ms, 0.00MiB/s) Step #0 - "fetcher": 2018/07/15 08:26:11 Fetched gs://staging.PROJECT_ID.appspot.com/f9185bdfc5b57bef24b52a9bbeb09cdf981f279f (2495B in 579.458821ms, 0.00MiB/s) Step #0 - "fetcher": 2018/07/15 08:26:11 Fetched gs://staging.PROJECT_ID.appspot.com/0c676a042d5ad4e493046f23965ed648293225be (3162B in 577.802151ms, 0.01MiB/s) Step #0 - "fetcher": 2018/07/15 08:26:11 Fetched gs://staging.PROJECT_ID.appspot.com/5bf6fe209f6ec1a459ae628d8f94e6aedbf3abae (2675B in 571.413697ms, 0.00MiB/s) Step #0 - "fetcher": 2018/07/15 08:26:11 Processing 16 files. Step #0 - "fetcher": 2018/07/15 08:26:11 Fetched gs://staging.PROJECT_ID.appspot.com/ae/6382e88f-f9db-4087-9eca-2a1aee5881d6/manifest.json (3576B in 888.138003ms, 0.00MiB/s) Step #0 - "fetcher": 2018/07/15 08:26:10 Fetching manifest gs://staging.PROJECT_ID.appspot.com/ae/6382e88f-f9db-4087-9eca-2a1aee5881d6/manifest.json. Step #0 - "fetcher": Already have image (with digest): gcr.io/cloud-builders/gcs-fetcher Starting Step #0 - "fetcher" BUILD FETCHSOURCE starting build "88e0cc7f-62b7-496a-aa31-230e793b5ea1" ```
2018/07/15
[ "https://Stackoverflow.com/questions/51346677", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8025518/" ]
Its a weird error, because it just says permission denied in logs. In my case Actual reason was unpaid bills, which keeps **Cloud Build API** enabled just for suspense but actually deployment doesn't work. So do these steps 1. Pay your bills if there is any pending, in short your Payment Method has to be active in `Billings` for the particular project you are getting error 2. After bill is paid, disable the **Cloud Build API** and re-enable it, wait for few seconds/minutes and deploy again.
It shows in the 1st few lines of the log that image couldnt be pulled from registry due to unauthorized user credentials accessing the registry. Did you check the credentials? If you have a token based login, check if the token is not expired.
51,346,677
``` ERROR: build step 1 "gcr.io/gae-runtimes/nodejs8_app_builder:nodejs8_20180618_RC02" failed: exit status 1 ERROR Finished Step #1 - "builder" Step #1 - "builder": Permission denied for "be8392bdf4a2c92301391a124a5b72078453db3c15fcfc71f923e3c63d1bd8ea" from request "/v2/PROJECT_ID/app-engine-build-cache/node-cache/manifests/be8392bdf4a2c92301391a124a5b72078453db3c15fcfc71f923e3c63d1bd8ea". : None Step #1 - "builder": containerregistry.client.v2_2.docker_http_.V2DiagnosticException: response: {'status': '403', 'content-length': '291', 'x-xss-protection': '1; mode=block', 'transfer-encoding': 'chunked', 'server': 'Docker Registry', '-content-encoding': 'gzip', 'docker-distribution-api-version': 'registry/2.0', 'cache-control': 'private', 'date': 'Sun, 15 Jul 2018 08:26:14 GMT', 'x-frame-options': 'SAMEORIGIN', 'content-type': 'application/json'} Step #1 - "builder": File "/ftl-v0.4.0.par/containerregistry/client/v2_2/docker_http_.py", line 364, in Request Step #1 - "builder": File "/ftl-v0.4.0.par/containerregistry/client/v2_2/docker_image_.py", line 250, in _content Step #1 - "builder": File "/ftl-v0.4.0.par/containerregistry/client/v2_2/docker_image_.py", line 293, in manifest Step #1 - "builder": File "/ftl-v0.4.0.par/containerregistry/client/v2_2/docker_image_.py", line 279, in exists Step #1 - "builder": File "/ftl-v0.4.0.par/__main__/ftl/common/cache.py", line 166, in getEntryFromCreds Step #1 - "builder": File "/ftl-v0.4.0.par/__main__/ftl/common/cache.py", line 143, in _getLocalEntry Step #1 - "builder": File "/ftl-v0.4.0.par/__main__/ftl/common/cache.py", line 128, in _getEntry Step #1 - "builder": File "/ftl-v0.4.0.par/__main__/ftl/common/cache.py", line 110, in Get Step #1 - "builder": File "/ftl-v0.4.0.par/__main__/ftl/node/layer_builder.py", line 55, in BuildLayer Step #1 - "builder": File "/ftl-v0.4.0.par/__main__/ftl/node/builder.py", line 38, in Build Step #1 - "builder": File "/ftl-v0.4.0.par/__main__.py", line 52, in main Step #1 - "builder": File "/ftl-v0.4.0.par/__main__.py", line 61, in Step #1 - "builder": exec code in run_globals Step #1 - "builder": File "/usr/lib/python2.7/runpy.py", line 72, in _run_code Step #1 - "builder": "__main__", fname, loader, pkg_name) Step #1 - "builder": File "/usr/lib/python2.7/runpy.py", line 174, in _run_module_as_main Step #1 - "builder": Traceback (most recent call last): Step #1 - "builder": INFO full build took 0 seconds Step #1 - "builder": INFO build process for FTL image took 0 seconds Step #1 - "builder": INFO checking_cached_packages_json_layer took 0 seconds Step #1 - "builder": DEBUG Checking cache for cache_key be8392bdf4a2c92301391a124a5b72078453db3c15fcfc71f923e3c63d1bd8ea Step #1 - "builder": INFO starting: checking_cached_packages_json_layer Step #1 - "builder": INFO starting: build process for FTL image Step #1 - "builder": INFO builder initialization took 0 seconds Step #1 - "builder": INFO Loading Docker credentials for repository 'asia.gcr.io/PROJECT_ID/app-engine/default/20180715t135547:6382e88f-f9db-4087-9eca-2a1aee5881d6' Step #1 - "builder": INFO Loading Docker credentials for repository 'gcr.io/gae-runtimes/nodejs8:nodejs8_20180618_RC02' Step #1 - "builder": INFO starting: builder initialization Step #1 - "builder": INFO starting: full build Step #1 - "builder": INFO FTL arg passed: verbosity NOTSET Step #1 - "builder": INFO FTL arg passed: destination_path /srv Step #1 - "builder": INFO FTL arg passed: entrypoint None Step #1 - "builder": INFO FTL arg passed: directory /workspace Step #1 - "builder": INFO FTL arg passed: output_path None Step #1 - "builder": INFO FTL arg passed: base gcr.io/gae-runtimes/nodejs8:nodejs8_20180618_RC02 Step #1 - "builder": INFO FTL arg passed: upload True Step #1 - "builder": INFO FTL arg passed: cache True Step #1 - "builder": INFO FTL arg passed: global_cache False Step #1 - "builder": INFO FTL arg passed: name asia.gcr.io/PROJECT_ID/app-engine/default/20180715t135547:6382e88f-f9db-4087-9eca-2a1aee5881d6 Step #1 - "builder": INFO FTL arg passed: builder_output_path /builder/outputs Step #1 - "builder": INFO FTL arg passed: tar_base_image_path None Step #1 - "builder": INFO FTL arg passed: cache_repository asia.gcr.io/PROJECT_ID/app-engine-build-cache Step #1 - "builder": INFO FTL arg passed: exposed_ports None Step #1 - "builder": INFO Beginning FTL build for node Step #1 - "builder": INFO FTL version node-v0.4.0 Step #1 - "builder": Status: Downloaded newer image for gcr.io/gae-runtimes/nodejs8_app_builder:nodejs8_20180618_RC02 Step #1 - "builder": Digest: sha256:f937017daa12ccde31d70836e640ef0eaf327436695d05da38e4290c2eb2eb70 Step #1 - "builder": nodejs8_20180618_RC02: Pulling from gae-runtimes/nodejs8_app_builder Step #1 - "builder": Pulling image: gcr.io/gae-runtimes/nodejs8_app_builder:nodejs8_20180618_RC02 Starting Step #1 - "builder" Finished Step #0 - "fetcher" Step #0 - "fetcher": 2018/07/15 08:26:12 ****************************************************** Step #0 - "fetcher": 2018/07/15 08:26:12 Total time: 2.04 s Step #0 - "fetcher": 2018/07/15 08:26:12 Time for manifest: 888.14 ms Step #0 - "fetcher": 2018/07/15 08:26:12 MiB/s throughput: 0.28 MiB/s Step #0 - "fetcher": 2018/07/15 08:26:12 MiB downloaded: 0.33 MiB Step #0 - "fetcher": 2018/07/15 08:26:12 GCS timeouts: 0 Step #0 - "fetcher": 2018/07/15 08:26:12 Total retries: 0 Step #0 - "fetcher": 2018/07/15 08:26:12 Total files: 16 Step #0 - "fetcher": 2018/07/15 08:26:12 Actual workers: 16 Step #0 - "fetcher": 2018/07/15 08:26:12 Requested workers: 200 Step #0 - "fetcher": 2018/07/15 08:26:12 Completed: 2018-07-15T08:26:12Z Step #0 - "fetcher": 2018/07/15 08:26:12 Started: 2018-07-15T08:26:10Z Step #0 - "fetcher": 2018/07/15 08:26:12 Status: SUCCESS Step #0 - "fetcher": 2018/07/15 08:26:12 ****************************************************** Step #0 - "fetcher": 2018/07/15 08:26:12 Fetched gs://staging.PROJECT_ID.appspot.com/5e9210875e15a2eb7d50c666136266837638eb03 (322831B in 1.145458029s, 0.27MiB/s) Step #0 - "fetcher": 2018/07/15 08:26:12 Fetched gs://staging.PROJECT_ID.appspot.com/058b7e502bf6750c6f01453ef947d5dd7e854e07 (1279B in 861.521735ms, 0.00MiB/s) Step #0 - "fetcher": 2018/07/15 08:26:12 Fetched gs://staging.PROJECT_ID.appspot.com/5d87534d139519ba7cec4d48d2c3ba27b99e80b0 (319B in 846.233597ms, 0.00MiB/s) Step #0 - "fetcher": 2018/07/15 08:26:12 Fetched gs://staging.PROJECT_ID.appspot.com/668461d157d199b783be12fd2f2ba9c6d154130c (1271B in 838.8342ms, 0.00MiB/s) Step #0 - "fetcher": 2018/07/15 08:26:11 Fetched gs://staging.PROJECT_ID.appspot.com/8dd0bca621558e6ce972f38d8aa9765e49436172 (327B in 589.603096ms, 0.00MiB/s) Step #0 - "fetcher": 2018/07/15 08:26:11 Fetched gs://staging.PROJECT_ID.appspot.com/c6b4f62664bbe2779fdff10261bc384708e73e7d (36B in 588.36617ms, 0.00MiB/s) Step #0 - "fetcher": 2018/07/15 08:26:11 Fetched gs://staging.PROJECT_ID.appspot.com/c271c61f49150008a5eeae99a9bd09570bd5d549 (2558B in 588.802856ms, 0.00MiB/s) Step #0 - "fetcher": 2018/07/15 08:26:11 Fetched gs://staging.PROJECT_ID.appspot.com/f293a6701e6de41513ba08b50bbbacb58ffbc19a (119B in 586.215815ms, 0.00MiB/s) Step #0 - "fetcher": 2018/07/15 08:26:11 Fetched gs://staging.PROJECT_ID.appspot.com/88ef0fc94347f5e38160bdacef44fedc51b85877 (2305B in 584.714922ms, 0.00MiB/s) Step #0 - "fetcher": 2018/07/15 08:26:11 Fetched gs://staging.PROJECT_ID.appspot.com/73c3a01c14c7b696454020d6dc917ea32a50872c (53B in 584.291891ms, 0.00MiB/s) Step #0 - "fetcher": 2018/07/15 08:26:11 Fetched gs://staging.PROJECT_ID.appspot.com/757cebb200f220928061cdabddd6126d67a46984 (1683B in 583.3675ms, 0.00MiB/s) Step #0 - "fetcher": 2018/07/15 08:26:11 Fetched gs://staging.PROJECT_ID.appspot.com/1bbf5d56ff53e82b6444cab2a87d43b14d23a8b3 (217B in 584.334096ms, 0.00MiB/s) Step #0 - "fetcher": 2018/07/15 08:26:11 Fetched gs://staging.PROJECT_ID.appspot.com/42a994f47562d763d59a4b64822554d24f0ffce7 (28B in 577.748008ms, 0.00MiB/s) Step #0 - "fetcher": 2018/07/15 08:26:11 Fetched gs://staging.PROJECT_ID.appspot.com/f9185bdfc5b57bef24b52a9bbeb09cdf981f279f (2495B in 579.458821ms, 0.00MiB/s) Step #0 - "fetcher": 2018/07/15 08:26:11 Fetched gs://staging.PROJECT_ID.appspot.com/0c676a042d5ad4e493046f23965ed648293225be (3162B in 577.802151ms, 0.01MiB/s) Step #0 - "fetcher": 2018/07/15 08:26:11 Fetched gs://staging.PROJECT_ID.appspot.com/5bf6fe209f6ec1a459ae628d8f94e6aedbf3abae (2675B in 571.413697ms, 0.00MiB/s) Step #0 - "fetcher": 2018/07/15 08:26:11 Processing 16 files. Step #0 - "fetcher": 2018/07/15 08:26:11 Fetched gs://staging.PROJECT_ID.appspot.com/ae/6382e88f-f9db-4087-9eca-2a1aee5881d6/manifest.json (3576B in 888.138003ms, 0.00MiB/s) Step #0 - "fetcher": 2018/07/15 08:26:10 Fetching manifest gs://staging.PROJECT_ID.appspot.com/ae/6382e88f-f9db-4087-9eca-2a1aee5881d6/manifest.json. Step #0 - "fetcher": Already have image (with digest): gcr.io/cloud-builders/gcs-fetcher Starting Step #0 - "fetcher" BUILD FETCHSOURCE starting build "88e0cc7f-62b7-496a-aa31-230e793b5ea1" ```
2018/07/15
[ "https://Stackoverflow.com/questions/51346677", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8025518/" ]
> > ### Troubleshooting > > > If you find 403 (access denied) errors in your build logs, try the following steps: > > > Disable the Cloud Build API and re-enable it. Doing so should give your service account access to your project again. > > > Fixed an issue for me.
Its a weird error, because it just says permission denied in logs. In my case Actual reason was unpaid bills, which keeps **Cloud Build API** enabled just for suspense but actually deployment doesn't work. So do these steps 1. Pay your bills if there is any pending, in short your Payment Method has to be active in `Billings` for the particular project you are getting error 2. After bill is paid, disable the **Cloud Build API** and re-enable it, wait for few seconds/minutes and deploy again.
45,417,077
I've got a module called `core`, which contains a number of python files. If I do: ``` from core.curve import Curve ``` Does `__init__.py` get called? Can I move import statements that apply to all core files into `__init__.py` to save repeating myself? What **should** go into `__init__.py`?
2017/07/31
[ "https://Stackoverflow.com/questions/45417077", "https://Stackoverflow.com", "https://Stackoverflow.com/users/222151/" ]
> > Is \_\_init\_\_.py run everytime I import anything from that module? > > > According to [docs](https://docs.python.org/2/tutorial/modules.html#importing-from-a-package) in most cases **yes**, it is.
You can add all your functions that you want to use in your directory ``` - core - __init__.py ``` in this `__init__.py` add your class and function references like ``` from .curve import Curve from .some import SomethingElse ``` and where you want to User your class just refer it like ``` from core import Curve ```
45,417,077
I've got a module called `core`, which contains a number of python files. If I do: ``` from core.curve import Curve ``` Does `__init__.py` get called? Can I move import statements that apply to all core files into `__init__.py` to save repeating myself? What **should** go into `__init__.py`?
2017/07/31
[ "https://Stackoverflow.com/questions/45417077", "https://Stackoverflow.com", "https://Stackoverflow.com/users/222151/" ]
> > I've got a module called core, which contains a number of python files. > > > if it contains python files, it's not a module, it's a directory containing python files - and eventually a package if it contains an `__init__.py` file. > > If I do: `from core.curve import Curve` does `__init__.py` get called? > > > It's never "called" - it's not a function - but it gets loaded the first time the package or one of it's submodules gets imported in a process. It's then stored in `sys.modules` and subsequent imports will find it there. > > Can I move import statements that apply to all core files into **init**.py to save repeating myself? > > > Nope. namespaces are per-module, not per-package. And it would be a very bad idea anyway, what you name "repeating yourself" is, in this case, a real helper when it comes to maintaining your code (explicit imports means you know without ambiguity which symbol comes from which module). > > What should go into **init**.py? > > > Technically you can actually put whatever you want in your `__init__.py` files, but most often than not they are just empty. A couple known uses case are [using it as a facade](https://en.wikipedia.org/wiki/Facade_pattern) for the package's submodules, selecting a concrete implementation for a common API based on thye current platform or some environment variable etc... Oh and yes: it's also a good place to add some meta informations about your package (version, author etc).
> > Is \_\_init\_\_.py run everytime I import anything from that module? > > > According to [docs](https://docs.python.org/2/tutorial/modules.html#importing-from-a-package) in most cases **yes**, it is.
45,417,077
I've got a module called `core`, which contains a number of python files. If I do: ``` from core.curve import Curve ``` Does `__init__.py` get called? Can I move import statements that apply to all core files into `__init__.py` to save repeating myself? What **should** go into `__init__.py`?
2017/07/31
[ "https://Stackoverflow.com/questions/45417077", "https://Stackoverflow.com", "https://Stackoverflow.com/users/222151/" ]
> > I've got a module called core, which contains a number of python files. > > > if it contains python files, it's not a module, it's a directory containing python files - and eventually a package if it contains an `__init__.py` file. > > If I do: `from core.curve import Curve` does `__init__.py` get called? > > > It's never "called" - it's not a function - but it gets loaded the first time the package or one of it's submodules gets imported in a process. It's then stored in `sys.modules` and subsequent imports will find it there. > > Can I move import statements that apply to all core files into **init**.py to save repeating myself? > > > Nope. namespaces are per-module, not per-package. And it would be a very bad idea anyway, what you name "repeating yourself" is, in this case, a real helper when it comes to maintaining your code (explicit imports means you know without ambiguity which symbol comes from which module). > > What should go into **init**.py? > > > Technically you can actually put whatever you want in your `__init__.py` files, but most often than not they are just empty. A couple known uses case are [using it as a facade](https://en.wikipedia.org/wiki/Facade_pattern) for the package's submodules, selecting a concrete implementation for a common API based on thye current platform or some environment variable etc... Oh and yes: it's also a good place to add some meta informations about your package (version, author etc).
You can add all your functions that you want to use in your directory ``` - core - __init__.py ``` in this `__init__.py` add your class and function references like ``` from .curve import Curve from .some import SomethingElse ``` and where you want to User your class just refer it like ``` from core import Curve ```