repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
sequence
docstring
stringlengths
3
17.3k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
ratt-ru/PyMORESANE
pymoresane/iuwt.py
gpu_iuwt_recomposition
def gpu_iuwt_recomposition(in1, scale_adjust, store_on_gpu, smoothed_array): """ This function calls the a trous algorithm code to recompose the input into a single array. This is the implementation of the isotropic undecimated wavelet transform recomposition for a GPU. INPUTS: in1 (no default): Array containing wavelet coefficients. scale_adjust (no default): Indicates the number of omitted array pages. store_on_gpu (no default): Boolean specifier for whether the decomposition is stored on the gpu or not. OUTPUTS: recomposiiton Array containing the reconstructed array. """ wavelet_filter = (1./16)*np.array([1,4,6,4,1], dtype=np.float32) # Filter-bank for use in the a trous algorithm. wavelet_filter = gpuarray.to_gpu_async(wavelet_filter) # Determines scale with adjustment and creates a zero array on the GPU to store the output,unless smoothed_array # is given. max_scale = in1.shape[0] + scale_adjust if smoothed_array is None: recomposition = gpuarray.zeros([in1.shape[1], in1.shape[2]], np.float32) else: recomposition = gpuarray.to_gpu(smoothed_array.astype(np.float32)) # Determines whether the array is already on the GPU or not. If not, moves it to the GPU. try: gpu_in1 = gpuarray.to_gpu_async(in1.astype(np.float32)) except: gpu_in1 = in1 # Creates a working array on the GPU. gpu_tmp = gpuarray.empty_like(recomposition) # Creates and fills an array with the appropriate scale value. gpu_scale = gpuarray.zeros([1], np.int32) gpu_scale += max_scale-1 # Fetches the a trous kernels. gpu_a_trous_row_kernel, gpu_a_trous_col_kernel = gpu_a_trous() grid_rows = int(in1.shape[1]//32) grid_cols = int(in1.shape[2]//32) # The following loops call the a trous algorithm code to recompose the input. The first loop assumes that there are # non-zero wavelet coefficients at scales above scale_adjust, while the second loop completes the recomposition # on the scales less than scale_adjust. for i in range(max_scale-1, scale_adjust-1, -1): gpu_a_trous_row_kernel(recomposition, gpu_tmp, wavelet_filter, gpu_scale, block=(32,32,1), grid=(grid_cols, grid_rows)) gpu_a_trous_col_kernel(gpu_tmp, recomposition, wavelet_filter, gpu_scale, block=(32,32,1), grid=(grid_cols, grid_rows)) recomposition = recomposition[:,:] + gpu_in1[i-scale_adjust,:,:] gpu_scale -= 1 if scale_adjust>0: for i in range(scale_adjust-1, -1, -1): gpu_a_trous_row_kernel(recomposition, gpu_tmp, wavelet_filter, gpu_scale, block=(32,32,1), grid=(grid_cols, grid_rows)) gpu_a_trous_col_kernel(gpu_tmp, recomposition, wavelet_filter, gpu_scale, block=(32,32,1), grid=(grid_cols, grid_rows)) gpu_scale -= 1 # Return values depend on mode. if store_on_gpu: return recomposition else: return recomposition.get()
python
def gpu_iuwt_recomposition(in1, scale_adjust, store_on_gpu, smoothed_array): """ This function calls the a trous algorithm code to recompose the input into a single array. This is the implementation of the isotropic undecimated wavelet transform recomposition for a GPU. INPUTS: in1 (no default): Array containing wavelet coefficients. scale_adjust (no default): Indicates the number of omitted array pages. store_on_gpu (no default): Boolean specifier for whether the decomposition is stored on the gpu or not. OUTPUTS: recomposiiton Array containing the reconstructed array. """ wavelet_filter = (1./16)*np.array([1,4,6,4,1], dtype=np.float32) # Filter-bank for use in the a trous algorithm. wavelet_filter = gpuarray.to_gpu_async(wavelet_filter) # Determines scale with adjustment and creates a zero array on the GPU to store the output,unless smoothed_array # is given. max_scale = in1.shape[0] + scale_adjust if smoothed_array is None: recomposition = gpuarray.zeros([in1.shape[1], in1.shape[2]], np.float32) else: recomposition = gpuarray.to_gpu(smoothed_array.astype(np.float32)) # Determines whether the array is already on the GPU or not. If not, moves it to the GPU. try: gpu_in1 = gpuarray.to_gpu_async(in1.astype(np.float32)) except: gpu_in1 = in1 # Creates a working array on the GPU. gpu_tmp = gpuarray.empty_like(recomposition) # Creates and fills an array with the appropriate scale value. gpu_scale = gpuarray.zeros([1], np.int32) gpu_scale += max_scale-1 # Fetches the a trous kernels. gpu_a_trous_row_kernel, gpu_a_trous_col_kernel = gpu_a_trous() grid_rows = int(in1.shape[1]//32) grid_cols = int(in1.shape[2]//32) # The following loops call the a trous algorithm code to recompose the input. The first loop assumes that there are # non-zero wavelet coefficients at scales above scale_adjust, while the second loop completes the recomposition # on the scales less than scale_adjust. for i in range(max_scale-1, scale_adjust-1, -1): gpu_a_trous_row_kernel(recomposition, gpu_tmp, wavelet_filter, gpu_scale, block=(32,32,1), grid=(grid_cols, grid_rows)) gpu_a_trous_col_kernel(gpu_tmp, recomposition, wavelet_filter, gpu_scale, block=(32,32,1), grid=(grid_cols, grid_rows)) recomposition = recomposition[:,:] + gpu_in1[i-scale_adjust,:,:] gpu_scale -= 1 if scale_adjust>0: for i in range(scale_adjust-1, -1, -1): gpu_a_trous_row_kernel(recomposition, gpu_tmp, wavelet_filter, gpu_scale, block=(32,32,1), grid=(grid_cols, grid_rows)) gpu_a_trous_col_kernel(gpu_tmp, recomposition, wavelet_filter, gpu_scale, block=(32,32,1), grid=(grid_cols, grid_rows)) gpu_scale -= 1 # Return values depend on mode. if store_on_gpu: return recomposition else: return recomposition.get()
[ "def", "gpu_iuwt_recomposition", "(", "in1", ",", "scale_adjust", ",", "store_on_gpu", ",", "smoothed_array", ")", ":", "wavelet_filter", "=", "(", "1.", "/", "16", ")", "*", "np", ".", "array", "(", "[", "1", ",", "4", ",", "6", ",", "4", ",", "1", "]", ",", "dtype", "=", "np", ".", "float32", ")", "# Filter-bank for use in the a trous algorithm.", "wavelet_filter", "=", "gpuarray", ".", "to_gpu_async", "(", "wavelet_filter", ")", "# Determines scale with adjustment and creates a zero array on the GPU to store the output,unless smoothed_array", "# is given.", "max_scale", "=", "in1", ".", "shape", "[", "0", "]", "+", "scale_adjust", "if", "smoothed_array", "is", "None", ":", "recomposition", "=", "gpuarray", ".", "zeros", "(", "[", "in1", ".", "shape", "[", "1", "]", ",", "in1", ".", "shape", "[", "2", "]", "]", ",", "np", ".", "float32", ")", "else", ":", "recomposition", "=", "gpuarray", ".", "to_gpu", "(", "smoothed_array", ".", "astype", "(", "np", ".", "float32", ")", ")", "# Determines whether the array is already on the GPU or not. If not, moves it to the GPU.", "try", ":", "gpu_in1", "=", "gpuarray", ".", "to_gpu_async", "(", "in1", ".", "astype", "(", "np", ".", "float32", ")", ")", "except", ":", "gpu_in1", "=", "in1", "# Creates a working array on the GPU.", "gpu_tmp", "=", "gpuarray", ".", "empty_like", "(", "recomposition", ")", "# Creates and fills an array with the appropriate scale value.", "gpu_scale", "=", "gpuarray", ".", "zeros", "(", "[", "1", "]", ",", "np", ".", "int32", ")", "gpu_scale", "+=", "max_scale", "-", "1", "# Fetches the a trous kernels.", "gpu_a_trous_row_kernel", ",", "gpu_a_trous_col_kernel", "=", "gpu_a_trous", "(", ")", "grid_rows", "=", "int", "(", "in1", ".", "shape", "[", "1", "]", "//", "32", ")", "grid_cols", "=", "int", "(", "in1", ".", "shape", "[", "2", "]", "//", "32", ")", "# The following loops call the a trous algorithm code to recompose the input. The first loop assumes that there are", "# non-zero wavelet coefficients at scales above scale_adjust, while the second loop completes the recomposition", "# on the scales less than scale_adjust.", "for", "i", "in", "range", "(", "max_scale", "-", "1", ",", "scale_adjust", "-", "1", ",", "-", "1", ")", ":", "gpu_a_trous_row_kernel", "(", "recomposition", ",", "gpu_tmp", ",", "wavelet_filter", ",", "gpu_scale", ",", "block", "=", "(", "32", ",", "32", ",", "1", ")", ",", "grid", "=", "(", "grid_cols", ",", "grid_rows", ")", ")", "gpu_a_trous_col_kernel", "(", "gpu_tmp", ",", "recomposition", ",", "wavelet_filter", ",", "gpu_scale", ",", "block", "=", "(", "32", ",", "32", ",", "1", ")", ",", "grid", "=", "(", "grid_cols", ",", "grid_rows", ")", ")", "recomposition", "=", "recomposition", "[", ":", ",", ":", "]", "+", "gpu_in1", "[", "i", "-", "scale_adjust", ",", ":", ",", ":", "]", "gpu_scale", "-=", "1", "if", "scale_adjust", ">", "0", ":", "for", "i", "in", "range", "(", "scale_adjust", "-", "1", ",", "-", "1", ",", "-", "1", ")", ":", "gpu_a_trous_row_kernel", "(", "recomposition", ",", "gpu_tmp", ",", "wavelet_filter", ",", "gpu_scale", ",", "block", "=", "(", "32", ",", "32", ",", "1", ")", ",", "grid", "=", "(", "grid_cols", ",", "grid_rows", ")", ")", "gpu_a_trous_col_kernel", "(", "gpu_tmp", ",", "recomposition", ",", "wavelet_filter", ",", "gpu_scale", ",", "block", "=", "(", "32", ",", "32", ",", "1", ")", ",", "grid", "=", "(", "grid_cols", ",", "grid_rows", ")", ")", "gpu_scale", "-=", "1", "# Return values depend on mode.", "if", "store_on_gpu", ":", "return", "recomposition", "else", ":", "return", "recomposition", ".", "get", "(", ")" ]
This function calls the a trous algorithm code to recompose the input into a single array. This is the implementation of the isotropic undecimated wavelet transform recomposition for a GPU. INPUTS: in1 (no default): Array containing wavelet coefficients. scale_adjust (no default): Indicates the number of omitted array pages. store_on_gpu (no default): Boolean specifier for whether the decomposition is stored on the gpu or not. OUTPUTS: recomposiiton Array containing the reconstructed array.
[ "This", "function", "calls", "the", "a", "trous", "algorithm", "code", "to", "recompose", "the", "input", "into", "a", "single", "array", ".", "This", "is", "the", "implementation", "of", "the", "isotropic", "undecimated", "wavelet", "transform", "recomposition", "for", "a", "GPU", "." ]
b024591ad0bbb69320d08841f28a2c27f62ae1af
https://github.com/ratt-ru/PyMORESANE/blob/b024591ad0bbb69320d08841f28a2c27f62ae1af/pymoresane/iuwt.py#L501-L581
train
marcelcaraciolo/foursquare
examples/django/example/djfoursquare/views.py
unauth
def unauth(request): """ logout and remove all session data """ if check_key(request): api = get_api(request) request.session.clear() logout(request) return HttpResponseRedirect(reverse('main'))
python
def unauth(request): """ logout and remove all session data """ if check_key(request): api = get_api(request) request.session.clear() logout(request) return HttpResponseRedirect(reverse('main'))
[ "def", "unauth", "(", "request", ")", ":", "if", "check_key", "(", "request", ")", ":", "api", "=", "get_api", "(", "request", ")", "request", ".", "session", ".", "clear", "(", ")", "logout", "(", "request", ")", "return", "HttpResponseRedirect", "(", "reverse", "(", "'main'", ")", ")" ]
logout and remove all session data
[ "logout", "and", "remove", "all", "session", "data" ]
a8bda33cc2d61e25aa8df72011246269fd98aa13
https://github.com/marcelcaraciolo/foursquare/blob/a8bda33cc2d61e25aa8df72011246269fd98aa13/examples/django/example/djfoursquare/views.py#L22-L30
train
marcelcaraciolo/foursquare
examples/django/example/djfoursquare/views.py
info
def info(request): """ display some user info to show we have authenticated successfully """ if check_key(request): api = get_api(request) user = api.users(id='self') print dir(user) return render_to_response('djfoursquare/info.html', {'user': user}) else: return HttpResponseRedirect(reverse('main'))
python
def info(request): """ display some user info to show we have authenticated successfully """ if check_key(request): api = get_api(request) user = api.users(id='self') print dir(user) return render_to_response('djfoursquare/info.html', {'user': user}) else: return HttpResponseRedirect(reverse('main'))
[ "def", "info", "(", "request", ")", ":", "if", "check_key", "(", "request", ")", ":", "api", "=", "get_api", "(", "request", ")", "user", "=", "api", ".", "users", "(", "id", "=", "'self'", ")", "print", "dir", "(", "user", ")", "return", "render_to_response", "(", "'djfoursquare/info.html'", ",", "{", "'user'", ":", "user", "}", ")", "else", ":", "return", "HttpResponseRedirect", "(", "reverse", "(", "'main'", ")", ")" ]
display some user info to show we have authenticated successfully
[ "display", "some", "user", "info", "to", "show", "we", "have", "authenticated", "successfully" ]
a8bda33cc2d61e25aa8df72011246269fd98aa13
https://github.com/marcelcaraciolo/foursquare/blob/a8bda33cc2d61e25aa8df72011246269fd98aa13/examples/django/example/djfoursquare/views.py#L33-L43
train
marcelcaraciolo/foursquare
examples/django/example/djfoursquare/views.py
check_key
def check_key(request): """ Check to see if we already have an access_key stored, if we do then we have already gone through OAuth. If not then we haven't and we probably need to. """ try: access_key = request.session.get('oauth_token', None) if not access_key: return False except KeyError: return False return True
python
def check_key(request): """ Check to see if we already have an access_key stored, if we do then we have already gone through OAuth. If not then we haven't and we probably need to. """ try: access_key = request.session.get('oauth_token', None) if not access_key: return False except KeyError: return False return True
[ "def", "check_key", "(", "request", ")", ":", "try", ":", "access_key", "=", "request", ".", "session", ".", "get", "(", "'oauth_token'", ",", "None", ")", "if", "not", "access_key", ":", "return", "False", "except", "KeyError", ":", "return", "False", "return", "True" ]
Check to see if we already have an access_key stored, if we do then we have already gone through OAuth. If not then we haven't and we probably need to.
[ "Check", "to", "see", "if", "we", "already", "have", "an", "access_key", "stored", "if", "we", "do", "then", "we", "have", "already", "gone", "through", "OAuth", ".", "If", "not", "then", "we", "haven", "t", "and", "we", "probably", "need", "to", "." ]
a8bda33cc2d61e25aa8df72011246269fd98aa13
https://github.com/marcelcaraciolo/foursquare/blob/a8bda33cc2d61e25aa8df72011246269fd98aa13/examples/django/example/djfoursquare/views.py#L73-L85
train
praekeltfoundation/seaworthy
seaworthy/stream/_timeout.py
stream_timeout
def stream_timeout(stream, timeout, timeout_msg=None): """ Iterate over items in a streaming response from the Docker client within a timeout. :param ~docker.types.daemon.CancellableStream stream: Stream from the Docker client to consume items from. :param timeout: Timeout value in seconds. :param timeout_msg: Message to raise in the exception when a timeout occurs. """ timed_out = threading.Event() def timeout_func(): timed_out.set() stream.close() timer = threading.Timer(timeout, timeout_func) try: timer.start() for item in stream: yield item # A timeout looks the same as the loop ending. So we need to check a # flag to determine whether a timeout occurred or not. if timed_out.is_set(): raise TimeoutError(timeout_msg) finally: timer.cancel() # Close the stream's underlying response object (if it has one) to # avoid potential socket leaks. # This method seems to have more success at preventing ResourceWarnings # than just stream.close() (should this be improved upstream?) # FIXME: Potential race condition if Timer thread closes the stream at # the same time we do here, but hopefully not with serious side effects if hasattr(stream, '_response'): stream._response.close()
python
def stream_timeout(stream, timeout, timeout_msg=None): """ Iterate over items in a streaming response from the Docker client within a timeout. :param ~docker.types.daemon.CancellableStream stream: Stream from the Docker client to consume items from. :param timeout: Timeout value in seconds. :param timeout_msg: Message to raise in the exception when a timeout occurs. """ timed_out = threading.Event() def timeout_func(): timed_out.set() stream.close() timer = threading.Timer(timeout, timeout_func) try: timer.start() for item in stream: yield item # A timeout looks the same as the loop ending. So we need to check a # flag to determine whether a timeout occurred or not. if timed_out.is_set(): raise TimeoutError(timeout_msg) finally: timer.cancel() # Close the stream's underlying response object (if it has one) to # avoid potential socket leaks. # This method seems to have more success at preventing ResourceWarnings # than just stream.close() (should this be improved upstream?) # FIXME: Potential race condition if Timer thread closes the stream at # the same time we do here, but hopefully not with serious side effects if hasattr(stream, '_response'): stream._response.close()
[ "def", "stream_timeout", "(", "stream", ",", "timeout", ",", "timeout_msg", "=", "None", ")", ":", "timed_out", "=", "threading", ".", "Event", "(", ")", "def", "timeout_func", "(", ")", ":", "timed_out", ".", "set", "(", ")", "stream", ".", "close", "(", ")", "timer", "=", "threading", ".", "Timer", "(", "timeout", ",", "timeout_func", ")", "try", ":", "timer", ".", "start", "(", ")", "for", "item", "in", "stream", ":", "yield", "item", "# A timeout looks the same as the loop ending. So we need to check a", "# flag to determine whether a timeout occurred or not.", "if", "timed_out", ".", "is_set", "(", ")", ":", "raise", "TimeoutError", "(", "timeout_msg", ")", "finally", ":", "timer", ".", "cancel", "(", ")", "# Close the stream's underlying response object (if it has one) to", "# avoid potential socket leaks.", "# This method seems to have more success at preventing ResourceWarnings", "# than just stream.close() (should this be improved upstream?)", "# FIXME: Potential race condition if Timer thread closes the stream at", "# the same time we do here, but hopefully not with serious side effects", "if", "hasattr", "(", "stream", ",", "'_response'", ")", ":", "stream", ".", "_response", ".", "close", "(", ")" ]
Iterate over items in a streaming response from the Docker client within a timeout. :param ~docker.types.daemon.CancellableStream stream: Stream from the Docker client to consume items from. :param timeout: Timeout value in seconds. :param timeout_msg: Message to raise in the exception when a timeout occurs.
[ "Iterate", "over", "items", "in", "a", "streaming", "response", "from", "the", "Docker", "client", "within", "a", "timeout", "." ]
6f10a19b45d4ea1dc3bd0553cc4d0438696c079c
https://github.com/praekeltfoundation/seaworthy/blob/6f10a19b45d4ea1dc3bd0553cc4d0438696c079c/seaworthy/stream/_timeout.py#L4-L41
train
tuomas2/automate
src/automate/callable.py
AbstractCallable.get_state
def get_state(self, caller): """ Get per-program state. """ if caller in self.state: return self.state[caller] else: rv = self.state[caller] = DictObject() return rv
python
def get_state(self, caller): """ Get per-program state. """ if caller in self.state: return self.state[caller] else: rv = self.state[caller] = DictObject() return rv
[ "def", "get_state", "(", "self", ",", "caller", ")", ":", "if", "caller", "in", "self", ".", "state", ":", "return", "self", ".", "state", "[", "caller", "]", "else", ":", "rv", "=", "self", ".", "state", "[", "caller", "]", "=", "DictObject", "(", ")", "return", "rv" ]
Get per-program state.
[ "Get", "per", "-", "program", "state", "." ]
d8a8cd03cd0da047e033a2d305f3f260f8c4e017
https://github.com/tuomas2/automate/blob/d8a8cd03cd0da047e033a2d305f3f260f8c4e017/src/automate/callable.py#L74-L83
train
tuomas2/automate
src/automate/callable.py
AbstractCallable.name_to_system_object
def name_to_system_object(self, value): """ Return object for given name registered in System namespace. """ if not self.system: raise SystemNotReady if isinstance(value, (str, Object)): rv = self.system.name_to_system_object(value) return rv if rv else value else: return value
python
def name_to_system_object(self, value): """ Return object for given name registered in System namespace. """ if not self.system: raise SystemNotReady if isinstance(value, (str, Object)): rv = self.system.name_to_system_object(value) return rv if rv else value else: return value
[ "def", "name_to_system_object", "(", "self", ",", "value", ")", ":", "if", "not", "self", ".", "system", ":", "raise", "SystemNotReady", "if", "isinstance", "(", "value", ",", "(", "str", ",", "Object", ")", ")", ":", "rv", "=", "self", ".", "system", ".", "name_to_system_object", "(", "value", ")", "return", "rv", "if", "rv", "else", "value", "else", ":", "return", "value" ]
Return object for given name registered in System namespace.
[ "Return", "object", "for", "given", "name", "registered", "in", "System", "namespace", "." ]
d8a8cd03cd0da047e033a2d305f3f260f8c4e017
https://github.com/tuomas2/automate/blob/d8a8cd03cd0da047e033a2d305f3f260f8c4e017/src/automate/callable.py#L250-L261
train
tuomas2/automate
src/automate/callable.py
AbstractCallable.cancel
def cancel(self, caller): """ Recursively cancel all threaded background processes of this Callable. This is called automatically for actions if program deactivates. """ for o in {i for i in self.children if isinstance(i, AbstractCallable)}: o.cancel(caller)
python
def cancel(self, caller): """ Recursively cancel all threaded background processes of this Callable. This is called automatically for actions if program deactivates. """ for o in {i for i in self.children if isinstance(i, AbstractCallable)}: o.cancel(caller)
[ "def", "cancel", "(", "self", ",", "caller", ")", ":", "for", "o", "in", "{", "i", "for", "i", "in", "self", ".", "children", "if", "isinstance", "(", "i", ",", "AbstractCallable", ")", "}", ":", "o", ".", "cancel", "(", "caller", ")" ]
Recursively cancel all threaded background processes of this Callable. This is called automatically for actions if program deactivates.
[ "Recursively", "cancel", "all", "threaded", "background", "processes", "of", "this", "Callable", ".", "This", "is", "called", "automatically", "for", "actions", "if", "program", "deactivates", "." ]
d8a8cd03cd0da047e033a2d305f3f260f8c4e017
https://github.com/tuomas2/automate/blob/d8a8cd03cd0da047e033a2d305f3f260f8c4e017/src/automate/callable.py#L311-L317
train
tuomas2/automate
src/automate/callable.py
AbstractCallable.give_str
def give_str(self): """ Give string representation of the callable. """ args = self._args[:] kwargs = self._kwargs return self._give_str(args, kwargs)
python
def give_str(self): """ Give string representation of the callable. """ args = self._args[:] kwargs = self._kwargs return self._give_str(args, kwargs)
[ "def", "give_str", "(", "self", ")", ":", "args", "=", "self", ".", "_args", "[", ":", "]", "kwargs", "=", "self", ".", "_kwargs", "return", "self", ".", "_give_str", "(", "args", ",", "kwargs", ")" ]
Give string representation of the callable.
[ "Give", "string", "representation", "of", "the", "callable", "." ]
d8a8cd03cd0da047e033a2d305f3f260f8c4e017
https://github.com/tuomas2/automate/blob/d8a8cd03cd0da047e033a2d305f3f260f8c4e017/src/automate/callable.py#L333-L339
train
fauskanger/mypolr
mypolr/polr_api.py
PolrApi._make_request
def _make_request(self, endpoint, params): """ Prepares the request and catches common errors and returns tuple of data and the request response. Read more about error codes: https://docs.polrproject.org/en/latest/developer-guide/api/#http-error-codes :param endpoint: full endpoint url :type endpoint: str :param params: parameters for the given endpoint :type params: dict :return: Tuple of response data, and the response instance :rtype: dict, requests.Response """ # params = { # **self._base_params, # Mind order to allow params to overwrite base params # **params # } full_params = self._base_params.copy() full_params.update(params) try: r = requests.get(endpoint, full_params) data = r.json() if r.status_code == 401 and not endpoint.endswith('lookup'): raise exceptions.UnauthorizedKeyError elif r.status_code == 400 and not endpoint.endswith('shorten'): raise exceptions.BadApiRequest elif r.status_code == 500: raise exceptions.ServerOrConnectionError return data, r except ValueError as e: raise exceptions.BadApiResponse(e) except requests.RequestException: raise exceptions.ServerOrConnectionError
python
def _make_request(self, endpoint, params): """ Prepares the request and catches common errors and returns tuple of data and the request response. Read more about error codes: https://docs.polrproject.org/en/latest/developer-guide/api/#http-error-codes :param endpoint: full endpoint url :type endpoint: str :param params: parameters for the given endpoint :type params: dict :return: Tuple of response data, and the response instance :rtype: dict, requests.Response """ # params = { # **self._base_params, # Mind order to allow params to overwrite base params # **params # } full_params = self._base_params.copy() full_params.update(params) try: r = requests.get(endpoint, full_params) data = r.json() if r.status_code == 401 and not endpoint.endswith('lookup'): raise exceptions.UnauthorizedKeyError elif r.status_code == 400 and not endpoint.endswith('shorten'): raise exceptions.BadApiRequest elif r.status_code == 500: raise exceptions.ServerOrConnectionError return data, r except ValueError as e: raise exceptions.BadApiResponse(e) except requests.RequestException: raise exceptions.ServerOrConnectionError
[ "def", "_make_request", "(", "self", ",", "endpoint", ",", "params", ")", ":", "# params = {", "# **self._base_params, # Mind order to allow params to overwrite base params", "# **params", "# }", "full_params", "=", "self", ".", "_base_params", ".", "copy", "(", ")", "full_params", ".", "update", "(", "params", ")", "try", ":", "r", "=", "requests", ".", "get", "(", "endpoint", ",", "full_params", ")", "data", "=", "r", ".", "json", "(", ")", "if", "r", ".", "status_code", "==", "401", "and", "not", "endpoint", ".", "endswith", "(", "'lookup'", ")", ":", "raise", "exceptions", ".", "UnauthorizedKeyError", "elif", "r", ".", "status_code", "==", "400", "and", "not", "endpoint", ".", "endswith", "(", "'shorten'", ")", ":", "raise", "exceptions", ".", "BadApiRequest", "elif", "r", ".", "status_code", "==", "500", ":", "raise", "exceptions", ".", "ServerOrConnectionError", "return", "data", ",", "r", "except", "ValueError", "as", "e", ":", "raise", "exceptions", ".", "BadApiResponse", "(", "e", ")", "except", "requests", ".", "RequestException", ":", "raise", "exceptions", ".", "ServerOrConnectionError" ]
Prepares the request and catches common errors and returns tuple of data and the request response. Read more about error codes: https://docs.polrproject.org/en/latest/developer-guide/api/#http-error-codes :param endpoint: full endpoint url :type endpoint: str :param params: parameters for the given endpoint :type params: dict :return: Tuple of response data, and the response instance :rtype: dict, requests.Response
[ "Prepares", "the", "request", "and", "catches", "common", "errors", "and", "returns", "tuple", "of", "data", "and", "the", "request", "response", "." ]
46eb4fc5ba0f65412634a37e30e05de79fc9db4c
https://github.com/fauskanger/mypolr/blob/46eb4fc5ba0f65412634a37e30e05de79fc9db4c/mypolr/polr_api.py#L42-L74
train
fauskanger/mypolr
mypolr/polr_api.py
PolrApi.shorten
def shorten(self, long_url, custom_ending=None, is_secret=False): """ Creates a short url if valid :param str long_url: The url to shorten. :param custom_ending: The custom url to create if available. :type custom_ending: str or None :param bool is_secret: if not public, it's secret :return: a short link :rtype: str """ params = { 'url': long_url, 'is_secret': 'true' if is_secret else 'false', 'custom_ending': custom_ending } data, r = self._make_request(self.api_shorten_endpoint, params) if r.status_code == 400: if custom_ending is not None: raise exceptions.CustomEndingUnavailable(custom_ending) raise exceptions.BadApiRequest elif r.status_code == 403: raise exceptions.QuotaExceededError action = data.get('action') short_url = data.get('result') if action == 'shorten' and short_url is not None: return short_url raise exceptions.DebugTempWarning
python
def shorten(self, long_url, custom_ending=None, is_secret=False): """ Creates a short url if valid :param str long_url: The url to shorten. :param custom_ending: The custom url to create if available. :type custom_ending: str or None :param bool is_secret: if not public, it's secret :return: a short link :rtype: str """ params = { 'url': long_url, 'is_secret': 'true' if is_secret else 'false', 'custom_ending': custom_ending } data, r = self._make_request(self.api_shorten_endpoint, params) if r.status_code == 400: if custom_ending is not None: raise exceptions.CustomEndingUnavailable(custom_ending) raise exceptions.BadApiRequest elif r.status_code == 403: raise exceptions.QuotaExceededError action = data.get('action') short_url = data.get('result') if action == 'shorten' and short_url is not None: return short_url raise exceptions.DebugTempWarning
[ "def", "shorten", "(", "self", ",", "long_url", ",", "custom_ending", "=", "None", ",", "is_secret", "=", "False", ")", ":", "params", "=", "{", "'url'", ":", "long_url", ",", "'is_secret'", ":", "'true'", "if", "is_secret", "else", "'false'", ",", "'custom_ending'", ":", "custom_ending", "}", "data", ",", "r", "=", "self", ".", "_make_request", "(", "self", ".", "api_shorten_endpoint", ",", "params", ")", "if", "r", ".", "status_code", "==", "400", ":", "if", "custom_ending", "is", "not", "None", ":", "raise", "exceptions", ".", "CustomEndingUnavailable", "(", "custom_ending", ")", "raise", "exceptions", ".", "BadApiRequest", "elif", "r", ".", "status_code", "==", "403", ":", "raise", "exceptions", ".", "QuotaExceededError", "action", "=", "data", ".", "get", "(", "'action'", ")", "short_url", "=", "data", ".", "get", "(", "'result'", ")", "if", "action", "==", "'shorten'", "and", "short_url", "is", "not", "None", ":", "return", "short_url", "raise", "exceptions", ".", "DebugTempWarning" ]
Creates a short url if valid :param str long_url: The url to shorten. :param custom_ending: The custom url to create if available. :type custom_ending: str or None :param bool is_secret: if not public, it's secret :return: a short link :rtype: str
[ "Creates", "a", "short", "url", "if", "valid" ]
46eb4fc5ba0f65412634a37e30e05de79fc9db4c
https://github.com/fauskanger/mypolr/blob/46eb4fc5ba0f65412634a37e30e05de79fc9db4c/mypolr/polr_api.py#L76-L103
train
fauskanger/mypolr
mypolr/polr_api.py
PolrApi._get_ending
def _get_ending(self, lookup_url): """ Returns the short url ending from a short url or an short url ending. Example: - Given `<your Polr server>/5N3f8`, return `5N3f8`. - Given `5N3f8`, return `5N3f8`. :param lookup_url: A short url or short url ending :type lookup_url: str :return: The url ending :rtype: str """ if lookup_url.startswith(self.api_server): return lookup_url[len(self.api_server) + 1:] return lookup_url
python
def _get_ending(self, lookup_url): """ Returns the short url ending from a short url or an short url ending. Example: - Given `<your Polr server>/5N3f8`, return `5N3f8`. - Given `5N3f8`, return `5N3f8`. :param lookup_url: A short url or short url ending :type lookup_url: str :return: The url ending :rtype: str """ if lookup_url.startswith(self.api_server): return lookup_url[len(self.api_server) + 1:] return lookup_url
[ "def", "_get_ending", "(", "self", ",", "lookup_url", ")", ":", "if", "lookup_url", ".", "startswith", "(", "self", ".", "api_server", ")", ":", "return", "lookup_url", "[", "len", "(", "self", ".", "api_server", ")", "+", "1", ":", "]", "return", "lookup_url" ]
Returns the short url ending from a short url or an short url ending. Example: - Given `<your Polr server>/5N3f8`, return `5N3f8`. - Given `5N3f8`, return `5N3f8`. :param lookup_url: A short url or short url ending :type lookup_url: str :return: The url ending :rtype: str
[ "Returns", "the", "short", "url", "ending", "from", "a", "short", "url", "or", "an", "short", "url", "ending", "." ]
46eb4fc5ba0f65412634a37e30e05de79fc9db4c
https://github.com/fauskanger/mypolr/blob/46eb4fc5ba0f65412634a37e30e05de79fc9db4c/mypolr/polr_api.py#L105-L120
train
fauskanger/mypolr
mypolr/polr_api.py
PolrApi.lookup
def lookup(self, lookup_url, url_key=None): """ Looks up the url_ending to obtain information about the short url. If it exists, the API will return a dictionary with information, including the long_url that is the destination of the given short url URL. The lookup object looks like something like this: .. code-block:: python { 'clicks': 42, 'created_at': { 'date': '2017-12-03 00:40:45.000000', 'timezone': 'UTC', 'timezone_type': 3 }, 'long_url': 'https://stackoverflow.com/questions/tagged/python', 'updated_at': { 'date': '2017-12-24 13:37:00.000000', 'timezone': 'UTC', 'timezone_type': 3 } } :param str lookup_url: An url ending or full short url address :param url_key: optional URL ending key for lookups against secret URLs :type url_key: str or None :return: Lookup dictionary containing, among others things, the long url; or None if not existing :rtype: dict or None """ url_ending = self._get_ending(lookup_url) params = { 'url_ending': url_ending, 'url_key': url_key } data, r = self._make_request(self.api_lookup_endpoint, params) if r.status_code == 401: if url_key is not None: raise exceptions.UnauthorizedKeyError('given url_key is not valid for secret lookup.') raise exceptions.UnauthorizedKeyError elif r.status_code == 404: return False # no url found in lookup action = data.get('action') full_url = data.get('result') if action == 'lookup' and full_url is not None: return full_url raise exceptions.DebugTempWarning
python
def lookup(self, lookup_url, url_key=None): """ Looks up the url_ending to obtain information about the short url. If it exists, the API will return a dictionary with information, including the long_url that is the destination of the given short url URL. The lookup object looks like something like this: .. code-block:: python { 'clicks': 42, 'created_at': { 'date': '2017-12-03 00:40:45.000000', 'timezone': 'UTC', 'timezone_type': 3 }, 'long_url': 'https://stackoverflow.com/questions/tagged/python', 'updated_at': { 'date': '2017-12-24 13:37:00.000000', 'timezone': 'UTC', 'timezone_type': 3 } } :param str lookup_url: An url ending or full short url address :param url_key: optional URL ending key for lookups against secret URLs :type url_key: str or None :return: Lookup dictionary containing, among others things, the long url; or None if not existing :rtype: dict or None """ url_ending = self._get_ending(lookup_url) params = { 'url_ending': url_ending, 'url_key': url_key } data, r = self._make_request(self.api_lookup_endpoint, params) if r.status_code == 401: if url_key is not None: raise exceptions.UnauthorizedKeyError('given url_key is not valid for secret lookup.') raise exceptions.UnauthorizedKeyError elif r.status_code == 404: return False # no url found in lookup action = data.get('action') full_url = data.get('result') if action == 'lookup' and full_url is not None: return full_url raise exceptions.DebugTempWarning
[ "def", "lookup", "(", "self", ",", "lookup_url", ",", "url_key", "=", "None", ")", ":", "url_ending", "=", "self", ".", "_get_ending", "(", "lookup_url", ")", "params", "=", "{", "'url_ending'", ":", "url_ending", ",", "'url_key'", ":", "url_key", "}", "data", ",", "r", "=", "self", ".", "_make_request", "(", "self", ".", "api_lookup_endpoint", ",", "params", ")", "if", "r", ".", "status_code", "==", "401", ":", "if", "url_key", "is", "not", "None", ":", "raise", "exceptions", ".", "UnauthorizedKeyError", "(", "'given url_key is not valid for secret lookup.'", ")", "raise", "exceptions", ".", "UnauthorizedKeyError", "elif", "r", ".", "status_code", "==", "404", ":", "return", "False", "# no url found in lookup", "action", "=", "data", ".", "get", "(", "'action'", ")", "full_url", "=", "data", ".", "get", "(", "'result'", ")", "if", "action", "==", "'lookup'", "and", "full_url", "is", "not", "None", ":", "return", "full_url", "raise", "exceptions", ".", "DebugTempWarning" ]
Looks up the url_ending to obtain information about the short url. If it exists, the API will return a dictionary with information, including the long_url that is the destination of the given short url URL. The lookup object looks like something like this: .. code-block:: python { 'clicks': 42, 'created_at': { 'date': '2017-12-03 00:40:45.000000', 'timezone': 'UTC', 'timezone_type': 3 }, 'long_url': 'https://stackoverflow.com/questions/tagged/python', 'updated_at': { 'date': '2017-12-24 13:37:00.000000', 'timezone': 'UTC', 'timezone_type': 3 } } :param str lookup_url: An url ending or full short url address :param url_key: optional URL ending key for lookups against secret URLs :type url_key: str or None :return: Lookup dictionary containing, among others things, the long url; or None if not existing :rtype: dict or None
[ "Looks", "up", "the", "url_ending", "to", "obtain", "information", "about", "the", "short", "url", "." ]
46eb4fc5ba0f65412634a37e30e05de79fc9db4c
https://github.com/fauskanger/mypolr/blob/46eb4fc5ba0f65412634a37e30e05de79fc9db4c/mypolr/polr_api.py#L122-L173
train
fauskanger/mypolr
mypolr/cli.py
make_argparser
def make_argparser(): """ Setup argparse arguments. :return: The parser which :class:`MypolrCli` expects parsed arguments from. :rtype: argparse.ArgumentParser """ parser = argparse.ArgumentParser(prog='mypolr', description="Interacts with the Polr Project's API.\n\n" "User Guide and documentation: https://mypolr.readthedocs.io", formatter_class=argparse.ArgumentDefaultsHelpFormatter, epilog="NOTE: if configurations are saved, they are stored as plain text on disk, " "and can be read by anyone with access to the file.") parser.add_argument("-v", "--version", action="store_true", help="Print version and exit.") parser.add_argument("url", nargs='?', default=None, help="The url to process.") api_group = parser.add_argument_group('API server arguments', 'Use these for configure the API. Can be stored locally with --save.') api_group.add_argument("-s", "--server", default=None, help="Server hosting the API.") api_group.add_argument("-k", "--key", default=None, help="API_KEY to authenticate against server.") api_group.add_argument("--api-root", default=DEFAULT_API_ROOT, help="API endpoint root.") option_group = parser.add_argument_group('Action options', 'Configure the API action to use.') option_group.add_argument("-c", "--custom", default=None, help="Custom short url ending.") option_group.add_argument("--secret", action="store_true", help="Set option if using secret url.") option_group.add_argument("-l", "--lookup", action="store_true", help="Perform lookup action instead of shorten action.") manage_group = parser.add_argument_group('Manage credentials', 'Use these to save, delete or update SERVER, KEY and/or ' 'API_ROOT locally in ~/.mypolr/config.ini.') manage_group.add_argument("--save", action="store_true", help="Save configuration (including credentials) in plaintext(!).") manage_group.add_argument("--clear", action="store_true", help="Clear configuration.") return parser
python
def make_argparser(): """ Setup argparse arguments. :return: The parser which :class:`MypolrCli` expects parsed arguments from. :rtype: argparse.ArgumentParser """ parser = argparse.ArgumentParser(prog='mypolr', description="Interacts with the Polr Project's API.\n\n" "User Guide and documentation: https://mypolr.readthedocs.io", formatter_class=argparse.ArgumentDefaultsHelpFormatter, epilog="NOTE: if configurations are saved, they are stored as plain text on disk, " "and can be read by anyone with access to the file.") parser.add_argument("-v", "--version", action="store_true", help="Print version and exit.") parser.add_argument("url", nargs='?', default=None, help="The url to process.") api_group = parser.add_argument_group('API server arguments', 'Use these for configure the API. Can be stored locally with --save.') api_group.add_argument("-s", "--server", default=None, help="Server hosting the API.") api_group.add_argument("-k", "--key", default=None, help="API_KEY to authenticate against server.") api_group.add_argument("--api-root", default=DEFAULT_API_ROOT, help="API endpoint root.") option_group = parser.add_argument_group('Action options', 'Configure the API action to use.') option_group.add_argument("-c", "--custom", default=None, help="Custom short url ending.") option_group.add_argument("--secret", action="store_true", help="Set option if using secret url.") option_group.add_argument("-l", "--lookup", action="store_true", help="Perform lookup action instead of shorten action.") manage_group = parser.add_argument_group('Manage credentials', 'Use these to save, delete or update SERVER, KEY and/or ' 'API_ROOT locally in ~/.mypolr/config.ini.') manage_group.add_argument("--save", action="store_true", help="Save configuration (including credentials) in plaintext(!).") manage_group.add_argument("--clear", action="store_true", help="Clear configuration.") return parser
[ "def", "make_argparser", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "prog", "=", "'mypolr'", ",", "description", "=", "\"Interacts with the Polr Project's API.\\n\\n\"", "\"User Guide and documentation: https://mypolr.readthedocs.io\"", ",", "formatter_class", "=", "argparse", ".", "ArgumentDefaultsHelpFormatter", ",", "epilog", "=", "\"NOTE: if configurations are saved, they are stored as plain text on disk, \"", "\"and can be read by anyone with access to the file.\"", ")", "parser", ".", "add_argument", "(", "\"-v\"", ",", "\"--version\"", ",", "action", "=", "\"store_true\"", ",", "help", "=", "\"Print version and exit.\"", ")", "parser", ".", "add_argument", "(", "\"url\"", ",", "nargs", "=", "'?'", ",", "default", "=", "None", ",", "help", "=", "\"The url to process.\"", ")", "api_group", "=", "parser", ".", "add_argument_group", "(", "'API server arguments'", ",", "'Use these for configure the API. Can be stored locally with --save.'", ")", "api_group", ".", "add_argument", "(", "\"-s\"", ",", "\"--server\"", ",", "default", "=", "None", ",", "help", "=", "\"Server hosting the API.\"", ")", "api_group", ".", "add_argument", "(", "\"-k\"", ",", "\"--key\"", ",", "default", "=", "None", ",", "help", "=", "\"API_KEY to authenticate against server.\"", ")", "api_group", ".", "add_argument", "(", "\"--api-root\"", ",", "default", "=", "DEFAULT_API_ROOT", ",", "help", "=", "\"API endpoint root.\"", ")", "option_group", "=", "parser", ".", "add_argument_group", "(", "'Action options'", ",", "'Configure the API action to use.'", ")", "option_group", ".", "add_argument", "(", "\"-c\"", ",", "\"--custom\"", ",", "default", "=", "None", ",", "help", "=", "\"Custom short url ending.\"", ")", "option_group", ".", "add_argument", "(", "\"--secret\"", ",", "action", "=", "\"store_true\"", ",", "help", "=", "\"Set option if using secret url.\"", ")", "option_group", ".", "add_argument", "(", "\"-l\"", ",", "\"--lookup\"", ",", "action", "=", "\"store_true\"", ",", "help", "=", "\"Perform lookup action instead of shorten action.\"", ")", "manage_group", "=", "parser", ".", "add_argument_group", "(", "'Manage credentials'", ",", "'Use these to save, delete or update SERVER, KEY and/or '", "'API_ROOT locally in ~/.mypolr/config.ini.'", ")", "manage_group", ".", "add_argument", "(", "\"--save\"", ",", "action", "=", "\"store_true\"", ",", "help", "=", "\"Save configuration (including credentials) in plaintext(!).\"", ")", "manage_group", ".", "add_argument", "(", "\"--clear\"", ",", "action", "=", "\"store_true\"", ",", "help", "=", "\"Clear configuration.\"", ")", "return", "parser" ]
Setup argparse arguments. :return: The parser which :class:`MypolrCli` expects parsed arguments from. :rtype: argparse.ArgumentParser
[ "Setup", "argparse", "arguments", "." ]
46eb4fc5ba0f65412634a37e30e05de79fc9db4c
https://github.com/fauskanger/mypolr/blob/46eb4fc5ba0f65412634a37e30e05de79fc9db4c/mypolr/cli.py#L18-L61
train
ratt-ru/PyMORESANE
pymoresane/iuwt_toolbox.py
estimate_threshold
def estimate_threshold(in1, edge_excl=0, int_excl=0): """ This function estimates the noise using the MAD estimator. INPUTS: in1 (no default): The array from which the noise is estimated OUTPUTS: out1 An array of per-scale noise estimates. """ out1 = np.empty([in1.shape[0]]) mid = in1.shape[1]/2 if (edge_excl!=0) | (int_excl!=0): if edge_excl!=0: mask = np.zeros([in1.shape[1], in1.shape[2]]) mask[edge_excl:-edge_excl, edge_excl:-edge_excl] = 1 else: mask = np.ones([in1.shape[1], in1.shape[2]]) if int_excl!=0: mask[mid-int_excl:mid+int_excl, mid-int_excl:mid+int_excl] = 0 else: mask = np.ones([in1.shape[1], in1.shape[2]]) for i in range(in1.shape[0]): out1[i] = np.median(np.abs(in1[i,mask==1]))/0.6745 return out1
python
def estimate_threshold(in1, edge_excl=0, int_excl=0): """ This function estimates the noise using the MAD estimator. INPUTS: in1 (no default): The array from which the noise is estimated OUTPUTS: out1 An array of per-scale noise estimates. """ out1 = np.empty([in1.shape[0]]) mid = in1.shape[1]/2 if (edge_excl!=0) | (int_excl!=0): if edge_excl!=0: mask = np.zeros([in1.shape[1], in1.shape[2]]) mask[edge_excl:-edge_excl, edge_excl:-edge_excl] = 1 else: mask = np.ones([in1.shape[1], in1.shape[2]]) if int_excl!=0: mask[mid-int_excl:mid+int_excl, mid-int_excl:mid+int_excl] = 0 else: mask = np.ones([in1.shape[1], in1.shape[2]]) for i in range(in1.shape[0]): out1[i] = np.median(np.abs(in1[i,mask==1]))/0.6745 return out1
[ "def", "estimate_threshold", "(", "in1", ",", "edge_excl", "=", "0", ",", "int_excl", "=", "0", ")", ":", "out1", "=", "np", ".", "empty", "(", "[", "in1", ".", "shape", "[", "0", "]", "]", ")", "mid", "=", "in1", ".", "shape", "[", "1", "]", "/", "2", "if", "(", "edge_excl", "!=", "0", ")", "|", "(", "int_excl", "!=", "0", ")", ":", "if", "edge_excl", "!=", "0", ":", "mask", "=", "np", ".", "zeros", "(", "[", "in1", ".", "shape", "[", "1", "]", ",", "in1", ".", "shape", "[", "2", "]", "]", ")", "mask", "[", "edge_excl", ":", "-", "edge_excl", ",", "edge_excl", ":", "-", "edge_excl", "]", "=", "1", "else", ":", "mask", "=", "np", ".", "ones", "(", "[", "in1", ".", "shape", "[", "1", "]", ",", "in1", ".", "shape", "[", "2", "]", "]", ")", "if", "int_excl", "!=", "0", ":", "mask", "[", "mid", "-", "int_excl", ":", "mid", "+", "int_excl", ",", "mid", "-", "int_excl", ":", "mid", "+", "int_excl", "]", "=", "0", "else", ":", "mask", "=", "np", ".", "ones", "(", "[", "in1", ".", "shape", "[", "1", "]", ",", "in1", ".", "shape", "[", "2", "]", "]", ")", "for", "i", "in", "range", "(", "in1", ".", "shape", "[", "0", "]", ")", ":", "out1", "[", "i", "]", "=", "np", ".", "median", "(", "np", ".", "abs", "(", "in1", "[", "i", ",", "mask", "==", "1", "]", ")", ")", "/", "0.6745", "return", "out1" ]
This function estimates the noise using the MAD estimator. INPUTS: in1 (no default): The array from which the noise is estimated OUTPUTS: out1 An array of per-scale noise estimates.
[ "This", "function", "estimates", "the", "noise", "using", "the", "MAD", "estimator", "." ]
b024591ad0bbb69320d08841f28a2c27f62ae1af
https://github.com/ratt-ru/PyMORESANE/blob/b024591ad0bbb69320d08841f28a2c27f62ae1af/pymoresane/iuwt_toolbox.py#L17-L48
train
ratt-ru/PyMORESANE
pymoresane/iuwt_toolbox.py
source_extraction
def source_extraction(in1, tolerance, mode="cpu", store_on_gpu=False, neg_comp=False): """ Convenience function for allocating work to cpu or gpu, depending on the selected mode. INPUTS: in1 (no default): Array containing the wavelet decomposition. tolerance (no default): Percentage of maximum coefficient at which objects are deemed significant. mode (default="cpu"):Mode of operation - either "gpu" or "cpu". OUTPUTS: Array containing the significant wavelet coefficients of extracted sources. """ if mode=="cpu": return cpu_source_extraction(in1, tolerance, neg_comp) elif mode=="gpu": return gpu_source_extraction(in1, tolerance, store_on_gpu, neg_comp)
python
def source_extraction(in1, tolerance, mode="cpu", store_on_gpu=False, neg_comp=False): """ Convenience function for allocating work to cpu or gpu, depending on the selected mode. INPUTS: in1 (no default): Array containing the wavelet decomposition. tolerance (no default): Percentage of maximum coefficient at which objects are deemed significant. mode (default="cpu"):Mode of operation - either "gpu" or "cpu". OUTPUTS: Array containing the significant wavelet coefficients of extracted sources. """ if mode=="cpu": return cpu_source_extraction(in1, tolerance, neg_comp) elif mode=="gpu": return gpu_source_extraction(in1, tolerance, store_on_gpu, neg_comp)
[ "def", "source_extraction", "(", "in1", ",", "tolerance", ",", "mode", "=", "\"cpu\"", ",", "store_on_gpu", "=", "False", ",", "neg_comp", "=", "False", ")", ":", "if", "mode", "==", "\"cpu\"", ":", "return", "cpu_source_extraction", "(", "in1", ",", "tolerance", ",", "neg_comp", ")", "elif", "mode", "==", "\"gpu\"", ":", "return", "gpu_source_extraction", "(", "in1", ",", "tolerance", ",", "store_on_gpu", ",", "neg_comp", ")" ]
Convenience function for allocating work to cpu or gpu, depending on the selected mode. INPUTS: in1 (no default): Array containing the wavelet decomposition. tolerance (no default): Percentage of maximum coefficient at which objects are deemed significant. mode (default="cpu"):Mode of operation - either "gpu" or "cpu". OUTPUTS: Array containing the significant wavelet coefficients of extracted sources.
[ "Convenience", "function", "for", "allocating", "work", "to", "cpu", "or", "gpu", "depending", "on", "the", "selected", "mode", "." ]
b024591ad0bbb69320d08841f28a2c27f62ae1af
https://github.com/ratt-ru/PyMORESANE/blob/b024591ad0bbb69320d08841f28a2c27f62ae1af/pymoresane/iuwt_toolbox.py#L77-L94
train
ratt-ru/PyMORESANE
pymoresane/iuwt_toolbox.py
cpu_source_extraction
def cpu_source_extraction(in1, tolerance, neg_comp): """ The following function determines connectivity within a given wavelet decomposition. These connected and labelled structures are thresholded to within some tolerance of the maximum coefficient at the scale. This determines whether on not an object is to be considered as significant. Significant objects are extracted and factored into a mask which is finally multiplied by the wavelet coefficients to return only wavelet coefficients belonging to significant objects across all scales. INPUTS: in1 (no default): Array containing the wavelet decomposition. tolerance (no default): Percentage of maximum coefficient at which objects are deemed significant. OUTPUTS: objects*in1 The wavelet coefficients of the significant structures. objects The mask of the significant structures. """ # The following initialises some variables for storing the labelled image and the number of labels. The per scale # maxima are also initialised here. scale_maxima = np.empty([in1.shape[0],1]) objects = np.empty_like(in1, dtype=np.int32) object_count = np.empty([in1.shape[0],1], dtype=np.int32) # The following loop uses functionality from the ndimage module to assess connectivity. The maxima are also # calculated here. for i in range(in1.shape[0]): if neg_comp: scale_maxima[i] = np.max(abs(in1[i,:,:])) else: scale_maxima[i] = np.max(in1[i,:,:]) objects[i,:,:], object_count[i] = ndimage.label(in1[i,:,:], structure=[[1,1,1],[1,1,1],[1,1,1]]) # The following removes the insignificant objects and then extracts the remaining ones. for i in range(-1,-in1.shape[0]-1,-1): if neg_comp: if i==(-1): tmp = (abs(in1[i,:,:])>=(tolerance*scale_maxima[i]))*objects[i,:,:] else: tmp = (abs(in1[i,:,:])>=(tolerance*scale_maxima[i]))*objects[i,:,:]*objects[i+1,:,:] else: if i==(-1): tmp = (in1[i,:,:]>=(tolerance*scale_maxima[i]))*objects[i,:,:] else: tmp = (in1[i,:,:]>=(tolerance*scale_maxima[i]))*objects[i,:,:]*objects[i+1,:,:] labels = np.unique(tmp[tmp>0]) for j in labels: objects[i,(objects[i,:,:]==j)] = -1 objects[i,(objects[i,:,:]>0)] = 0 objects[i,:,:] = -(objects[i,:,:]) return objects*in1, objects
python
def cpu_source_extraction(in1, tolerance, neg_comp): """ The following function determines connectivity within a given wavelet decomposition. These connected and labelled structures are thresholded to within some tolerance of the maximum coefficient at the scale. This determines whether on not an object is to be considered as significant. Significant objects are extracted and factored into a mask which is finally multiplied by the wavelet coefficients to return only wavelet coefficients belonging to significant objects across all scales. INPUTS: in1 (no default): Array containing the wavelet decomposition. tolerance (no default): Percentage of maximum coefficient at which objects are deemed significant. OUTPUTS: objects*in1 The wavelet coefficients of the significant structures. objects The mask of the significant structures. """ # The following initialises some variables for storing the labelled image and the number of labels. The per scale # maxima are also initialised here. scale_maxima = np.empty([in1.shape[0],1]) objects = np.empty_like(in1, dtype=np.int32) object_count = np.empty([in1.shape[0],1], dtype=np.int32) # The following loop uses functionality from the ndimage module to assess connectivity. The maxima are also # calculated here. for i in range(in1.shape[0]): if neg_comp: scale_maxima[i] = np.max(abs(in1[i,:,:])) else: scale_maxima[i] = np.max(in1[i,:,:]) objects[i,:,:], object_count[i] = ndimage.label(in1[i,:,:], structure=[[1,1,1],[1,1,1],[1,1,1]]) # The following removes the insignificant objects and then extracts the remaining ones. for i in range(-1,-in1.shape[0]-1,-1): if neg_comp: if i==(-1): tmp = (abs(in1[i,:,:])>=(tolerance*scale_maxima[i]))*objects[i,:,:] else: tmp = (abs(in1[i,:,:])>=(tolerance*scale_maxima[i]))*objects[i,:,:]*objects[i+1,:,:] else: if i==(-1): tmp = (in1[i,:,:]>=(tolerance*scale_maxima[i]))*objects[i,:,:] else: tmp = (in1[i,:,:]>=(tolerance*scale_maxima[i]))*objects[i,:,:]*objects[i+1,:,:] labels = np.unique(tmp[tmp>0]) for j in labels: objects[i,(objects[i,:,:]==j)] = -1 objects[i,(objects[i,:,:]>0)] = 0 objects[i,:,:] = -(objects[i,:,:]) return objects*in1, objects
[ "def", "cpu_source_extraction", "(", "in1", ",", "tolerance", ",", "neg_comp", ")", ":", "# The following initialises some variables for storing the labelled image and the number of labels. The per scale", "# maxima are also initialised here.", "scale_maxima", "=", "np", ".", "empty", "(", "[", "in1", ".", "shape", "[", "0", "]", ",", "1", "]", ")", "objects", "=", "np", ".", "empty_like", "(", "in1", ",", "dtype", "=", "np", ".", "int32", ")", "object_count", "=", "np", ".", "empty", "(", "[", "in1", ".", "shape", "[", "0", "]", ",", "1", "]", ",", "dtype", "=", "np", ".", "int32", ")", "# The following loop uses functionality from the ndimage module to assess connectivity. The maxima are also", "# calculated here.", "for", "i", "in", "range", "(", "in1", ".", "shape", "[", "0", "]", ")", ":", "if", "neg_comp", ":", "scale_maxima", "[", "i", "]", "=", "np", ".", "max", "(", "abs", "(", "in1", "[", "i", ",", ":", ",", ":", "]", ")", ")", "else", ":", "scale_maxima", "[", "i", "]", "=", "np", ".", "max", "(", "in1", "[", "i", ",", ":", ",", ":", "]", ")", "objects", "[", "i", ",", ":", ",", ":", "]", ",", "object_count", "[", "i", "]", "=", "ndimage", ".", "label", "(", "in1", "[", "i", ",", ":", ",", ":", "]", ",", "structure", "=", "[", "[", "1", ",", "1", ",", "1", "]", ",", "[", "1", ",", "1", ",", "1", "]", ",", "[", "1", ",", "1", ",", "1", "]", "]", ")", "# The following removes the insignificant objects and then extracts the remaining ones.", "for", "i", "in", "range", "(", "-", "1", ",", "-", "in1", ".", "shape", "[", "0", "]", "-", "1", ",", "-", "1", ")", ":", "if", "neg_comp", ":", "if", "i", "==", "(", "-", "1", ")", ":", "tmp", "=", "(", "abs", "(", "in1", "[", "i", ",", ":", ",", ":", "]", ")", ">=", "(", "tolerance", "*", "scale_maxima", "[", "i", "]", ")", ")", "*", "objects", "[", "i", ",", ":", ",", ":", "]", "else", ":", "tmp", "=", "(", "abs", "(", "in1", "[", "i", ",", ":", ",", ":", "]", ")", ">=", "(", "tolerance", "*", "scale_maxima", "[", "i", "]", ")", ")", "*", "objects", "[", "i", ",", ":", ",", ":", "]", "*", "objects", "[", "i", "+", "1", ",", ":", ",", ":", "]", "else", ":", "if", "i", "==", "(", "-", "1", ")", ":", "tmp", "=", "(", "in1", "[", "i", ",", ":", ",", ":", "]", ">=", "(", "tolerance", "*", "scale_maxima", "[", "i", "]", ")", ")", "*", "objects", "[", "i", ",", ":", ",", ":", "]", "else", ":", "tmp", "=", "(", "in1", "[", "i", ",", ":", ",", ":", "]", ">=", "(", "tolerance", "*", "scale_maxima", "[", "i", "]", ")", ")", "*", "objects", "[", "i", ",", ":", ",", ":", "]", "*", "objects", "[", "i", "+", "1", ",", ":", ",", ":", "]", "labels", "=", "np", ".", "unique", "(", "tmp", "[", "tmp", ">", "0", "]", ")", "for", "j", "in", "labels", ":", "objects", "[", "i", ",", "(", "objects", "[", "i", ",", ":", ",", ":", "]", "==", "j", ")", "]", "=", "-", "1", "objects", "[", "i", ",", "(", "objects", "[", "i", ",", ":", ",", ":", "]", ">", "0", ")", "]", "=", "0", "objects", "[", "i", ",", ":", ",", ":", "]", "=", "-", "(", "objects", "[", "i", ",", ":", ",", ":", "]", ")", "return", "objects", "*", "in1", ",", "objects" ]
The following function determines connectivity within a given wavelet decomposition. These connected and labelled structures are thresholded to within some tolerance of the maximum coefficient at the scale. This determines whether on not an object is to be considered as significant. Significant objects are extracted and factored into a mask which is finally multiplied by the wavelet coefficients to return only wavelet coefficients belonging to significant objects across all scales. INPUTS: in1 (no default): Array containing the wavelet decomposition. tolerance (no default): Percentage of maximum coefficient at which objects are deemed significant. OUTPUTS: objects*in1 The wavelet coefficients of the significant structures. objects The mask of the significant structures.
[ "The", "following", "function", "determines", "connectivity", "within", "a", "given", "wavelet", "decomposition", ".", "These", "connected", "and", "labelled", "structures", "are", "thresholded", "to", "within", "some", "tolerance", "of", "the", "maximum", "coefficient", "at", "the", "scale", ".", "This", "determines", "whether", "on", "not", "an", "object", "is", "to", "be", "considered", "as", "significant", ".", "Significant", "objects", "are", "extracted", "and", "factored", "into", "a", "mask", "which", "is", "finally", "multiplied", "by", "the", "wavelet", "coefficients", "to", "return", "only", "wavelet", "coefficients", "belonging", "to", "significant", "objects", "across", "all", "scales", "." ]
b024591ad0bbb69320d08841f28a2c27f62ae1af
https://github.com/ratt-ru/PyMORESANE/blob/b024591ad0bbb69320d08841f28a2c27f62ae1af/pymoresane/iuwt_toolbox.py#L97-L154
train
ratt-ru/PyMORESANE
pymoresane/iuwt_toolbox.py
snr_ratio
def snr_ratio(in1, in2): """ The following function simply calculates the signal to noise ratio between two signals. INPUTS: in1 (no default): Array containing values for signal 1. in2 (no default): Array containing values for signal 2. OUTPUTS: out1 The ratio of the signal to noise ratios of two signals. """ out1 = 20*(np.log10(np.linalg.norm(in1)/np.linalg.norm(in1-in2))) return out1
python
def snr_ratio(in1, in2): """ The following function simply calculates the signal to noise ratio between two signals. INPUTS: in1 (no default): Array containing values for signal 1. in2 (no default): Array containing values for signal 2. OUTPUTS: out1 The ratio of the signal to noise ratios of two signals. """ out1 = 20*(np.log10(np.linalg.norm(in1)/np.linalg.norm(in1-in2))) return out1
[ "def", "snr_ratio", "(", "in1", ",", "in2", ")", ":", "out1", "=", "20", "*", "(", "np", ".", "log10", "(", "np", ".", "linalg", ".", "norm", "(", "in1", ")", "/", "np", ".", "linalg", ".", "norm", "(", "in1", "-", "in2", ")", ")", ")", "return", "out1" ]
The following function simply calculates the signal to noise ratio between two signals. INPUTS: in1 (no default): Array containing values for signal 1. in2 (no default): Array containing values for signal 2. OUTPUTS: out1 The ratio of the signal to noise ratios of two signals.
[ "The", "following", "function", "simply", "calculates", "the", "signal", "to", "noise", "ratio", "between", "two", "signals", "." ]
b024591ad0bbb69320d08841f28a2c27f62ae1af
https://github.com/ratt-ru/PyMORESANE/blob/b024591ad0bbb69320d08841f28a2c27f62ae1af/pymoresane/iuwt_toolbox.py#L292-L306
train
praekeltfoundation/seaworthy
seaworthy/containers/rabbitmq.py
RabbitMQContainer.wait_for_start
def wait_for_start(self): """ Wait for the RabbitMQ process to be come up. """ er = self.exec_rabbitmqctl( 'wait', ['--pid', '1', '--timeout', str(int(self.wait_timeout))]) output_lines(er, error_exc=TimeoutError)
python
def wait_for_start(self): """ Wait for the RabbitMQ process to be come up. """ er = self.exec_rabbitmqctl( 'wait', ['--pid', '1', '--timeout', str(int(self.wait_timeout))]) output_lines(er, error_exc=TimeoutError)
[ "def", "wait_for_start", "(", "self", ")", ":", "er", "=", "self", ".", "exec_rabbitmqctl", "(", "'wait'", ",", "[", "'--pid'", ",", "'1'", ",", "'--timeout'", ",", "str", "(", "int", "(", "self", ".", "wait_timeout", ")", ")", "]", ")", "output_lines", "(", "er", ",", "error_exc", "=", "TimeoutError", ")" ]
Wait for the RabbitMQ process to be come up.
[ "Wait", "for", "the", "RabbitMQ", "process", "to", "be", "come", "up", "." ]
6f10a19b45d4ea1dc3bd0553cc4d0438696c079c
https://github.com/praekeltfoundation/seaworthy/blob/6f10a19b45d4ea1dc3bd0553cc4d0438696c079c/seaworthy/containers/rabbitmq.py#L56-L62
train
praekeltfoundation/seaworthy
seaworthy/containers/rabbitmq.py
RabbitMQContainer.exec_rabbitmqctl
def exec_rabbitmqctl(self, command, args=[], rabbitmqctl_opts=['-q']): """ Execute a ``rabbitmqctl`` command inside a running container. :param command: the command to run :param args: a list of args for the command :param rabbitmqctl_opts: a list of extra options to pass to ``rabbitmqctl`` :returns: a tuple of the command exit code and output """ cmd = ['rabbitmqctl'] + rabbitmqctl_opts + [command] + args return self.inner().exec_run(cmd)
python
def exec_rabbitmqctl(self, command, args=[], rabbitmqctl_opts=['-q']): """ Execute a ``rabbitmqctl`` command inside a running container. :param command: the command to run :param args: a list of args for the command :param rabbitmqctl_opts: a list of extra options to pass to ``rabbitmqctl`` :returns: a tuple of the command exit code and output """ cmd = ['rabbitmqctl'] + rabbitmqctl_opts + [command] + args return self.inner().exec_run(cmd)
[ "def", "exec_rabbitmqctl", "(", "self", ",", "command", ",", "args", "=", "[", "]", ",", "rabbitmqctl_opts", "=", "[", "'-q'", "]", ")", ":", "cmd", "=", "[", "'rabbitmqctl'", "]", "+", "rabbitmqctl_opts", "+", "[", "command", "]", "+", "args", "return", "self", ".", "inner", "(", ")", ".", "exec_run", "(", "cmd", ")" ]
Execute a ``rabbitmqctl`` command inside a running container. :param command: the command to run :param args: a list of args for the command :param rabbitmqctl_opts: a list of extra options to pass to ``rabbitmqctl`` :returns: a tuple of the command exit code and output
[ "Execute", "a", "rabbitmqctl", "command", "inside", "a", "running", "container", "." ]
6f10a19b45d4ea1dc3bd0553cc4d0438696c079c
https://github.com/praekeltfoundation/seaworthy/blob/6f10a19b45d4ea1dc3bd0553cc4d0438696c079c/seaworthy/containers/rabbitmq.py#L87-L98
train
praekeltfoundation/seaworthy
seaworthy/containers/rabbitmq.py
RabbitMQContainer.exec_rabbitmqctl_list
def exec_rabbitmqctl_list(self, resources, args=[], rabbitmq_opts=['-q', '--no-table-headers']): """ Execute a ``rabbitmqctl`` command to list the given resources. :param resources: the resources to list, e.g. ``'vhosts'`` :param args: a list of args for the command :param rabbitmqctl_opts: a list of extra options to pass to ``rabbitmqctl`` :returns: a tuple of the command exit code and output """ command = 'list_{}'.format(resources) return self.exec_rabbitmqctl(command, args, rabbitmq_opts)
python
def exec_rabbitmqctl_list(self, resources, args=[], rabbitmq_opts=['-q', '--no-table-headers']): """ Execute a ``rabbitmqctl`` command to list the given resources. :param resources: the resources to list, e.g. ``'vhosts'`` :param args: a list of args for the command :param rabbitmqctl_opts: a list of extra options to pass to ``rabbitmqctl`` :returns: a tuple of the command exit code and output """ command = 'list_{}'.format(resources) return self.exec_rabbitmqctl(command, args, rabbitmq_opts)
[ "def", "exec_rabbitmqctl_list", "(", "self", ",", "resources", ",", "args", "=", "[", "]", ",", "rabbitmq_opts", "=", "[", "'-q'", ",", "'--no-table-headers'", "]", ")", ":", "command", "=", "'list_{}'", ".", "format", "(", "resources", ")", "return", "self", ".", "exec_rabbitmqctl", "(", "command", ",", "args", ",", "rabbitmq_opts", ")" ]
Execute a ``rabbitmqctl`` command to list the given resources. :param resources: the resources to list, e.g. ``'vhosts'`` :param args: a list of args for the command :param rabbitmqctl_opts: a list of extra options to pass to ``rabbitmqctl`` :returns: a tuple of the command exit code and output
[ "Execute", "a", "rabbitmqctl", "command", "to", "list", "the", "given", "resources", "." ]
6f10a19b45d4ea1dc3bd0553cc4d0438696c079c
https://github.com/praekeltfoundation/seaworthy/blob/6f10a19b45d4ea1dc3bd0553cc4d0438696c079c/seaworthy/containers/rabbitmq.py#L100-L112
train
praekeltfoundation/seaworthy
seaworthy/containers/rabbitmq.py
RabbitMQContainer.list_users
def list_users(self): """ Run the ``list_users`` command and return a list of tuples describing the users. :return: A list of 2-element tuples. The first element is the username, the second a list of tags for the user. """ lines = output_lines(self.exec_rabbitmqctl_list('users')) return [_parse_rabbitmq_user(line) for line in lines]
python
def list_users(self): """ Run the ``list_users`` command and return a list of tuples describing the users. :return: A list of 2-element tuples. The first element is the username, the second a list of tags for the user. """ lines = output_lines(self.exec_rabbitmqctl_list('users')) return [_parse_rabbitmq_user(line) for line in lines]
[ "def", "list_users", "(", "self", ")", ":", "lines", "=", "output_lines", "(", "self", ".", "exec_rabbitmqctl_list", "(", "'users'", ")", ")", "return", "[", "_parse_rabbitmq_user", "(", "line", ")", "for", "line", "in", "lines", "]" ]
Run the ``list_users`` command and return a list of tuples describing the users. :return: A list of 2-element tuples. The first element is the username, the second a list of tags for the user.
[ "Run", "the", "list_users", "command", "and", "return", "a", "list", "of", "tuples", "describing", "the", "users", "." ]
6f10a19b45d4ea1dc3bd0553cc4d0438696c079c
https://github.com/praekeltfoundation/seaworthy/blob/6f10a19b45d4ea1dc3bd0553cc4d0438696c079c/seaworthy/containers/rabbitmq.py#L133-L143
train
praekeltfoundation/seaworthy
seaworthy/containers/rabbitmq.py
RabbitMQContainer.broker_url
def broker_url(self): """ Returns a "broker URL" for use with Celery. """ return 'amqp://{}:{}@{}/{}'.format( self.user, self.password, self.name, self.vhost)
python
def broker_url(self): """ Returns a "broker URL" for use with Celery. """ return 'amqp://{}:{}@{}/{}'.format( self.user, self.password, self.name, self.vhost)
[ "def", "broker_url", "(", "self", ")", ":", "return", "'amqp://{}:{}@{}/{}'", ".", "format", "(", "self", ".", "user", ",", "self", ".", "password", ",", "self", ".", "name", ",", "self", ".", "vhost", ")" ]
Returns a "broker URL" for use with Celery.
[ "Returns", "a", "broker", "URL", "for", "use", "with", "Celery", "." ]
6f10a19b45d4ea1dc3bd0553cc4d0438696c079c
https://github.com/praekeltfoundation/seaworthy/blob/6f10a19b45d4ea1dc3bd0553cc4d0438696c079c/seaworthy/containers/rabbitmq.py#L145-L148
train
praekeltfoundation/seaworthy
seaworthy/containers/postgresql.py
PostgreSQLContainer.exec_pg_success
def exec_pg_success(self, cmd): """ Execute a command inside a running container as the postgres user, asserting success. """ result = self.inner().exec_run(cmd, user='postgres') assert result.exit_code == 0, result.output.decode('utf-8') return result
python
def exec_pg_success(self, cmd): """ Execute a command inside a running container as the postgres user, asserting success. """ result = self.inner().exec_run(cmd, user='postgres') assert result.exit_code == 0, result.output.decode('utf-8') return result
[ "def", "exec_pg_success", "(", "self", ",", "cmd", ")", ":", "result", "=", "self", ".", "inner", "(", ")", ".", "exec_run", "(", "cmd", ",", "user", "=", "'postgres'", ")", "assert", "result", ".", "exit_code", "==", "0", ",", "result", ".", "output", ".", "decode", "(", "'utf-8'", ")", "return", "result" ]
Execute a command inside a running container as the postgres user, asserting success.
[ "Execute", "a", "command", "inside", "a", "running", "container", "as", "the", "postgres", "user", "asserting", "success", "." ]
6f10a19b45d4ea1dc3bd0553cc4d0438696c079c
https://github.com/praekeltfoundation/seaworthy/blob/6f10a19b45d4ea1dc3bd0553cc4d0438696c079c/seaworthy/containers/postgresql.py#L63-L70
train
praekeltfoundation/seaworthy
seaworthy/containers/postgresql.py
PostgreSQLContainer.clean
def clean(self): """ Remove all data by dropping and recreating the configured database. .. note:: Only the configured database is removed. Any other databases remain untouched. """ self.exec_pg_success(['dropdb', '-U', self.user, self.database]) self.exec_pg_success(['createdb', '-U', self.user, self.database])
python
def clean(self): """ Remove all data by dropping and recreating the configured database. .. note:: Only the configured database is removed. Any other databases remain untouched. """ self.exec_pg_success(['dropdb', '-U', self.user, self.database]) self.exec_pg_success(['createdb', '-U', self.user, self.database])
[ "def", "clean", "(", "self", ")", ":", "self", ".", "exec_pg_success", "(", "[", "'dropdb'", ",", "'-U'", ",", "self", ".", "user", ",", "self", ".", "database", "]", ")", "self", ".", "exec_pg_success", "(", "[", "'createdb'", ",", "'-U'", ",", "self", ".", "user", ",", "self", ".", "database", "]", ")" ]
Remove all data by dropping and recreating the configured database. .. note:: Only the configured database is removed. Any other databases remain untouched.
[ "Remove", "all", "data", "by", "dropping", "and", "recreating", "the", "configured", "database", "." ]
6f10a19b45d4ea1dc3bd0553cc4d0438696c079c
https://github.com/praekeltfoundation/seaworthy/blob/6f10a19b45d4ea1dc3bd0553cc4d0438696c079c/seaworthy/containers/postgresql.py#L72-L82
train
praekeltfoundation/seaworthy
seaworthy/containers/postgresql.py
PostgreSQLContainer.exec_psql
def exec_psql(self, command, psql_opts=['-qtA']): """ Execute a ``psql`` command inside a running container. By default the container's database is connected to. :param command: the command to run (passed to ``-c``) :param psql_opts: a list of extra options to pass to ``psql`` :returns: a tuple of the command exit code and output """ cmd = ['psql'] + psql_opts + [ '--dbname', self.database, '-U', self.user, '-c', command, ] return self.inner().exec_run(cmd, user='postgres')
python
def exec_psql(self, command, psql_opts=['-qtA']): """ Execute a ``psql`` command inside a running container. By default the container's database is connected to. :param command: the command to run (passed to ``-c``) :param psql_opts: a list of extra options to pass to ``psql`` :returns: a tuple of the command exit code and output """ cmd = ['psql'] + psql_opts + [ '--dbname', self.database, '-U', self.user, '-c', command, ] return self.inner().exec_run(cmd, user='postgres')
[ "def", "exec_psql", "(", "self", ",", "command", ",", "psql_opts", "=", "[", "'-qtA'", "]", ")", ":", "cmd", "=", "[", "'psql'", "]", "+", "psql_opts", "+", "[", "'--dbname'", ",", "self", ".", "database", ",", "'-U'", ",", "self", ".", "user", ",", "'-c'", ",", "command", ",", "]", "return", "self", ".", "inner", "(", ")", ".", "exec_run", "(", "cmd", ",", "user", "=", "'postgres'", ")" ]
Execute a ``psql`` command inside a running container. By default the container's database is connected to. :param command: the command to run (passed to ``-c``) :param psql_opts: a list of extra options to pass to ``psql`` :returns: a tuple of the command exit code and output
[ "Execute", "a", "psql", "command", "inside", "a", "running", "container", ".", "By", "default", "the", "container", "s", "database", "is", "connected", "to", "." ]
6f10a19b45d4ea1dc3bd0553cc4d0438696c079c
https://github.com/praekeltfoundation/seaworthy/blob/6f10a19b45d4ea1dc3bd0553cc4d0438696c079c/seaworthy/containers/postgresql.py#L84-L98
train
praekeltfoundation/seaworthy
seaworthy/containers/postgresql.py
PostgreSQLContainer.list_databases
def list_databases(self): """ Runs the ``\\list`` command and returns a list of column values with information about all databases. """ lines = output_lines(self.exec_psql('\\list')) return [line.split('|') for line in lines]
python
def list_databases(self): """ Runs the ``\\list`` command and returns a list of column values with information about all databases. """ lines = output_lines(self.exec_psql('\\list')) return [line.split('|') for line in lines]
[ "def", "list_databases", "(", "self", ")", ":", "lines", "=", "output_lines", "(", "self", ".", "exec_psql", "(", "'\\\\list'", ")", ")", "return", "[", "line", ".", "split", "(", "'|'", ")", "for", "line", "in", "lines", "]" ]
Runs the ``\\list`` command and returns a list of column values with information about all databases.
[ "Runs", "the", "\\\\", "list", "command", "and", "returns", "a", "list", "of", "column", "values", "with", "information", "about", "all", "databases", "." ]
6f10a19b45d4ea1dc3bd0553cc4d0438696c079c
https://github.com/praekeltfoundation/seaworthy/blob/6f10a19b45d4ea1dc3bd0553cc4d0438696c079c/seaworthy/containers/postgresql.py#L100-L106
train
praekeltfoundation/seaworthy
seaworthy/containers/postgresql.py
PostgreSQLContainer.list_tables
def list_tables(self): """ Runs the ``\\dt`` command and returns a list of column values with information about all tables in the database. """ lines = output_lines(self.exec_psql('\\dt')) return [line.split('|') for line in lines]
python
def list_tables(self): """ Runs the ``\\dt`` command and returns a list of column values with information about all tables in the database. """ lines = output_lines(self.exec_psql('\\dt')) return [line.split('|') for line in lines]
[ "def", "list_tables", "(", "self", ")", ":", "lines", "=", "output_lines", "(", "self", ".", "exec_psql", "(", "'\\\\dt'", ")", ")", "return", "[", "line", ".", "split", "(", "'|'", ")", "for", "line", "in", "lines", "]" ]
Runs the ``\\dt`` command and returns a list of column values with information about all tables in the database.
[ "Runs", "the", "\\\\", "dt", "command", "and", "returns", "a", "list", "of", "column", "values", "with", "information", "about", "all", "tables", "in", "the", "database", "." ]
6f10a19b45d4ea1dc3bd0553cc4d0438696c079c
https://github.com/praekeltfoundation/seaworthy/blob/6f10a19b45d4ea1dc3bd0553cc4d0438696c079c/seaworthy/containers/postgresql.py#L108-L114
train
praekeltfoundation/seaworthy
seaworthy/containers/postgresql.py
PostgreSQLContainer.list_users
def list_users(self): """ Runs the ``\\du`` command and returns a list of column values with information about all user roles. """ lines = output_lines(self.exec_psql('\\du')) return [line.split('|') for line in lines]
python
def list_users(self): """ Runs the ``\\du`` command and returns a list of column values with information about all user roles. """ lines = output_lines(self.exec_psql('\\du')) return [line.split('|') for line in lines]
[ "def", "list_users", "(", "self", ")", ":", "lines", "=", "output_lines", "(", "self", ".", "exec_psql", "(", "'\\\\du'", ")", ")", "return", "[", "line", ".", "split", "(", "'|'", ")", "for", "line", "in", "lines", "]" ]
Runs the ``\\du`` command and returns a list of column values with information about all user roles.
[ "Runs", "the", "\\\\", "du", "command", "and", "returns", "a", "list", "of", "column", "values", "with", "information", "about", "all", "user", "roles", "." ]
6f10a19b45d4ea1dc3bd0553cc4d0438696c079c
https://github.com/praekeltfoundation/seaworthy/blob/6f10a19b45d4ea1dc3bd0553cc4d0438696c079c/seaworthy/containers/postgresql.py#L116-L122
train
praekeltfoundation/seaworthy
seaworthy/containers/postgresql.py
PostgreSQLContainer.database_url
def database_url(self): """ Returns a "database URL" for use with DJ-Database-URL and similar libraries. """ return 'postgres://{}:{}@{}/{}'.format( self.user, self.password, self.name, self.database)
python
def database_url(self): """ Returns a "database URL" for use with DJ-Database-URL and similar libraries. """ return 'postgres://{}:{}@{}/{}'.format( self.user, self.password, self.name, self.database)
[ "def", "database_url", "(", "self", ")", ":", "return", "'postgres://{}:{}@{}/{}'", ".", "format", "(", "self", ".", "user", ",", "self", ".", "password", ",", "self", ".", "name", ",", "self", ".", "database", ")" ]
Returns a "database URL" for use with DJ-Database-URL and similar libraries.
[ "Returns", "a", "database", "URL", "for", "use", "with", "DJ", "-", "Database", "-", "URL", "and", "similar", "libraries", "." ]
6f10a19b45d4ea1dc3bd0553cc4d0438696c079c
https://github.com/praekeltfoundation/seaworthy/blob/6f10a19b45d4ea1dc3bd0553cc4d0438696c079c/seaworthy/containers/postgresql.py#L124-L130
train
ionelmc/python-matrix
src/matrix/__init__.py
from_config
def from_config(config): """ Generate a matrix from a configuration dictionary. """ matrix = {} variables = config.keys() for entries in product(*config.values()): combination = dict(zip(variables, entries)) include = True for value in combination.values(): for reducer in value.reducers: if reducer.pattern == '-': match = not combination[reducer.variable].value else: match = fnmatch(combination[reducer.variable].value, reducer.pattern) if match if reducer.is_exclude else not match: include = False if include: key = '-'.join(entry.alias for entry in entries if entry.alias) data = dict( zip(variables, (entry.value for entry in entries)) ) if key in matrix and data != matrix[key]: raise DuplicateEnvironment(key, data, matrix[key]) matrix[key] = data return matrix
python
def from_config(config): """ Generate a matrix from a configuration dictionary. """ matrix = {} variables = config.keys() for entries in product(*config.values()): combination = dict(zip(variables, entries)) include = True for value in combination.values(): for reducer in value.reducers: if reducer.pattern == '-': match = not combination[reducer.variable].value else: match = fnmatch(combination[reducer.variable].value, reducer.pattern) if match if reducer.is_exclude else not match: include = False if include: key = '-'.join(entry.alias for entry in entries if entry.alias) data = dict( zip(variables, (entry.value for entry in entries)) ) if key in matrix and data != matrix[key]: raise DuplicateEnvironment(key, data, matrix[key]) matrix[key] = data return matrix
[ "def", "from_config", "(", "config", ")", ":", "matrix", "=", "{", "}", "variables", "=", "config", ".", "keys", "(", ")", "for", "entries", "in", "product", "(", "*", "config", ".", "values", "(", ")", ")", ":", "combination", "=", "dict", "(", "zip", "(", "variables", ",", "entries", ")", ")", "include", "=", "True", "for", "value", "in", "combination", ".", "values", "(", ")", ":", "for", "reducer", "in", "value", ".", "reducers", ":", "if", "reducer", ".", "pattern", "==", "'-'", ":", "match", "=", "not", "combination", "[", "reducer", ".", "variable", "]", ".", "value", "else", ":", "match", "=", "fnmatch", "(", "combination", "[", "reducer", ".", "variable", "]", ".", "value", ",", "reducer", ".", "pattern", ")", "if", "match", "if", "reducer", ".", "is_exclude", "else", "not", "match", ":", "include", "=", "False", "if", "include", ":", "key", "=", "'-'", ".", "join", "(", "entry", ".", "alias", "for", "entry", "in", "entries", "if", "entry", ".", "alias", ")", "data", "=", "dict", "(", "zip", "(", "variables", ",", "(", "entry", ".", "value", "for", "entry", "in", "entries", ")", ")", ")", "if", "key", "in", "matrix", "and", "data", "!=", "matrix", "[", "key", "]", ":", "raise", "DuplicateEnvironment", "(", "key", ",", "data", ",", "matrix", "[", "key", "]", ")", "matrix", "[", "key", "]", "=", "data", "return", "matrix" ]
Generate a matrix from a configuration dictionary.
[ "Generate", "a", "matrix", "from", "a", "configuration", "dictionary", "." ]
e1a63879a6c94c37c3883386f1d86eb7c2179a5b
https://github.com/ionelmc/python-matrix/blob/e1a63879a6c94c37c3883386f1d86eb7c2179a5b/src/matrix/__init__.py#L131-L156
train
tuomas2/automate
src/automate/worker.py
StatusWorkerThread.flush
def flush(self): """ This only needs to be called manually from unit tests """ self.logger.debug('Flush joining') self.queue.join() self.logger.debug('Flush joining ready')
python
def flush(self): """ This only needs to be called manually from unit tests """ self.logger.debug('Flush joining') self.queue.join() self.logger.debug('Flush joining ready')
[ "def", "flush", "(", "self", ")", ":", "self", ".", "logger", ".", "debug", "(", "'Flush joining'", ")", "self", ".", "queue", ".", "join", "(", ")", "self", ".", "logger", ".", "debug", "(", "'Flush joining ready'", ")" ]
This only needs to be called manually from unit tests
[ "This", "only", "needs", "to", "be", "called", "manually", "from", "unit", "tests" ]
d8a8cd03cd0da047e033a2d305f3f260f8c4e017
https://github.com/tuomas2/automate/blob/d8a8cd03cd0da047e033a2d305f3f260f8c4e017/src/automate/worker.py#L112-L119
train
praekeltfoundation/seaworthy
seaworthy/utils.py
output_lines
def output_lines(output, encoding='utf-8', error_exc=None): """ Convert bytestring container output or the result of a container exec command into a sequence of unicode lines. :param output: Container output bytes or an :class:`docker.models.containers.ExecResult` instance. :param encoding: The encoding to use when converting bytes to unicode (default ``utf-8``). :param error_exc: Optional exception to raise if ``output`` is an ``ExecResult`` with a nonzero exit code. :returns: list[str] """ if isinstance(output, ExecResult): exit_code, output = output if exit_code != 0 and error_exc is not None: raise error_exc(output.decode(encoding)) return output.decode(encoding).splitlines()
python
def output_lines(output, encoding='utf-8', error_exc=None): """ Convert bytestring container output or the result of a container exec command into a sequence of unicode lines. :param output: Container output bytes or an :class:`docker.models.containers.ExecResult` instance. :param encoding: The encoding to use when converting bytes to unicode (default ``utf-8``). :param error_exc: Optional exception to raise if ``output`` is an ``ExecResult`` with a nonzero exit code. :returns: list[str] """ if isinstance(output, ExecResult): exit_code, output = output if exit_code != 0 and error_exc is not None: raise error_exc(output.decode(encoding)) return output.decode(encoding).splitlines()
[ "def", "output_lines", "(", "output", ",", "encoding", "=", "'utf-8'", ",", "error_exc", "=", "None", ")", ":", "if", "isinstance", "(", "output", ",", "ExecResult", ")", ":", "exit_code", ",", "output", "=", "output", "if", "exit_code", "!=", "0", "and", "error_exc", "is", "not", "None", ":", "raise", "error_exc", "(", "output", ".", "decode", "(", "encoding", ")", ")", "return", "output", ".", "decode", "(", "encoding", ")", ".", "splitlines", "(", ")" ]
Convert bytestring container output or the result of a container exec command into a sequence of unicode lines. :param output: Container output bytes or an :class:`docker.models.containers.ExecResult` instance. :param encoding: The encoding to use when converting bytes to unicode (default ``utf-8``). :param error_exc: Optional exception to raise if ``output`` is an ``ExecResult`` with a nonzero exit code. :returns: list[str]
[ "Convert", "bytestring", "container", "output", "or", "the", "result", "of", "a", "container", "exec", "command", "into", "a", "sequence", "of", "unicode", "lines", "." ]
6f10a19b45d4ea1dc3bd0553cc4d0438696c079c
https://github.com/praekeltfoundation/seaworthy/blob/6f10a19b45d4ea1dc3bd0553cc4d0438696c079c/seaworthy/utils.py#L4-L27
train
utek/pyseaweed
pyseaweed/weed.py
WeedFS.get_file
def get_file(self, fid): """Get file from WeedFS. Returns file content. May be problematic for large files as content is stored in memory. Args: **fid**: File identifier <volume_id>,<file_name_hash> Returns: Content of the file with provided fid or None if file doesn't exist on the server .. versionadded:: 0.3.1 """ url = self.get_file_url(fid) return self.conn.get_raw_data(url)
python
def get_file(self, fid): """Get file from WeedFS. Returns file content. May be problematic for large files as content is stored in memory. Args: **fid**: File identifier <volume_id>,<file_name_hash> Returns: Content of the file with provided fid or None if file doesn't exist on the server .. versionadded:: 0.3.1 """ url = self.get_file_url(fid) return self.conn.get_raw_data(url)
[ "def", "get_file", "(", "self", ",", "fid", ")", ":", "url", "=", "self", ".", "get_file_url", "(", "fid", ")", "return", "self", ".", "conn", ".", "get_raw_data", "(", "url", ")" ]
Get file from WeedFS. Returns file content. May be problematic for large files as content is stored in memory. Args: **fid**: File identifier <volume_id>,<file_name_hash> Returns: Content of the file with provided fid or None if file doesn't exist on the server .. versionadded:: 0.3.1
[ "Get", "file", "from", "WeedFS", "." ]
218049329885425a2b8370157fa44952e64516be
https://github.com/utek/pyseaweed/blob/218049329885425a2b8370157fa44952e64516be/pyseaweed/weed.py#L50-L66
train
utek/pyseaweed
pyseaweed/weed.py
WeedFS.get_file_url
def get_file_url(self, fid, public=None): """ Get url for the file :param string fid: File ID :param boolean public: public or internal url :rtype: string """ try: volume_id, rest = fid.strip().split(",") except ValueError: raise BadFidFormat( "fid must be in format: <volume_id>,<file_name_hash>") file_location = self.get_file_location(volume_id) if public is None: public = self.use_public_url volume_url = file_location.public_url if public else file_location.url url = "http://{volume_url}/{fid}".format( volume_url=volume_url, fid=fid) return url
python
def get_file_url(self, fid, public=None): """ Get url for the file :param string fid: File ID :param boolean public: public or internal url :rtype: string """ try: volume_id, rest = fid.strip().split(",") except ValueError: raise BadFidFormat( "fid must be in format: <volume_id>,<file_name_hash>") file_location = self.get_file_location(volume_id) if public is None: public = self.use_public_url volume_url = file_location.public_url if public else file_location.url url = "http://{volume_url}/{fid}".format( volume_url=volume_url, fid=fid) return url
[ "def", "get_file_url", "(", "self", ",", "fid", ",", "public", "=", "None", ")", ":", "try", ":", "volume_id", ",", "rest", "=", "fid", ".", "strip", "(", ")", ".", "split", "(", "\",\"", ")", "except", "ValueError", ":", "raise", "BadFidFormat", "(", "\"fid must be in format: <volume_id>,<file_name_hash>\"", ")", "file_location", "=", "self", ".", "get_file_location", "(", "volume_id", ")", "if", "public", "is", "None", ":", "public", "=", "self", ".", "use_public_url", "volume_url", "=", "file_location", ".", "public_url", "if", "public", "else", "file_location", ".", "url", "url", "=", "\"http://{volume_url}/{fid}\"", ".", "format", "(", "volume_url", "=", "volume_url", ",", "fid", "=", "fid", ")", "return", "url" ]
Get url for the file :param string fid: File ID :param boolean public: public or internal url :rtype: string
[ "Get", "url", "for", "the", "file" ]
218049329885425a2b8370157fa44952e64516be
https://github.com/utek/pyseaweed/blob/218049329885425a2b8370157fa44952e64516be/pyseaweed/weed.py#L68-L87
train
utek/pyseaweed
pyseaweed/weed.py
WeedFS.get_file_location
def get_file_location(self, volume_id): """ Get location for the file, WeedFS volume is choosed randomly :param integer volume_id: volume_id :rtype: namedtuple `FileLocation` `{"public_url":"", "url":""}` """ url = ("http://{master_addr}:{master_port}/" "dir/lookup?volumeId={volume_id}").format( master_addr=self.master_addr, master_port=self.master_port, volume_id=volume_id) data = json.loads(self.conn.get_data(url)) _file_location = random.choice(data['locations']) FileLocation = namedtuple('FileLocation', "public_url url") return FileLocation(_file_location['publicUrl'], _file_location['url'])
python
def get_file_location(self, volume_id): """ Get location for the file, WeedFS volume is choosed randomly :param integer volume_id: volume_id :rtype: namedtuple `FileLocation` `{"public_url":"", "url":""}` """ url = ("http://{master_addr}:{master_port}/" "dir/lookup?volumeId={volume_id}").format( master_addr=self.master_addr, master_port=self.master_port, volume_id=volume_id) data = json.loads(self.conn.get_data(url)) _file_location = random.choice(data['locations']) FileLocation = namedtuple('FileLocation', "public_url url") return FileLocation(_file_location['publicUrl'], _file_location['url'])
[ "def", "get_file_location", "(", "self", ",", "volume_id", ")", ":", "url", "=", "(", "\"http://{master_addr}:{master_port}/\"", "\"dir/lookup?volumeId={volume_id}\"", ")", ".", "format", "(", "master_addr", "=", "self", ".", "master_addr", ",", "master_port", "=", "self", ".", "master_port", ",", "volume_id", "=", "volume_id", ")", "data", "=", "json", ".", "loads", "(", "self", ".", "conn", ".", "get_data", "(", "url", ")", ")", "_file_location", "=", "random", ".", "choice", "(", "data", "[", "'locations'", "]", ")", "FileLocation", "=", "namedtuple", "(", "'FileLocation'", ",", "\"public_url url\"", ")", "return", "FileLocation", "(", "_file_location", "[", "'publicUrl'", "]", ",", "_file_location", "[", "'url'", "]", ")" ]
Get location for the file, WeedFS volume is choosed randomly :param integer volume_id: volume_id :rtype: namedtuple `FileLocation` `{"public_url":"", "url":""}`
[ "Get", "location", "for", "the", "file", "WeedFS", "volume", "is", "choosed", "randomly" ]
218049329885425a2b8370157fa44952e64516be
https://github.com/utek/pyseaweed/blob/218049329885425a2b8370157fa44952e64516be/pyseaweed/weed.py#L89-L105
train
utek/pyseaweed
pyseaweed/weed.py
WeedFS.get_file_size
def get_file_size(self, fid): """ Gets size of uploaded file Or None if file doesn't exist. Args: **fid**: File identifier <volume_id>,<file_name_hash> Returns: Int or None """ url = self.get_file_url(fid) res = self.conn.head(url) if res is not None: size = res.headers.get("content-length", None) if size is not None: return int(size) return None
python
def get_file_size(self, fid): """ Gets size of uploaded file Or None if file doesn't exist. Args: **fid**: File identifier <volume_id>,<file_name_hash> Returns: Int or None """ url = self.get_file_url(fid) res = self.conn.head(url) if res is not None: size = res.headers.get("content-length", None) if size is not None: return int(size) return None
[ "def", "get_file_size", "(", "self", ",", "fid", ")", ":", "url", "=", "self", ".", "get_file_url", "(", "fid", ")", "res", "=", "self", ".", "conn", ".", "head", "(", "url", ")", "if", "res", "is", "not", "None", ":", "size", "=", "res", ".", "headers", ".", "get", "(", "\"content-length\"", ",", "None", ")", "if", "size", "is", "not", "None", ":", "return", "int", "(", "size", ")", "return", "None" ]
Gets size of uploaded file Or None if file doesn't exist. Args: **fid**: File identifier <volume_id>,<file_name_hash> Returns: Int or None
[ "Gets", "size", "of", "uploaded", "file", "Or", "None", "if", "file", "doesn", "t", "exist", "." ]
218049329885425a2b8370157fa44952e64516be
https://github.com/utek/pyseaweed/blob/218049329885425a2b8370157fa44952e64516be/pyseaweed/weed.py#L107-L124
train
utek/pyseaweed
pyseaweed/weed.py
WeedFS.file_exists
def file_exists(self, fid): """Checks if file with provided fid exists Args: **fid**: File identifier <volume_id>,<file_name_hash> Returns: True if file exists. False if not. """ res = self.get_file_size(fid) if res is not None: return True return False
python
def file_exists(self, fid): """Checks if file with provided fid exists Args: **fid**: File identifier <volume_id>,<file_name_hash> Returns: True if file exists. False if not. """ res = self.get_file_size(fid) if res is not None: return True return False
[ "def", "file_exists", "(", "self", ",", "fid", ")", ":", "res", "=", "self", ".", "get_file_size", "(", "fid", ")", "if", "res", "is", "not", "None", ":", "return", "True", "return", "False" ]
Checks if file with provided fid exists Args: **fid**: File identifier <volume_id>,<file_name_hash> Returns: True if file exists. False if not.
[ "Checks", "if", "file", "with", "provided", "fid", "exists" ]
218049329885425a2b8370157fa44952e64516be
https://github.com/utek/pyseaweed/blob/218049329885425a2b8370157fa44952e64516be/pyseaweed/weed.py#L126-L138
train
utek/pyseaweed
pyseaweed/weed.py
WeedFS.delete_file
def delete_file(self, fid): """ Delete file from WeedFS :param string fid: File ID """ url = self.get_file_url(fid) return self.conn.delete_data(url)
python
def delete_file(self, fid): """ Delete file from WeedFS :param string fid: File ID """ url = self.get_file_url(fid) return self.conn.delete_data(url)
[ "def", "delete_file", "(", "self", ",", "fid", ")", ":", "url", "=", "self", ".", "get_file_url", "(", "fid", ")", "return", "self", ".", "conn", ".", "delete_data", "(", "url", ")" ]
Delete file from WeedFS :param string fid: File ID
[ "Delete", "file", "from", "WeedFS" ]
218049329885425a2b8370157fa44952e64516be
https://github.com/utek/pyseaweed/blob/218049329885425a2b8370157fa44952e64516be/pyseaweed/weed.py#L140-L147
train
utek/pyseaweed
pyseaweed/weed.py
WeedFS.upload_file
def upload_file(self, path=None, stream=None, name=None, **kwargs): """ Uploads file to WeedFS I takes either path or stream and name and upload it to WeedFS server. Returns fid of the uploaded file. :param string path: :param string stream: :param string name: :rtype: string or None """ params = "&".join(["%s=%s" % (k, v) for k, v in kwargs.items()]) url = "http://{master_addr}:{master_port}/dir/assign{params}".format( master_addr=self.master_addr, master_port=self.master_port, params="?" + params if params else '' ) data = json.loads(self.conn.get_data(url)) if data.get("error") is not None: return None post_url = "http://{url}/{fid}".format( url=data['publicUrl' if self.use_public_url else 'url'], fid=data['fid'] ) if path is not None: filename = os.path.basename(path) with open(path, "rb") as file_stream: res = self.conn.post_file(post_url, filename, file_stream) # we have file like object and filename elif stream is not None and name is not None: res = self.conn.post_file(post_url, name, stream) else: raise ValueError( "If `path` is None then *both* `stream` and `name` must not" " be None ") response_data = json.loads(res) if "size" in response_data: return data.get('fid') return None
python
def upload_file(self, path=None, stream=None, name=None, **kwargs): """ Uploads file to WeedFS I takes either path or stream and name and upload it to WeedFS server. Returns fid of the uploaded file. :param string path: :param string stream: :param string name: :rtype: string or None """ params = "&".join(["%s=%s" % (k, v) for k, v in kwargs.items()]) url = "http://{master_addr}:{master_port}/dir/assign{params}".format( master_addr=self.master_addr, master_port=self.master_port, params="?" + params if params else '' ) data = json.loads(self.conn.get_data(url)) if data.get("error") is not None: return None post_url = "http://{url}/{fid}".format( url=data['publicUrl' if self.use_public_url else 'url'], fid=data['fid'] ) if path is not None: filename = os.path.basename(path) with open(path, "rb") as file_stream: res = self.conn.post_file(post_url, filename, file_stream) # we have file like object and filename elif stream is not None and name is not None: res = self.conn.post_file(post_url, name, stream) else: raise ValueError( "If `path` is None then *both* `stream` and `name` must not" " be None ") response_data = json.loads(res) if "size" in response_data: return data.get('fid') return None
[ "def", "upload_file", "(", "self", ",", "path", "=", "None", ",", "stream", "=", "None", ",", "name", "=", "None", ",", "*", "*", "kwargs", ")", ":", "params", "=", "\"&\"", ".", "join", "(", "[", "\"%s=%s\"", "%", "(", "k", ",", "v", ")", "for", "k", ",", "v", "in", "kwargs", ".", "items", "(", ")", "]", ")", "url", "=", "\"http://{master_addr}:{master_port}/dir/assign{params}\"", ".", "format", "(", "master_addr", "=", "self", ".", "master_addr", ",", "master_port", "=", "self", ".", "master_port", ",", "params", "=", "\"?\"", "+", "params", "if", "params", "else", "''", ")", "data", "=", "json", ".", "loads", "(", "self", ".", "conn", ".", "get_data", "(", "url", ")", ")", "if", "data", ".", "get", "(", "\"error\"", ")", "is", "not", "None", ":", "return", "None", "post_url", "=", "\"http://{url}/{fid}\"", ".", "format", "(", "url", "=", "data", "[", "'publicUrl'", "if", "self", ".", "use_public_url", "else", "'url'", "]", ",", "fid", "=", "data", "[", "'fid'", "]", ")", "if", "path", "is", "not", "None", ":", "filename", "=", "os", ".", "path", ".", "basename", "(", "path", ")", "with", "open", "(", "path", ",", "\"rb\"", ")", "as", "file_stream", ":", "res", "=", "self", ".", "conn", ".", "post_file", "(", "post_url", ",", "filename", ",", "file_stream", ")", "# we have file like object and filename", "elif", "stream", "is", "not", "None", "and", "name", "is", "not", "None", ":", "res", "=", "self", ".", "conn", ".", "post_file", "(", "post_url", ",", "name", ",", "stream", ")", "else", ":", "raise", "ValueError", "(", "\"If `path` is None then *both* `stream` and `name` must not\"", "\" be None \"", ")", "response_data", "=", "json", ".", "loads", "(", "res", ")", "if", "\"size\"", "in", "response_data", ":", "return", "data", ".", "get", "(", "'fid'", ")", "return", "None" ]
Uploads file to WeedFS I takes either path or stream and name and upload it to WeedFS server. Returns fid of the uploaded file. :param string path: :param string stream: :param string name: :rtype: string or None
[ "Uploads", "file", "to", "WeedFS" ]
218049329885425a2b8370157fa44952e64516be
https://github.com/utek/pyseaweed/blob/218049329885425a2b8370157fa44952e64516be/pyseaweed/weed.py#L149-L192
train
utek/pyseaweed
pyseaweed/weed.py
WeedFS.vacuum
def vacuum(self, threshold=0.3): ''' Force garbage collection :param float threshold (optional): The threshold is optional, and will not change the default threshold. :rtype: boolean ''' url = ("http://{master_addr}:{master_port}/" "vol/vacuum?garbageThreshold={threshold}").format( master_addr=self.master_addr, master_port=self.master_port, threshold=threshold) res = self.conn.get_data(url) if res is not None: return True return False
python
def vacuum(self, threshold=0.3): ''' Force garbage collection :param float threshold (optional): The threshold is optional, and will not change the default threshold. :rtype: boolean ''' url = ("http://{master_addr}:{master_port}/" "vol/vacuum?garbageThreshold={threshold}").format( master_addr=self.master_addr, master_port=self.master_port, threshold=threshold) res = self.conn.get_data(url) if res is not None: return True return False
[ "def", "vacuum", "(", "self", ",", "threshold", "=", "0.3", ")", ":", "url", "=", "(", "\"http://{master_addr}:{master_port}/\"", "\"vol/vacuum?garbageThreshold={threshold}\"", ")", ".", "format", "(", "master_addr", "=", "self", ".", "master_addr", ",", "master_port", "=", "self", ".", "master_port", ",", "threshold", "=", "threshold", ")", "res", "=", "self", ".", "conn", ".", "get_data", "(", "url", ")", "if", "res", "is", "not", "None", ":", "return", "True", "return", "False" ]
Force garbage collection :param float threshold (optional): The threshold is optional, and will not change the default threshold. :rtype: boolean
[ "Force", "garbage", "collection" ]
218049329885425a2b8370157fa44952e64516be
https://github.com/utek/pyseaweed/blob/218049329885425a2b8370157fa44952e64516be/pyseaweed/weed.py#L194-L211
train
utek/pyseaweed
pyseaweed/weed.py
WeedFS.version
def version(self): ''' Returns Weed-FS master version :rtype: string ''' url = "http://{master_addr}:{master_port}/dir/status".format( master_addr=self.master_addr, master_port=self.master_port) data = self.conn.get_data(url) response_data = json.loads(data) return response_data.get("Version")
python
def version(self): ''' Returns Weed-FS master version :rtype: string ''' url = "http://{master_addr}:{master_port}/dir/status".format( master_addr=self.master_addr, master_port=self.master_port) data = self.conn.get_data(url) response_data = json.loads(data) return response_data.get("Version")
[ "def", "version", "(", "self", ")", ":", "url", "=", "\"http://{master_addr}:{master_port}/dir/status\"", ".", "format", "(", "master_addr", "=", "self", ".", "master_addr", ",", "master_port", "=", "self", ".", "master_port", ")", "data", "=", "self", ".", "conn", ".", "get_data", "(", "url", ")", "response_data", "=", "json", ".", "loads", "(", "data", ")", "return", "response_data", ".", "get", "(", "\"Version\"", ")" ]
Returns Weed-FS master version :rtype: string
[ "Returns", "Weed", "-", "FS", "master", "version" ]
218049329885425a2b8370157fa44952e64516be
https://github.com/utek/pyseaweed/blob/218049329885425a2b8370157fa44952e64516be/pyseaweed/weed.py#L214-L225
train
ratt-ru/PyMORESANE
pymoresane/iuwt_convolution.py
fft_convolve
def fft_convolve(in1, in2, conv_device="cpu", conv_mode="linear", store_on_gpu=False): """ This function determines the convolution of two inputs using the FFT. Contains an implementation for both CPU and GPU. INPUTS: in1 (no default): Array containing one set of data, possibly an image. in2 (no default): Gpuarray containing the FFT of the PSF. conv_device (default = "cpu"): Parameter which allows specification of "cpu" or "gpu". conv_mode (default = "linear"): Mode specifier for the convolution - "linear" or "circular". """ # NOTE: Circular convolution assumes a periodic repetition of the input. This can cause edge effects. Linear # convolution pads the input with zeros to avoid this problem but is consequently heavier on computation and # memory. if conv_device=='gpu': if conv_mode=="linear": fft_in1 = pad_array(in1) fft_in1 = gpu_r2c_fft(fft_in1, store_on_gpu=True) fft_in2 = in2 conv_in1_in2 = fft_in1*fft_in2 conv_in1_in2 = contiguous_slice(fft_shift(gpu_c2r_ifft(conv_in1_in2, is_gpuarray=True, store_on_gpu=True))) if store_on_gpu: return conv_in1_in2 else: return conv_in1_in2.get() elif conv_mode=="circular": fft_in1 = gpu_r2c_fft(in1, store_on_gpu=True) fft_in2 = in2 conv_in1_in2 = fft_in1*fft_in2 conv_in1_in2 = fft_shift(gpu_c2r_ifft(conv_in1_in2, is_gpuarray=True, store_on_gpu=True)) if store_on_gpu: return conv_in1_in2 else: return conv_in1_in2.get() else: if conv_mode=="linear": fft_in1 = pad_array(in1) fft_in2 = in2 out1_slice = tuple(slice(0.5*sz,1.5*sz) for sz in in1.shape) return np.require(np.fft.fftshift(np.fft.irfft2(fft_in2*np.fft.rfft2(fft_in1)))[out1_slice], np.float32, 'C') elif conv_mode=="circular": return np.fft.fftshift(np.fft.irfft2(in2*np.fft.rfft2(in1)))
python
def fft_convolve(in1, in2, conv_device="cpu", conv_mode="linear", store_on_gpu=False): """ This function determines the convolution of two inputs using the FFT. Contains an implementation for both CPU and GPU. INPUTS: in1 (no default): Array containing one set of data, possibly an image. in2 (no default): Gpuarray containing the FFT of the PSF. conv_device (default = "cpu"): Parameter which allows specification of "cpu" or "gpu". conv_mode (default = "linear"): Mode specifier for the convolution - "linear" or "circular". """ # NOTE: Circular convolution assumes a periodic repetition of the input. This can cause edge effects. Linear # convolution pads the input with zeros to avoid this problem but is consequently heavier on computation and # memory. if conv_device=='gpu': if conv_mode=="linear": fft_in1 = pad_array(in1) fft_in1 = gpu_r2c_fft(fft_in1, store_on_gpu=True) fft_in2 = in2 conv_in1_in2 = fft_in1*fft_in2 conv_in1_in2 = contiguous_slice(fft_shift(gpu_c2r_ifft(conv_in1_in2, is_gpuarray=True, store_on_gpu=True))) if store_on_gpu: return conv_in1_in2 else: return conv_in1_in2.get() elif conv_mode=="circular": fft_in1 = gpu_r2c_fft(in1, store_on_gpu=True) fft_in2 = in2 conv_in1_in2 = fft_in1*fft_in2 conv_in1_in2 = fft_shift(gpu_c2r_ifft(conv_in1_in2, is_gpuarray=True, store_on_gpu=True)) if store_on_gpu: return conv_in1_in2 else: return conv_in1_in2.get() else: if conv_mode=="linear": fft_in1 = pad_array(in1) fft_in2 = in2 out1_slice = tuple(slice(0.5*sz,1.5*sz) for sz in in1.shape) return np.require(np.fft.fftshift(np.fft.irfft2(fft_in2*np.fft.rfft2(fft_in1)))[out1_slice], np.float32, 'C') elif conv_mode=="circular": return np.fft.fftshift(np.fft.irfft2(in2*np.fft.rfft2(in1)))
[ "def", "fft_convolve", "(", "in1", ",", "in2", ",", "conv_device", "=", "\"cpu\"", ",", "conv_mode", "=", "\"linear\"", ",", "store_on_gpu", "=", "False", ")", ":", "# NOTE: Circular convolution assumes a periodic repetition of the input. This can cause edge effects. Linear", "# convolution pads the input with zeros to avoid this problem but is consequently heavier on computation and", "# memory.", "if", "conv_device", "==", "'gpu'", ":", "if", "conv_mode", "==", "\"linear\"", ":", "fft_in1", "=", "pad_array", "(", "in1", ")", "fft_in1", "=", "gpu_r2c_fft", "(", "fft_in1", ",", "store_on_gpu", "=", "True", ")", "fft_in2", "=", "in2", "conv_in1_in2", "=", "fft_in1", "*", "fft_in2", "conv_in1_in2", "=", "contiguous_slice", "(", "fft_shift", "(", "gpu_c2r_ifft", "(", "conv_in1_in2", ",", "is_gpuarray", "=", "True", ",", "store_on_gpu", "=", "True", ")", ")", ")", "if", "store_on_gpu", ":", "return", "conv_in1_in2", "else", ":", "return", "conv_in1_in2", ".", "get", "(", ")", "elif", "conv_mode", "==", "\"circular\"", ":", "fft_in1", "=", "gpu_r2c_fft", "(", "in1", ",", "store_on_gpu", "=", "True", ")", "fft_in2", "=", "in2", "conv_in1_in2", "=", "fft_in1", "*", "fft_in2", "conv_in1_in2", "=", "fft_shift", "(", "gpu_c2r_ifft", "(", "conv_in1_in2", ",", "is_gpuarray", "=", "True", ",", "store_on_gpu", "=", "True", ")", ")", "if", "store_on_gpu", ":", "return", "conv_in1_in2", "else", ":", "return", "conv_in1_in2", ".", "get", "(", ")", "else", ":", "if", "conv_mode", "==", "\"linear\"", ":", "fft_in1", "=", "pad_array", "(", "in1", ")", "fft_in2", "=", "in2", "out1_slice", "=", "tuple", "(", "slice", "(", "0.5", "*", "sz", ",", "1.5", "*", "sz", ")", "for", "sz", "in", "in1", ".", "shape", ")", "return", "np", ".", "require", "(", "np", ".", "fft", ".", "fftshift", "(", "np", ".", "fft", ".", "irfft2", "(", "fft_in2", "*", "np", ".", "fft", ".", "rfft2", "(", "fft_in1", ")", ")", ")", "[", "out1_slice", "]", ",", "np", ".", "float32", ",", "'C'", ")", "elif", "conv_mode", "==", "\"circular\"", ":", "return", "np", ".", "fft", ".", "fftshift", "(", "np", ".", "fft", ".", "irfft2", "(", "in2", "*", "np", ".", "fft", ".", "rfft2", "(", "in1", ")", ")", ")" ]
This function determines the convolution of two inputs using the FFT. Contains an implementation for both CPU and GPU. INPUTS: in1 (no default): Array containing one set of data, possibly an image. in2 (no default): Gpuarray containing the FFT of the PSF. conv_device (default = "cpu"): Parameter which allows specification of "cpu" or "gpu". conv_mode (default = "linear"): Mode specifier for the convolution - "linear" or "circular".
[ "This", "function", "determines", "the", "convolution", "of", "two", "inputs", "using", "the", "FFT", ".", "Contains", "an", "implementation", "for", "both", "CPU", "and", "GPU", "." ]
b024591ad0bbb69320d08841f28a2c27f62ae1af
https://github.com/ratt-ru/PyMORESANE/blob/b024591ad0bbb69320d08841f28a2c27f62ae1af/pymoresane/iuwt_convolution.py#L18-L73
train
ratt-ru/PyMORESANE
pymoresane/iuwt_convolution.py
gpu_r2c_fft
def gpu_r2c_fft(in1, is_gpuarray=False, store_on_gpu=False): """ This function makes use of the scikits implementation of the FFT for GPUs to take the real to complex FFT. INPUTS: in1 (no default): The array on which the FFT is to be performed. is_gpuarray (default=True): Boolean specifier for whether or not input is on the gpu. store_on_gpu (default=False): Boolean specifier for whether the result is to be left on the gpu or not. OUTPUTS: gpu_out1 The gpu array containing the result. OR gpu_out1.get() The result from the gpu array. """ if is_gpuarray: gpu_in1 = in1 else: gpu_in1 = gpuarray.to_gpu_async(in1.astype(np.float32)) output_size = np.array(in1.shape) output_size[1] = 0.5*output_size[1] + 1 gpu_out1 = gpuarray.empty([output_size[0], output_size[1]], np.complex64) gpu_plan = Plan(gpu_in1.shape, np.float32, np.complex64) fft(gpu_in1, gpu_out1, gpu_plan) if store_on_gpu: return gpu_out1 else: return gpu_out1.get()
python
def gpu_r2c_fft(in1, is_gpuarray=False, store_on_gpu=False): """ This function makes use of the scikits implementation of the FFT for GPUs to take the real to complex FFT. INPUTS: in1 (no default): The array on which the FFT is to be performed. is_gpuarray (default=True): Boolean specifier for whether or not input is on the gpu. store_on_gpu (default=False): Boolean specifier for whether the result is to be left on the gpu or not. OUTPUTS: gpu_out1 The gpu array containing the result. OR gpu_out1.get() The result from the gpu array. """ if is_gpuarray: gpu_in1 = in1 else: gpu_in1 = gpuarray.to_gpu_async(in1.astype(np.float32)) output_size = np.array(in1.shape) output_size[1] = 0.5*output_size[1] + 1 gpu_out1 = gpuarray.empty([output_size[0], output_size[1]], np.complex64) gpu_plan = Plan(gpu_in1.shape, np.float32, np.complex64) fft(gpu_in1, gpu_out1, gpu_plan) if store_on_gpu: return gpu_out1 else: return gpu_out1.get()
[ "def", "gpu_r2c_fft", "(", "in1", ",", "is_gpuarray", "=", "False", ",", "store_on_gpu", "=", "False", ")", ":", "if", "is_gpuarray", ":", "gpu_in1", "=", "in1", "else", ":", "gpu_in1", "=", "gpuarray", ".", "to_gpu_async", "(", "in1", ".", "astype", "(", "np", ".", "float32", ")", ")", "output_size", "=", "np", ".", "array", "(", "in1", ".", "shape", ")", "output_size", "[", "1", "]", "=", "0.5", "*", "output_size", "[", "1", "]", "+", "1", "gpu_out1", "=", "gpuarray", ".", "empty", "(", "[", "output_size", "[", "0", "]", ",", "output_size", "[", "1", "]", "]", ",", "np", ".", "complex64", ")", "gpu_plan", "=", "Plan", "(", "gpu_in1", ".", "shape", ",", "np", ".", "float32", ",", "np", ".", "complex64", ")", "fft", "(", "gpu_in1", ",", "gpu_out1", ",", "gpu_plan", ")", "if", "store_on_gpu", ":", "return", "gpu_out1", "else", ":", "return", "gpu_out1", ".", "get", "(", ")" ]
This function makes use of the scikits implementation of the FFT for GPUs to take the real to complex FFT. INPUTS: in1 (no default): The array on which the FFT is to be performed. is_gpuarray (default=True): Boolean specifier for whether or not input is on the gpu. store_on_gpu (default=False): Boolean specifier for whether the result is to be left on the gpu or not. OUTPUTS: gpu_out1 The gpu array containing the result. OR gpu_out1.get() The result from the gpu array.
[ "This", "function", "makes", "use", "of", "the", "scikits", "implementation", "of", "the", "FFT", "for", "GPUs", "to", "take", "the", "real", "to", "complex", "FFT", "." ]
b024591ad0bbb69320d08841f28a2c27f62ae1af
https://github.com/ratt-ru/PyMORESANE/blob/b024591ad0bbb69320d08841f28a2c27f62ae1af/pymoresane/iuwt_convolution.py#L76-L106
train
ratt-ru/PyMORESANE
pymoresane/iuwt_convolution.py
gpu_c2r_ifft
def gpu_c2r_ifft(in1, is_gpuarray=False, store_on_gpu=False): """ This function makes use of the scikits implementation of the FFT for GPUs to take the complex to real IFFT. INPUTS: in1 (no default): The array on which the IFFT is to be performed. is_gpuarray (default=True): Boolean specifier for whether or not input is on the gpu. store_on_gpu (default=False): Boolean specifier for whether the result is to be left on the gpu or not. OUTPUTS: gpu_out1 The gpu array containing the result. OR gpu_out1.get() The result from the gpu array. """ if is_gpuarray: gpu_in1 = in1 else: gpu_in1 = gpuarray.to_gpu_async(in1.astype(np.complex64)) output_size = np.array(in1.shape) output_size[1] = 2*(output_size[1]-1) gpu_out1 = gpuarray.empty([output_size[0],output_size[1]], np.float32) gpu_plan = Plan(output_size, np.complex64, np.float32) ifft(gpu_in1, gpu_out1, gpu_plan) scale_fft(gpu_out1) if store_on_gpu: return gpu_out1 else: return gpu_out1.get()
python
def gpu_c2r_ifft(in1, is_gpuarray=False, store_on_gpu=False): """ This function makes use of the scikits implementation of the FFT for GPUs to take the complex to real IFFT. INPUTS: in1 (no default): The array on which the IFFT is to be performed. is_gpuarray (default=True): Boolean specifier for whether or not input is on the gpu. store_on_gpu (default=False): Boolean specifier for whether the result is to be left on the gpu or not. OUTPUTS: gpu_out1 The gpu array containing the result. OR gpu_out1.get() The result from the gpu array. """ if is_gpuarray: gpu_in1 = in1 else: gpu_in1 = gpuarray.to_gpu_async(in1.astype(np.complex64)) output_size = np.array(in1.shape) output_size[1] = 2*(output_size[1]-1) gpu_out1 = gpuarray.empty([output_size[0],output_size[1]], np.float32) gpu_plan = Plan(output_size, np.complex64, np.float32) ifft(gpu_in1, gpu_out1, gpu_plan) scale_fft(gpu_out1) if store_on_gpu: return gpu_out1 else: return gpu_out1.get()
[ "def", "gpu_c2r_ifft", "(", "in1", ",", "is_gpuarray", "=", "False", ",", "store_on_gpu", "=", "False", ")", ":", "if", "is_gpuarray", ":", "gpu_in1", "=", "in1", "else", ":", "gpu_in1", "=", "gpuarray", ".", "to_gpu_async", "(", "in1", ".", "astype", "(", "np", ".", "complex64", ")", ")", "output_size", "=", "np", ".", "array", "(", "in1", ".", "shape", ")", "output_size", "[", "1", "]", "=", "2", "*", "(", "output_size", "[", "1", "]", "-", "1", ")", "gpu_out1", "=", "gpuarray", ".", "empty", "(", "[", "output_size", "[", "0", "]", ",", "output_size", "[", "1", "]", "]", ",", "np", ".", "float32", ")", "gpu_plan", "=", "Plan", "(", "output_size", ",", "np", ".", "complex64", ",", "np", ".", "float32", ")", "ifft", "(", "gpu_in1", ",", "gpu_out1", ",", "gpu_plan", ")", "scale_fft", "(", "gpu_out1", ")", "if", "store_on_gpu", ":", "return", "gpu_out1", "else", ":", "return", "gpu_out1", ".", "get", "(", ")" ]
This function makes use of the scikits implementation of the FFT for GPUs to take the complex to real IFFT. INPUTS: in1 (no default): The array on which the IFFT is to be performed. is_gpuarray (default=True): Boolean specifier for whether or not input is on the gpu. store_on_gpu (default=False): Boolean specifier for whether the result is to be left on the gpu or not. OUTPUTS: gpu_out1 The gpu array containing the result. OR gpu_out1.get() The result from the gpu array.
[ "This", "function", "makes", "use", "of", "the", "scikits", "implementation", "of", "the", "FFT", "for", "GPUs", "to", "take", "the", "complex", "to", "real", "IFFT", "." ]
b024591ad0bbb69320d08841f28a2c27f62ae1af
https://github.com/ratt-ru/PyMORESANE/blob/b024591ad0bbb69320d08841f28a2c27f62ae1af/pymoresane/iuwt_convolution.py#L108-L139
train
ratt-ru/PyMORESANE
pymoresane/iuwt_convolution.py
pad_array
def pad_array(in1): """ Simple convenience function to pad arrays for linear convolution. INPUTS: in1 (no default): Input array which is to be padded. OUTPUTS: out1 Padded version of the input. """ padded_size = 2*np.array(in1.shape) out1 = np.zeros([padded_size[0],padded_size[1]]) out1[padded_size[0]/4:3*padded_size[0]/4,padded_size[1]/4:3*padded_size[1]/4] = in1 return out1
python
def pad_array(in1): """ Simple convenience function to pad arrays for linear convolution. INPUTS: in1 (no default): Input array which is to be padded. OUTPUTS: out1 Padded version of the input. """ padded_size = 2*np.array(in1.shape) out1 = np.zeros([padded_size[0],padded_size[1]]) out1[padded_size[0]/4:3*padded_size[0]/4,padded_size[1]/4:3*padded_size[1]/4] = in1 return out1
[ "def", "pad_array", "(", "in1", ")", ":", "padded_size", "=", "2", "*", "np", ".", "array", "(", "in1", ".", "shape", ")", "out1", "=", "np", ".", "zeros", "(", "[", "padded_size", "[", "0", "]", ",", "padded_size", "[", "1", "]", "]", ")", "out1", "[", "padded_size", "[", "0", "]", "/", "4", ":", "3", "*", "padded_size", "[", "0", "]", "/", "4", ",", "padded_size", "[", "1", "]", "/", "4", ":", "3", "*", "padded_size", "[", "1", "]", "/", "4", "]", "=", "in1", "return", "out1" ]
Simple convenience function to pad arrays for linear convolution. INPUTS: in1 (no default): Input array which is to be padded. OUTPUTS: out1 Padded version of the input.
[ "Simple", "convenience", "function", "to", "pad", "arrays", "for", "linear", "convolution", "." ]
b024591ad0bbb69320d08841f28a2c27f62ae1af
https://github.com/ratt-ru/PyMORESANE/blob/b024591ad0bbb69320d08841f28a2c27f62ae1af/pymoresane/iuwt_convolution.py#L142-L158
train
brndnmtthws/dragon-rest
dragon_rest/dragons.py
DragonAPI.is_dragon
def is_dragon(host, timeout=1): """ Check if host is a dragon. Check if the specified host is a dragon based on simple heuristic. The code simply checks if particular strings are in the index page. It should work for DragonMint or Innosilicon branded miners. """ try: r = requests.get('http://{}/'.format(host), timeout=timeout) if r.status_code == 200: if '<title>DragonMint</title>' in r.text or \ '<title>AsicMiner</title>' in r.text: return True except requests.exceptions.RequestException: pass return False
python
def is_dragon(host, timeout=1): """ Check if host is a dragon. Check if the specified host is a dragon based on simple heuristic. The code simply checks if particular strings are in the index page. It should work for DragonMint or Innosilicon branded miners. """ try: r = requests.get('http://{}/'.format(host), timeout=timeout) if r.status_code == 200: if '<title>DragonMint</title>' in r.text or \ '<title>AsicMiner</title>' in r.text: return True except requests.exceptions.RequestException: pass return False
[ "def", "is_dragon", "(", "host", ",", "timeout", "=", "1", ")", ":", "try", ":", "r", "=", "requests", ".", "get", "(", "'http://{}/'", ".", "format", "(", "host", ")", ",", "timeout", "=", "timeout", ")", "if", "r", ".", "status_code", "==", "200", ":", "if", "'<title>DragonMint</title>'", "in", "r", ".", "text", "or", "'<title>AsicMiner</title>'", "in", "r", ".", "text", ":", "return", "True", "except", "requests", ".", "exceptions", ".", "RequestException", ":", "pass", "return", "False" ]
Check if host is a dragon. Check if the specified host is a dragon based on simple heuristic. The code simply checks if particular strings are in the index page. It should work for DragonMint or Innosilicon branded miners.
[ "Check", "if", "host", "is", "a", "dragon", "." ]
10ea09a6203c0cbfeeeb854702764bd778769887
https://github.com/brndnmtthws/dragon-rest/blob/10ea09a6203c0cbfeeeb854702764bd778769887/dragon_rest/dragons.py#L49-L65
train
brndnmtthws/dragon-rest
dragon_rest/dragons.py
DragonAPI.updatePools
def updatePools(self, pool1, username1, password1, pool2=None, username2=None, password2=None, pool3=None, username3=None, password3=None): """Change the pools of the miner. This call will restart cgminer.""" return self.__post('/api/updatePools', data={ 'Pool1': pool1, 'UserName1': username1, 'Password1': password1, 'Pool2': pool2, 'UserName2': username2, 'Password2': password2, 'Pool3': pool3, 'UserName3': username3, 'Password3': password3, })
python
def updatePools(self, pool1, username1, password1, pool2=None, username2=None, password2=None, pool3=None, username3=None, password3=None): """Change the pools of the miner. This call will restart cgminer.""" return self.__post('/api/updatePools', data={ 'Pool1': pool1, 'UserName1': username1, 'Password1': password1, 'Pool2': pool2, 'UserName2': username2, 'Password2': password2, 'Pool3': pool3, 'UserName3': username3, 'Password3': password3, })
[ "def", "updatePools", "(", "self", ",", "pool1", ",", "username1", ",", "password1", ",", "pool2", "=", "None", ",", "username2", "=", "None", ",", "password2", "=", "None", ",", "pool3", "=", "None", ",", "username3", "=", "None", ",", "password3", "=", "None", ")", ":", "return", "self", ".", "__post", "(", "'/api/updatePools'", ",", "data", "=", "{", "'Pool1'", ":", "pool1", ",", "'UserName1'", ":", "username1", ",", "'Password1'", ":", "password1", ",", "'Pool2'", ":", "pool2", ",", "'UserName2'", ":", "username2", ",", "'Password2'", ":", "password2", ",", "'Pool3'", ":", "pool3", ",", "'UserName3'", ":", "username3", ",", "'Password3'", ":", "password3", ",", "}", ")" ]
Change the pools of the miner. This call will restart cgminer.
[ "Change", "the", "pools", "of", "the", "miner", ".", "This", "call", "will", "restart", "cgminer", "." ]
10ea09a6203c0cbfeeeb854702764bd778769887
https://github.com/brndnmtthws/dragon-rest/blob/10ea09a6203c0cbfeeeb854702764bd778769887/dragon_rest/dragons.py#L148-L170
train
brndnmtthws/dragon-rest
dragon_rest/dragons.py
DragonAPI.updatePassword
def updatePassword(self, user, currentPassword, newPassword): """Change the password of a user.""" return self.__post('/api/updatePassword', data={ 'user': user, 'currentPassword': currentPassword, 'newPassword': newPassword })
python
def updatePassword(self, user, currentPassword, newPassword): """Change the password of a user.""" return self.__post('/api/updatePassword', data={ 'user': user, 'currentPassword': currentPassword, 'newPassword': newPassword })
[ "def", "updatePassword", "(", "self", ",", "user", ",", "currentPassword", ",", "newPassword", ")", ":", "return", "self", ".", "__post", "(", "'/api/updatePassword'", ",", "data", "=", "{", "'user'", ":", "user", ",", "'currentPassword'", ":", "currentPassword", ",", "'newPassword'", ":", "newPassword", "}", ")" ]
Change the password of a user.
[ "Change", "the", "password", "of", "a", "user", "." ]
10ea09a6203c0cbfeeeb854702764bd778769887
https://github.com/brndnmtthws/dragon-rest/blob/10ea09a6203c0cbfeeeb854702764bd778769887/dragon_rest/dragons.py#L172-L182
train
brndnmtthws/dragon-rest
dragon_rest/dragons.py
DragonAPI.updateNetwork
def updateNetwork(self, dhcp='dhcp', ipaddress=None, netmask=None, gateway=None, dns=None): """Change the current network settings.""" return self.__post('/api/updateNetwork', data={ 'dhcp': dhcp, 'ipaddress': ipaddress, 'netmask': netmask, 'gateway': gateway, 'dns': json.dumps(dns) })
python
def updateNetwork(self, dhcp='dhcp', ipaddress=None, netmask=None, gateway=None, dns=None): """Change the current network settings.""" return self.__post('/api/updateNetwork', data={ 'dhcp': dhcp, 'ipaddress': ipaddress, 'netmask': netmask, 'gateway': gateway, 'dns': json.dumps(dns) })
[ "def", "updateNetwork", "(", "self", ",", "dhcp", "=", "'dhcp'", ",", "ipaddress", "=", "None", ",", "netmask", "=", "None", ",", "gateway", "=", "None", ",", "dns", "=", "None", ")", ":", "return", "self", ".", "__post", "(", "'/api/updateNetwork'", ",", "data", "=", "{", "'dhcp'", ":", "dhcp", ",", "'ipaddress'", ":", "ipaddress", ",", "'netmask'", ":", "netmask", ",", "'gateway'", ":", "gateway", ",", "'dns'", ":", "json", ".", "dumps", "(", "dns", ")", "}", ")" ]
Change the current network settings.
[ "Change", "the", "current", "network", "settings", "." ]
10ea09a6203c0cbfeeeb854702764bd778769887
https://github.com/brndnmtthws/dragon-rest/blob/10ea09a6203c0cbfeeeb854702764bd778769887/dragon_rest/dragons.py#L188-L202
train
brndnmtthws/dragon-rest
dragon_rest/dragons.py
DragonAPI.upgradeUpload
def upgradeUpload(self, file): """Upgrade the firmware of the miner.""" files = {'upfile': open(file, 'rb')} return self.__post_files('/upgrade/upload', files=files)
python
def upgradeUpload(self, file): """Upgrade the firmware of the miner.""" files = {'upfile': open(file, 'rb')} return self.__post_files('/upgrade/upload', files=files)
[ "def", "upgradeUpload", "(", "self", ",", "file", ")", ":", "files", "=", "{", "'upfile'", ":", "open", "(", "file", ",", "'rb'", ")", "}", "return", "self", ".", "__post_files", "(", "'/upgrade/upload'", ",", "files", "=", "files", ")" ]
Upgrade the firmware of the miner.
[ "Upgrade", "the", "firmware", "of", "the", "miner", "." ]
10ea09a6203c0cbfeeeb854702764bd778769887
https://github.com/brndnmtthws/dragon-rest/blob/10ea09a6203c0cbfeeeb854702764bd778769887/dragon_rest/dragons.py#L237-L241
train
tuomas2/automate
src/automate/statusobject.py
StatusObject.is_program
def is_program(self): """ A property which can be used to check if StatusObject uses program features or not. """ from automate.callables import Empty return not (isinstance(self.on_activate, Empty) and isinstance(self.on_deactivate, Empty) and isinstance(self.on_update, Empty))
python
def is_program(self): """ A property which can be used to check if StatusObject uses program features or not. """ from automate.callables import Empty return not (isinstance(self.on_activate, Empty) and isinstance(self.on_deactivate, Empty) and isinstance(self.on_update, Empty))
[ "def", "is_program", "(", "self", ")", ":", "from", "automate", ".", "callables", "import", "Empty", "return", "not", "(", "isinstance", "(", "self", ".", "on_activate", ",", "Empty", ")", "and", "isinstance", "(", "self", ".", "on_deactivate", ",", "Empty", ")", "and", "isinstance", "(", "self", ".", "on_update", ",", "Empty", ")", ")" ]
A property which can be used to check if StatusObject uses program features or not.
[ "A", "property", "which", "can", "be", "used", "to", "check", "if", "StatusObject", "uses", "program", "features", "or", "not", "." ]
d8a8cd03cd0da047e033a2d305f3f260f8c4e017
https://github.com/tuomas2/automate/blob/d8a8cd03cd0da047e033a2d305f3f260f8c4e017/src/automate/statusobject.py#L208-L215
train
tuomas2/automate
src/automate/statusobject.py
StatusObject.get_as_datadict
def get_as_datadict(self): """ Get data of this object as a data dictionary. Used by websocket service. """ d = super().get_as_datadict() d.update(dict(status=self.status, data_type=self.data_type, editable=self.editable)) return d
python
def get_as_datadict(self): """ Get data of this object as a data dictionary. Used by websocket service. """ d = super().get_as_datadict() d.update(dict(status=self.status, data_type=self.data_type, editable=self.editable)) return d
[ "def", "get_as_datadict", "(", "self", ")", ":", "d", "=", "super", "(", ")", ".", "get_as_datadict", "(", ")", "d", ".", "update", "(", "dict", "(", "status", "=", "self", ".", "status", ",", "data_type", "=", "self", ".", "data_type", ",", "editable", "=", "self", ".", "editable", ")", ")", "return", "d" ]
Get data of this object as a data dictionary. Used by websocket service.
[ "Get", "data", "of", "this", "object", "as", "a", "data", "dictionary", ".", "Used", "by", "websocket", "service", "." ]
d8a8cd03cd0da047e033a2d305f3f260f8c4e017
https://github.com/tuomas2/automate/blob/d8a8cd03cd0da047e033a2d305f3f260f8c4e017/src/automate/statusobject.py#L238-L244
train
tuomas2/automate
src/automate/statusobject.py
StatusObject._do_change_status
def _do_change_status(self, status, force=False): """ This function is called by - set_status - _update_program_stack if active program is being changed - thia may be launched by sensor status change. status lock is necessary because these happen from different threads. This does not directly change status, but adds change request to queue. """ self.system.worker_thread.put(DummyStatusWorkerTask(self._request_status_change_in_queue, status, force=force))
python
def _do_change_status(self, status, force=False): """ This function is called by - set_status - _update_program_stack if active program is being changed - thia may be launched by sensor status change. status lock is necessary because these happen from different threads. This does not directly change status, but adds change request to queue. """ self.system.worker_thread.put(DummyStatusWorkerTask(self._request_status_change_in_queue, status, force=force))
[ "def", "_do_change_status", "(", "self", ",", "status", ",", "force", "=", "False", ")", ":", "self", ".", "system", ".", "worker_thread", ".", "put", "(", "DummyStatusWorkerTask", "(", "self", ".", "_request_status_change_in_queue", ",", "status", ",", "force", "=", "force", ")", ")" ]
This function is called by - set_status - _update_program_stack if active program is being changed - thia may be launched by sensor status change. status lock is necessary because these happen from different threads. This does not directly change status, but adds change request to queue.
[ "This", "function", "is", "called", "by", "-", "set_status", "-", "_update_program_stack", "if", "active", "program", "is", "being", "changed", "-", "thia", "may", "be", "launched", "by", "sensor", "status", "change", ".", "status", "lock", "is", "necessary", "because", "these", "happen", "from", "different", "threads", "." ]
d8a8cd03cd0da047e033a2d305f3f260f8c4e017
https://github.com/tuomas2/automate/blob/d8a8cd03cd0da047e033a2d305f3f260f8c4e017/src/automate/statusobject.py#L354-L366
train
tuomas2/automate
src/automate/statusobject.py
AbstractActuator.activate_program
def activate_program(self, program): """ Called by program which desires to manipulate this actuator, when it is activated. """ self.logger.debug("activate_program %s", program) if program in self.program_stack: return with self._program_lock: self.logger.debug("activate_program got through %s", program) self.program_stack.append(program) self._update_program_stack()
python
def activate_program(self, program): """ Called by program which desires to manipulate this actuator, when it is activated. """ self.logger.debug("activate_program %s", program) if program in self.program_stack: return with self._program_lock: self.logger.debug("activate_program got through %s", program) self.program_stack.append(program) self._update_program_stack()
[ "def", "activate_program", "(", "self", ",", "program", ")", ":", "self", ".", "logger", ".", "debug", "(", "\"activate_program %s\"", ",", "program", ")", "if", "program", "in", "self", ".", "program_stack", ":", "return", "with", "self", ".", "_program_lock", ":", "self", ".", "logger", ".", "debug", "(", "\"activate_program got through %s\"", ",", "program", ")", "self", ".", "program_stack", ".", "append", "(", "program", ")", "self", ".", "_update_program_stack", "(", ")" ]
Called by program which desires to manipulate this actuator, when it is activated.
[ "Called", "by", "program", "which", "desires", "to", "manipulate", "this", "actuator", "when", "it", "is", "activated", "." ]
d8a8cd03cd0da047e033a2d305f3f260f8c4e017
https://github.com/tuomas2/automate/blob/d8a8cd03cd0da047e033a2d305f3f260f8c4e017/src/automate/statusobject.py#L578-L589
train
tuomas2/automate
src/automate/statusobject.py
AbstractActuator.deactivate_program
def deactivate_program(self, program): """ Called by program, when it is deactivated. """ self.logger.debug("deactivate_program %s", program) with self._program_lock: self.logger.debug("deactivate_program got through %s", program) if program not in self.program_stack: import ipdb ipdb.set_trace() self.program_stack.remove(program) if program in self.program_status: del self.program_status[program] self._update_program_stack()
python
def deactivate_program(self, program): """ Called by program, when it is deactivated. """ self.logger.debug("deactivate_program %s", program) with self._program_lock: self.logger.debug("deactivate_program got through %s", program) if program not in self.program_stack: import ipdb ipdb.set_trace() self.program_stack.remove(program) if program in self.program_status: del self.program_status[program] self._update_program_stack()
[ "def", "deactivate_program", "(", "self", ",", "program", ")", ":", "self", ".", "logger", ".", "debug", "(", "\"deactivate_program %s\"", ",", "program", ")", "with", "self", ".", "_program_lock", ":", "self", ".", "logger", ".", "debug", "(", "\"deactivate_program got through %s\"", ",", "program", ")", "if", "program", "not", "in", "self", ".", "program_stack", ":", "import", "ipdb", "ipdb", ".", "set_trace", "(", ")", "self", ".", "program_stack", ".", "remove", "(", "program", ")", "if", "program", "in", "self", ".", "program_status", ":", "del", "self", ".", "program_status", "[", "program", "]", "self", ".", "_update_program_stack", "(", ")" ]
Called by program, when it is deactivated.
[ "Called", "by", "program", "when", "it", "is", "deactivated", "." ]
d8a8cd03cd0da047e033a2d305f3f260f8c4e017
https://github.com/tuomas2/automate/blob/d8a8cd03cd0da047e033a2d305f3f260f8c4e017/src/automate/statusobject.py#L591-L605
train
praekeltfoundation/seaworthy
seaworthy/stream/logs.py
stream_logs
def stream_logs(container, timeout=10.0, **logs_kwargs): """ Stream logs from a Docker container within a timeout. :param ~docker.models.containers.Container container: Container who's log lines to stream. :param timeout: Timeout value in seconds. :param logs_kwargs: Additional keyword arguments to pass to ``container.logs()``. For example, the ``stdout`` and ``stderr`` boolean arguments can be used to determine whether to stream stdout or stderr or both (the default). :raises TimeoutError: When the timeout value is reached before the logs have completed. """ stream = container.logs(stream=True, **logs_kwargs) return stream_timeout( stream, timeout, 'Timeout waiting for container logs.')
python
def stream_logs(container, timeout=10.0, **logs_kwargs): """ Stream logs from a Docker container within a timeout. :param ~docker.models.containers.Container container: Container who's log lines to stream. :param timeout: Timeout value in seconds. :param logs_kwargs: Additional keyword arguments to pass to ``container.logs()``. For example, the ``stdout`` and ``stderr`` boolean arguments can be used to determine whether to stream stdout or stderr or both (the default). :raises TimeoutError: When the timeout value is reached before the logs have completed. """ stream = container.logs(stream=True, **logs_kwargs) return stream_timeout( stream, timeout, 'Timeout waiting for container logs.')
[ "def", "stream_logs", "(", "container", ",", "timeout", "=", "10.0", ",", "*", "*", "logs_kwargs", ")", ":", "stream", "=", "container", ".", "logs", "(", "stream", "=", "True", ",", "*", "*", "logs_kwargs", ")", "return", "stream_timeout", "(", "stream", ",", "timeout", ",", "'Timeout waiting for container logs.'", ")" ]
Stream logs from a Docker container within a timeout. :param ~docker.models.containers.Container container: Container who's log lines to stream. :param timeout: Timeout value in seconds. :param logs_kwargs: Additional keyword arguments to pass to ``container.logs()``. For example, the ``stdout`` and ``stderr`` boolean arguments can be used to determine whether to stream stdout or stderr or both (the default). :raises TimeoutError: When the timeout value is reached before the logs have completed.
[ "Stream", "logs", "from", "a", "Docker", "container", "within", "a", "timeout", "." ]
6f10a19b45d4ea1dc3bd0553cc4d0438696c079c
https://github.com/praekeltfoundation/seaworthy/blob/6f10a19b45d4ea1dc3bd0553cc4d0438696c079c/seaworthy/stream/logs.py#L8-L26
train
praekeltfoundation/seaworthy
seaworthy/helpers.py
fetch_image
def fetch_image(client, name): """ Fetch an image if it isn't already present. This works like ``docker pull`` and will pull the tag ``latest`` if no tag is specified in the image name. """ try: image = client.images.get(name) except docker.errors.ImageNotFound: name, tag = _parse_image_tag(name) tag = 'latest' if tag is None else tag log.info("Pulling tag '{}' for image '{}'...".format(tag, name)) image = client.images.pull(name, tag=tag) log.debug("Found image '{}' for tag '{}'".format(image.id, name)) return image
python
def fetch_image(client, name): """ Fetch an image if it isn't already present. This works like ``docker pull`` and will pull the tag ``latest`` if no tag is specified in the image name. """ try: image = client.images.get(name) except docker.errors.ImageNotFound: name, tag = _parse_image_tag(name) tag = 'latest' if tag is None else tag log.info("Pulling tag '{}' for image '{}'...".format(tag, name)) image = client.images.pull(name, tag=tag) log.debug("Found image '{}' for tag '{}'".format(image.id, name)) return image
[ "def", "fetch_image", "(", "client", ",", "name", ")", ":", "try", ":", "image", "=", "client", ".", "images", ".", "get", "(", "name", ")", "except", "docker", ".", "errors", ".", "ImageNotFound", ":", "name", ",", "tag", "=", "_parse_image_tag", "(", "name", ")", "tag", "=", "'latest'", "if", "tag", "is", "None", "else", "tag", "log", ".", "info", "(", "\"Pulling tag '{}' for image '{}'...\"", ".", "format", "(", "tag", ",", "name", ")", ")", "image", "=", "client", ".", "images", ".", "pull", "(", "name", ",", "tag", "=", "tag", ")", "log", ".", "debug", "(", "\"Found image '{}' for tag '{}'\"", ".", "format", "(", "image", ".", "id", ",", "name", ")", ")", "return", "image" ]
Fetch an image if it isn't already present. This works like ``docker pull`` and will pull the tag ``latest`` if no tag is specified in the image name.
[ "Fetch", "an", "image", "if", "it", "isn", "t", "already", "present", "." ]
6f10a19b45d4ea1dc3bd0553cc4d0438696c079c
https://github.com/praekeltfoundation/seaworthy/blob/6f10a19b45d4ea1dc3bd0553cc4d0438696c079c/seaworthy/helpers.py#L27-L44
train
praekeltfoundation/seaworthy
seaworthy/helpers.py
_HelperBase._get_id_and_model
def _get_id_and_model(self, id_or_model): """ Get both the model and ID of an object that could be an ID or a model. :param id_or_model: The object that could be an ID string or a model object. :param model_collection: The collection to which the model belongs. """ if isinstance(id_or_model, self.collection.model): model = id_or_model elif isinstance(id_or_model, str): # Assume we have an ID string model = self.collection.get(id_or_model) else: raise TypeError('Unexpected type {}, expected {} or {}'.format( type(id_or_model), str, self.collection.model)) return model.id, model
python
def _get_id_and_model(self, id_or_model): """ Get both the model and ID of an object that could be an ID or a model. :param id_or_model: The object that could be an ID string or a model object. :param model_collection: The collection to which the model belongs. """ if isinstance(id_or_model, self.collection.model): model = id_or_model elif isinstance(id_or_model, str): # Assume we have an ID string model = self.collection.get(id_or_model) else: raise TypeError('Unexpected type {}, expected {} or {}'.format( type(id_or_model), str, self.collection.model)) return model.id, model
[ "def", "_get_id_and_model", "(", "self", ",", "id_or_model", ")", ":", "if", "isinstance", "(", "id_or_model", ",", "self", ".", "collection", ".", "model", ")", ":", "model", "=", "id_or_model", "elif", "isinstance", "(", "id_or_model", ",", "str", ")", ":", "# Assume we have an ID string", "model", "=", "self", ".", "collection", ".", "get", "(", "id_or_model", ")", "else", ":", "raise", "TypeError", "(", "'Unexpected type {}, expected {} or {}'", ".", "format", "(", "type", "(", "id_or_model", ")", ",", "str", ",", "self", ".", "collection", ".", "model", ")", ")", "return", "model", ".", "id", ",", "model" ]
Get both the model and ID of an object that could be an ID or a model. :param id_or_model: The object that could be an ID string or a model object. :param model_collection: The collection to which the model belongs.
[ "Get", "both", "the", "model", "and", "ID", "of", "an", "object", "that", "could", "be", "an", "ID", "or", "a", "model", "." ]
6f10a19b45d4ea1dc3bd0553cc4d0438696c079c
https://github.com/praekeltfoundation/seaworthy/blob/6f10a19b45d4ea1dc3bd0553cc4d0438696c079c/seaworthy/helpers.py#L82-L100
train
praekeltfoundation/seaworthy
seaworthy/helpers.py
_HelperBase.create
def create(self, name, *args, **kwargs): """ Create an instance of this resource type. """ resource_name = self._resource_name(name) log.info( "Creating {} '{}'...".format(self._model_name, resource_name)) resource = self.collection.create(*args, name=resource_name, **kwargs) self._ids.add(resource.id) return resource
python
def create(self, name, *args, **kwargs): """ Create an instance of this resource type. """ resource_name = self._resource_name(name) log.info( "Creating {} '{}'...".format(self._model_name, resource_name)) resource = self.collection.create(*args, name=resource_name, **kwargs) self._ids.add(resource.id) return resource
[ "def", "create", "(", "self", ",", "name", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "resource_name", "=", "self", ".", "_resource_name", "(", "name", ")", "log", ".", "info", "(", "\"Creating {} '{}'...\"", ".", "format", "(", "self", ".", "_model_name", ",", "resource_name", ")", ")", "resource", "=", "self", ".", "collection", ".", "create", "(", "*", "args", ",", "name", "=", "resource_name", ",", "*", "*", "kwargs", ")", "self", ".", "_ids", ".", "add", "(", "resource", ".", "id", ")", "return", "resource" ]
Create an instance of this resource type.
[ "Create", "an", "instance", "of", "this", "resource", "type", "." ]
6f10a19b45d4ea1dc3bd0553cc4d0438696c079c
https://github.com/praekeltfoundation/seaworthy/blob/6f10a19b45d4ea1dc3bd0553cc4d0438696c079c/seaworthy/helpers.py#L102-L111
train
praekeltfoundation/seaworthy
seaworthy/helpers.py
_HelperBase.remove
def remove(self, resource, **kwargs): """ Remove an instance of this resource type. """ log.info( "Removing {} '{}'...".format(self._model_name, resource.name)) resource.remove(**kwargs) self._ids.remove(resource.id)
python
def remove(self, resource, **kwargs): """ Remove an instance of this resource type. """ log.info( "Removing {} '{}'...".format(self._model_name, resource.name)) resource.remove(**kwargs) self._ids.remove(resource.id)
[ "def", "remove", "(", "self", ",", "resource", ",", "*", "*", "kwargs", ")", ":", "log", ".", "info", "(", "\"Removing {} '{}'...\"", ".", "format", "(", "self", ".", "_model_name", ",", "resource", ".", "name", ")", ")", "resource", ".", "remove", "(", "*", "*", "kwargs", ")", "self", ".", "_ids", ".", "remove", "(", "resource", ".", "id", ")" ]
Remove an instance of this resource type.
[ "Remove", "an", "instance", "of", "this", "resource", "type", "." ]
6f10a19b45d4ea1dc3bd0553cc4d0438696c079c
https://github.com/praekeltfoundation/seaworthy/blob/6f10a19b45d4ea1dc3bd0553cc4d0438696c079c/seaworthy/helpers.py#L113-L120
train
praekeltfoundation/seaworthy
seaworthy/helpers.py
ContainerHelper.remove
def remove(self, container, force=True, volumes=True): """ Remove a container. :param container: The container to remove. :param force: Whether to force the removal of the container, even if it is running. Note that this defaults to True, unlike the Docker default. :param volumes: Whether to remove any volumes that were created implicitly with this container, i.e. any volumes that were created due to ``VOLUME`` directives in the Dockerfile. External volumes that were manually created will not be removed. Note that this defaults to True, unlike the Docker default (where the equivalent parameter, ``v``, defaults to False). """ super().remove(container, force=force, v=volumes)
python
def remove(self, container, force=True, volumes=True): """ Remove a container. :param container: The container to remove. :param force: Whether to force the removal of the container, even if it is running. Note that this defaults to True, unlike the Docker default. :param volumes: Whether to remove any volumes that were created implicitly with this container, i.e. any volumes that were created due to ``VOLUME`` directives in the Dockerfile. External volumes that were manually created will not be removed. Note that this defaults to True, unlike the Docker default (where the equivalent parameter, ``v``, defaults to False). """ super().remove(container, force=force, v=volumes)
[ "def", "remove", "(", "self", ",", "container", ",", "force", "=", "True", ",", "volumes", "=", "True", ")", ":", "super", "(", ")", ".", "remove", "(", "container", ",", "force", "=", "force", ",", "v", "=", "volumes", ")" ]
Remove a container. :param container: The container to remove. :param force: Whether to force the removal of the container, even if it is running. Note that this defaults to True, unlike the Docker default. :param volumes: Whether to remove any volumes that were created implicitly with this container, i.e. any volumes that were created due to ``VOLUME`` directives in the Dockerfile. External volumes that were manually created will not be removed. Note that this defaults to True, unlike the Docker default (where the equivalent parameter, ``v``, defaults to False).
[ "Remove", "a", "container", "." ]
6f10a19b45d4ea1dc3bd0553cc4d0438696c079c
https://github.com/praekeltfoundation/seaworthy/blob/6f10a19b45d4ea1dc3bd0553cc4d0438696c079c/seaworthy/helpers.py#L266-L283
train
praekeltfoundation/seaworthy
seaworthy/helpers.py
NetworkHelper.get_default
def get_default(self, create=True): """ Get the default bridge network that containers are connected to if no other network options are specified. :param create: Whether or not to create the network if it doesn't already exist. """ if self._default_network is None and create: log.debug("Creating default network...") self._default_network = self.create('default', driver='bridge') return self._default_network
python
def get_default(self, create=True): """ Get the default bridge network that containers are connected to if no other network options are specified. :param create: Whether or not to create the network if it doesn't already exist. """ if self._default_network is None and create: log.debug("Creating default network...") self._default_network = self.create('default', driver='bridge') return self._default_network
[ "def", "get_default", "(", "self", ",", "create", "=", "True", ")", ":", "if", "self", ".", "_default_network", "is", "None", "and", "create", ":", "log", ".", "debug", "(", "\"Creating default network...\"", ")", "self", ".", "_default_network", "=", "self", ".", "create", "(", "'default'", ",", "driver", "=", "'bridge'", ")", "return", "self", ".", "_default_network" ]
Get the default bridge network that containers are connected to if no other network options are specified. :param create: Whether or not to create the network if it doesn't already exist.
[ "Get", "the", "default", "bridge", "network", "that", "containers", "are", "connected", "to", "if", "no", "other", "network", "options", "are", "specified", "." ]
6f10a19b45d4ea1dc3bd0553cc4d0438696c079c
https://github.com/praekeltfoundation/seaworthy/blob/6f10a19b45d4ea1dc3bd0553cc4d0438696c079c/seaworthy/helpers.py#L326-L338
train
praekeltfoundation/seaworthy
seaworthy/helpers.py
DockerHelper._helper_for_model
def _helper_for_model(self, model_type): """ Get the helper for a given type of Docker model. For use by resource definitions. """ if model_type is models.containers.Container: return self.containers if model_type is models.images.Image: return self.images if model_type is models.networks.Network: return self.networks if model_type is models.volumes.Volume: return self.volumes raise ValueError('Unknown model type {}'.format(model_type))
python
def _helper_for_model(self, model_type): """ Get the helper for a given type of Docker model. For use by resource definitions. """ if model_type is models.containers.Container: return self.containers if model_type is models.images.Image: return self.images if model_type is models.networks.Network: return self.networks if model_type is models.volumes.Volume: return self.volumes raise ValueError('Unknown model type {}'.format(model_type))
[ "def", "_helper_for_model", "(", "self", ",", "model_type", ")", ":", "if", "model_type", "is", "models", ".", "containers", ".", "Container", ":", "return", "self", ".", "containers", "if", "model_type", "is", "models", ".", "images", ".", "Image", ":", "return", "self", ".", "images", "if", "model_type", "is", "models", ".", "networks", ".", "Network", ":", "return", "self", ".", "networks", "if", "model_type", "is", "models", ".", "volumes", ".", "Volume", ":", "return", "self", ".", "volumes", "raise", "ValueError", "(", "'Unknown model type {}'", ".", "format", "(", "model_type", ")", ")" ]
Get the helper for a given type of Docker model. For use by resource definitions.
[ "Get", "the", "helper", "for", "a", "given", "type", "of", "Docker", "model", ".", "For", "use", "by", "resource", "definitions", "." ]
6f10a19b45d4ea1dc3bd0553cc4d0438696c079c
https://github.com/praekeltfoundation/seaworthy/blob/6f10a19b45d4ea1dc3bd0553cc4d0438696c079c/seaworthy/helpers.py#L398-L412
train
praekeltfoundation/seaworthy
seaworthy/helpers.py
DockerHelper.teardown
def teardown(self): """ Clean up all resources when we're done with them. """ self.containers._teardown() self.networks._teardown() self.volumes._teardown() # We need to close the underlying APIClient explicitly to avoid # ResourceWarnings from unclosed HTTP connections. self._client.api.close()
python
def teardown(self): """ Clean up all resources when we're done with them. """ self.containers._teardown() self.networks._teardown() self.volumes._teardown() # We need to close the underlying APIClient explicitly to avoid # ResourceWarnings from unclosed HTTP connections. self._client.api.close()
[ "def", "teardown", "(", "self", ")", ":", "self", ".", "containers", ".", "_teardown", "(", ")", "self", ".", "networks", ".", "_teardown", "(", ")", "self", ".", "volumes", ".", "_teardown", "(", ")", "# We need to close the underlying APIClient explicitly to avoid", "# ResourceWarnings from unclosed HTTP connections.", "self", ".", "_client", ".", "api", ".", "close", "(", ")" ]
Clean up all resources when we're done with them.
[ "Clean", "up", "all", "resources", "when", "we", "re", "done", "with", "them", "." ]
6f10a19b45d4ea1dc3bd0553cc4d0438696c079c
https://github.com/praekeltfoundation/seaworthy/blob/6f10a19b45d4ea1dc3bd0553cc4d0438696c079c/seaworthy/helpers.py#L414-L424
train
praekeltfoundation/seaworthy
seaworthy/containers/redis.py
RedisContainer.exec_redis_cli
def exec_redis_cli(self, command, args=[], db=0, redis_cli_opts=[]): """ Execute a ``redis-cli`` command inside a running container. :param command: the command to run :param args: a list of args for the command :param db: the db number to query (default ``0``) :param redis_cli_opts: a list of extra options to pass to ``redis-cli`` :returns: a tuple of the command exit code and output """ cli_opts = ['-n', str(db)] + redis_cli_opts cmd = ['redis-cli'] + cli_opts + [command] + [str(a) for a in args] return self.inner().exec_run(cmd)
python
def exec_redis_cli(self, command, args=[], db=0, redis_cli_opts=[]): """ Execute a ``redis-cli`` command inside a running container. :param command: the command to run :param args: a list of args for the command :param db: the db number to query (default ``0``) :param redis_cli_opts: a list of extra options to pass to ``redis-cli`` :returns: a tuple of the command exit code and output """ cli_opts = ['-n', str(db)] + redis_cli_opts cmd = ['redis-cli'] + cli_opts + [command] + [str(a) for a in args] return self.inner().exec_run(cmd)
[ "def", "exec_redis_cli", "(", "self", ",", "command", ",", "args", "=", "[", "]", ",", "db", "=", "0", ",", "redis_cli_opts", "=", "[", "]", ")", ":", "cli_opts", "=", "[", "'-n'", ",", "str", "(", "db", ")", "]", "+", "redis_cli_opts", "cmd", "=", "[", "'redis-cli'", "]", "+", "cli_opts", "+", "[", "command", "]", "+", "[", "str", "(", "a", ")", "for", "a", "in", "args", "]", "return", "self", ".", "inner", "(", ")", ".", "exec_run", "(", "cmd", ")" ]
Execute a ``redis-cli`` command inside a running container. :param command: the command to run :param args: a list of args for the command :param db: the db number to query (default ``0``) :param redis_cli_opts: a list of extra options to pass to ``redis-cli`` :returns: a tuple of the command exit code and output
[ "Execute", "a", "redis", "-", "cli", "command", "inside", "a", "running", "container", "." ]
6f10a19b45d4ea1dc3bd0553cc4d0438696c079c
https://github.com/praekeltfoundation/seaworthy/blob/6f10a19b45d4ea1dc3bd0553cc4d0438696c079c/seaworthy/containers/redis.py#L40-L52
train
praekeltfoundation/seaworthy
seaworthy/containers/redis.py
RedisContainer.list_keys
def list_keys(self, pattern='*', db=0): """ Run the ``KEYS`` command and return the list of matching keys. :param pattern: the pattern to filter keys by (default ``*``) :param db: the db number to query (default ``0``) """ lines = output_lines(self.exec_redis_cli('KEYS', [pattern], db=db)) return [] if lines == [''] else lines
python
def list_keys(self, pattern='*', db=0): """ Run the ``KEYS`` command and return the list of matching keys. :param pattern: the pattern to filter keys by (default ``*``) :param db: the db number to query (default ``0``) """ lines = output_lines(self.exec_redis_cli('KEYS', [pattern], db=db)) return [] if lines == [''] else lines
[ "def", "list_keys", "(", "self", ",", "pattern", "=", "'*'", ",", "db", "=", "0", ")", ":", "lines", "=", "output_lines", "(", "self", ".", "exec_redis_cli", "(", "'KEYS'", ",", "[", "pattern", "]", ",", "db", "=", "db", ")", ")", "return", "[", "]", "if", "lines", "==", "[", "''", "]", "else", "lines" ]
Run the ``KEYS`` command and return the list of matching keys. :param pattern: the pattern to filter keys by (default ``*``) :param db: the db number to query (default ``0``)
[ "Run", "the", "KEYS", "command", "and", "return", "the", "list", "of", "matching", "keys", "." ]
6f10a19b45d4ea1dc3bd0553cc4d0438696c079c
https://github.com/praekeltfoundation/seaworthy/blob/6f10a19b45d4ea1dc3bd0553cc4d0438696c079c/seaworthy/containers/redis.py#L54-L62
train
tuomas2/automate
src/automate/common.py
threaded
def threaded(system, func, *args, **kwargs): """ uses thread_init as a decorator-style """ @wraps(func) def wrapper(*args, **kwargs): try: return func(*args, **kwargs) except Exception as e: if system.raven_client: system.raven_client.captureException() logger.exception('Exception occurred in thread: %s', e) return False return lambda: wrapper(*args, **kwargs)
python
def threaded(system, func, *args, **kwargs): """ uses thread_init as a decorator-style """ @wraps(func) def wrapper(*args, **kwargs): try: return func(*args, **kwargs) except Exception as e: if system.raven_client: system.raven_client.captureException() logger.exception('Exception occurred in thread: %s', e) return False return lambda: wrapper(*args, **kwargs)
[ "def", "threaded", "(", "system", ",", "func", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "@", "wraps", "(", "func", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "return", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", "except", "Exception", "as", "e", ":", "if", "system", ".", "raven_client", ":", "system", ".", "raven_client", ".", "captureException", "(", ")", "logger", ".", "exception", "(", "'Exception occurred in thread: %s'", ",", "e", ")", "return", "False", "return", "lambda", ":", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
uses thread_init as a decorator-style
[ "uses", "thread_init", "as", "a", "decorator", "-", "style" ]
d8a8cd03cd0da047e033a2d305f3f260f8c4e017
https://github.com/tuomas2/automate/blob/d8a8cd03cd0da047e033a2d305f3f260f8c4e017/src/automate/common.py#L96-L108
train
praekeltfoundation/seaworthy
seaworthy/stream/matchers.py
OrderedMatcher.match
def match(self, item): """ Return ``True`` if the expected matchers are matched in the expected order, otherwise ``False``. """ if self._position == len(self._matchers): raise RuntimeError('Matcher exhausted, no more matchers to use') matcher = self._matchers[self._position] if matcher(item): self._position += 1 if self._position == len(self._matchers): # All patterns have been matched return True return False
python
def match(self, item): """ Return ``True`` if the expected matchers are matched in the expected order, otherwise ``False``. """ if self._position == len(self._matchers): raise RuntimeError('Matcher exhausted, no more matchers to use') matcher = self._matchers[self._position] if matcher(item): self._position += 1 if self._position == len(self._matchers): # All patterns have been matched return True return False
[ "def", "match", "(", "self", ",", "item", ")", ":", "if", "self", ".", "_position", "==", "len", "(", "self", ".", "_matchers", ")", ":", "raise", "RuntimeError", "(", "'Matcher exhausted, no more matchers to use'", ")", "matcher", "=", "self", ".", "_matchers", "[", "self", ".", "_position", "]", "if", "matcher", "(", "item", ")", ":", "self", ".", "_position", "+=", "1", "if", "self", ".", "_position", "==", "len", "(", "self", ".", "_matchers", ")", ":", "# All patterns have been matched", "return", "True", "return", "False" ]
Return ``True`` if the expected matchers are matched in the expected order, otherwise ``False``.
[ "Return", "True", "if", "the", "expected", "matchers", "are", "matched", "in", "the", "expected", "order", "otherwise", "False", "." ]
6f10a19b45d4ea1dc3bd0553cc4d0438696c079c
https://github.com/praekeltfoundation/seaworthy/blob/6f10a19b45d4ea1dc3bd0553cc4d0438696c079c/seaworthy/stream/matchers.py#L81-L97
train
praekeltfoundation/seaworthy
seaworthy/stream/matchers.py
UnorderedMatcher.match
def match(self, item): """ Return ``True`` if the expected matchers are matched in any order, otherwise ``False``. """ if not self._unused_matchers: raise RuntimeError('Matcher exhausted, no more matchers to use') for matcher in self._unused_matchers: if matcher(item): self._used_matchers.append(matcher) break if not self._unused_matchers: # All patterns have been matched return True return False
python
def match(self, item): """ Return ``True`` if the expected matchers are matched in any order, otherwise ``False``. """ if not self._unused_matchers: raise RuntimeError('Matcher exhausted, no more matchers to use') for matcher in self._unused_matchers: if matcher(item): self._used_matchers.append(matcher) break if not self._unused_matchers: # All patterns have been matched return True return False
[ "def", "match", "(", "self", ",", "item", ")", ":", "if", "not", "self", ".", "_unused_matchers", ":", "raise", "RuntimeError", "(", "'Matcher exhausted, no more matchers to use'", ")", "for", "matcher", "in", "self", ".", "_unused_matchers", ":", "if", "matcher", "(", "item", ")", ":", "self", ".", "_used_matchers", ".", "append", "(", "matcher", ")", "break", "if", "not", "self", ".", "_unused_matchers", ":", "# All patterns have been matched", "return", "True", "return", "False" ]
Return ``True`` if the expected matchers are matched in any order, otherwise ``False``.
[ "Return", "True", "if", "the", "expected", "matchers", "are", "matched", "in", "any", "order", "otherwise", "False", "." ]
6f10a19b45d4ea1dc3bd0553cc4d0438696c079c
https://github.com/praekeltfoundation/seaworthy/blob/6f10a19b45d4ea1dc3bd0553cc4d0438696c079c/seaworthy/stream/matchers.py#L129-L146
train
ratt-ru/PyMORESANE
pymoresane/main.py
DataImage.moresane_by_scale
def moresane_by_scale(self, start_scale=1, stop_scale=20, subregion=None, sigma_level=4, loop_gain=0.1, tolerance=0.75, accuracy=1e-6, major_loop_miter=100, minor_loop_miter=30, all_on_gpu=False, decom_mode="ser", core_count=1, conv_device='cpu', conv_mode='linear', extraction_mode='cpu', enforce_positivity=False, edge_suppression=False, edge_offset=0, flux_threshold=0, neg_comp=False, edge_excl=0, int_excl=0): """ Extension of the MORESANE algorithm. This takes a scale-by-scale approach, attempting to remove all sources at the lower scales before moving onto the higher ones. At each step the algorithm may return to previous scales to remove the sources uncovered by the deconvolution. INPUTS: start_scale (default=1) The first scale which is to be considered. stop_scale (default=20) The maximum scale which is to be considered. Optional. subregion (default=None): Size, in pixels, of the central region to be analyzed and deconvolved. sigma_level (default=4) Number of sigma at which thresholding is to be performed. loop_gain (default=0.1): Loop gain for the deconvolution. tolerance (default=0.75): Tolerance level for object extraction. Significant objects contain wavelet coefficients greater than the tolerance multiplied by the maximum wavelet coefficient in the scale under consideration. accuracy (default=1e-6): Threshold on the standard deviation of the residual noise. Exit main loop when this threshold is reached. major_loop_miter (default=100): Maximum number of iterations allowed in the major loop. Exit condition. minor_loop_miter (default=30): Maximum number of iterations allowed in the minor loop. Serves as an exit condition when the SNR does not reach a maximum. all_on_gpu (default=False): Boolean specifier to toggle all gpu modes on. decom_mode (default='ser'): Specifier for decomposition mode - serial, multiprocessing, or gpu. core_count (default=1): In the event that multiprocessing, specifies the number of cores. conv_device (default='cpu'): Specifier for device to be used - cpu or gpu. conv_mode (default='linear'): Specifier for convolution mode - linear or circular. extraction_mode (default='cpu'): Specifier for mode to be used - cpu or gpu. enforce_positivity (default=False): Boolean specifier for whether or not a model must be strictly positive. edge_suppression (default=False): Boolean specifier for whether or not the edges are to be suprressed. edge_offset (default=0): Numeric value for an additional user-specified number of edge pixels to be ignored. This is added to the minimum suppression. OUTPUTS: self.model (no default): Model extracted by the algorithm. self.residual (no default): Residual signal after deconvolution. """ # The following preserves the dirty image as it will be changed on every iteration. dirty_data = self.dirty_data scale_count = start_scale while not (self.complete): logger.info("MORESANE at scale {}".format(scale_count)) self.moresane(subregion=subregion, scale_count=scale_count, sigma_level=sigma_level, loop_gain=loop_gain, tolerance=tolerance, accuracy=accuracy, major_loop_miter=major_loop_miter, minor_loop_miter=minor_loop_miter, all_on_gpu=all_on_gpu, decom_mode=decom_mode, core_count=core_count, conv_device=conv_device, conv_mode=conv_mode, extraction_mode=extraction_mode, enforce_positivity=enforce_positivity, edge_suppression=edge_suppression, edge_offset=edge_offset, flux_threshold=flux_threshold, neg_comp=neg_comp, edge_excl=edge_excl, int_excl=int_excl) self.dirty_data = self.residual scale_count += 1 if (scale_count>(np.log2(self.dirty_data.shape[0]))-1): logger.info("Maximum scale reached - finished.") break if (scale_count>stop_scale): logger.info("Maximum scale reached - finished.") break # Restores the original dirty image. self.dirty_data = dirty_data self.complete = False
python
def moresane_by_scale(self, start_scale=1, stop_scale=20, subregion=None, sigma_level=4, loop_gain=0.1, tolerance=0.75, accuracy=1e-6, major_loop_miter=100, minor_loop_miter=30, all_on_gpu=False, decom_mode="ser", core_count=1, conv_device='cpu', conv_mode='linear', extraction_mode='cpu', enforce_positivity=False, edge_suppression=False, edge_offset=0, flux_threshold=0, neg_comp=False, edge_excl=0, int_excl=0): """ Extension of the MORESANE algorithm. This takes a scale-by-scale approach, attempting to remove all sources at the lower scales before moving onto the higher ones. At each step the algorithm may return to previous scales to remove the sources uncovered by the deconvolution. INPUTS: start_scale (default=1) The first scale which is to be considered. stop_scale (default=20) The maximum scale which is to be considered. Optional. subregion (default=None): Size, in pixels, of the central region to be analyzed and deconvolved. sigma_level (default=4) Number of sigma at which thresholding is to be performed. loop_gain (default=0.1): Loop gain for the deconvolution. tolerance (default=0.75): Tolerance level for object extraction. Significant objects contain wavelet coefficients greater than the tolerance multiplied by the maximum wavelet coefficient in the scale under consideration. accuracy (default=1e-6): Threshold on the standard deviation of the residual noise. Exit main loop when this threshold is reached. major_loop_miter (default=100): Maximum number of iterations allowed in the major loop. Exit condition. minor_loop_miter (default=30): Maximum number of iterations allowed in the minor loop. Serves as an exit condition when the SNR does not reach a maximum. all_on_gpu (default=False): Boolean specifier to toggle all gpu modes on. decom_mode (default='ser'): Specifier for decomposition mode - serial, multiprocessing, or gpu. core_count (default=1): In the event that multiprocessing, specifies the number of cores. conv_device (default='cpu'): Specifier for device to be used - cpu or gpu. conv_mode (default='linear'): Specifier for convolution mode - linear or circular. extraction_mode (default='cpu'): Specifier for mode to be used - cpu or gpu. enforce_positivity (default=False): Boolean specifier for whether or not a model must be strictly positive. edge_suppression (default=False): Boolean specifier for whether or not the edges are to be suprressed. edge_offset (default=0): Numeric value for an additional user-specified number of edge pixels to be ignored. This is added to the minimum suppression. OUTPUTS: self.model (no default): Model extracted by the algorithm. self.residual (no default): Residual signal after deconvolution. """ # The following preserves the dirty image as it will be changed on every iteration. dirty_data = self.dirty_data scale_count = start_scale while not (self.complete): logger.info("MORESANE at scale {}".format(scale_count)) self.moresane(subregion=subregion, scale_count=scale_count, sigma_level=sigma_level, loop_gain=loop_gain, tolerance=tolerance, accuracy=accuracy, major_loop_miter=major_loop_miter, minor_loop_miter=minor_loop_miter, all_on_gpu=all_on_gpu, decom_mode=decom_mode, core_count=core_count, conv_device=conv_device, conv_mode=conv_mode, extraction_mode=extraction_mode, enforce_positivity=enforce_positivity, edge_suppression=edge_suppression, edge_offset=edge_offset, flux_threshold=flux_threshold, neg_comp=neg_comp, edge_excl=edge_excl, int_excl=int_excl) self.dirty_data = self.residual scale_count += 1 if (scale_count>(np.log2(self.dirty_data.shape[0]))-1): logger.info("Maximum scale reached - finished.") break if (scale_count>stop_scale): logger.info("Maximum scale reached - finished.") break # Restores the original dirty image. self.dirty_data = dirty_data self.complete = False
[ "def", "moresane_by_scale", "(", "self", ",", "start_scale", "=", "1", ",", "stop_scale", "=", "20", ",", "subregion", "=", "None", ",", "sigma_level", "=", "4", ",", "loop_gain", "=", "0.1", ",", "tolerance", "=", "0.75", ",", "accuracy", "=", "1e-6", ",", "major_loop_miter", "=", "100", ",", "minor_loop_miter", "=", "30", ",", "all_on_gpu", "=", "False", ",", "decom_mode", "=", "\"ser\"", ",", "core_count", "=", "1", ",", "conv_device", "=", "'cpu'", ",", "conv_mode", "=", "'linear'", ",", "extraction_mode", "=", "'cpu'", ",", "enforce_positivity", "=", "False", ",", "edge_suppression", "=", "False", ",", "edge_offset", "=", "0", ",", "flux_threshold", "=", "0", ",", "neg_comp", "=", "False", ",", "edge_excl", "=", "0", ",", "int_excl", "=", "0", ")", ":", "# The following preserves the dirty image as it will be changed on every iteration.", "dirty_data", "=", "self", ".", "dirty_data", "scale_count", "=", "start_scale", "while", "not", "(", "self", ".", "complete", ")", ":", "logger", ".", "info", "(", "\"MORESANE at scale {}\"", ".", "format", "(", "scale_count", ")", ")", "self", ".", "moresane", "(", "subregion", "=", "subregion", ",", "scale_count", "=", "scale_count", ",", "sigma_level", "=", "sigma_level", ",", "loop_gain", "=", "loop_gain", ",", "tolerance", "=", "tolerance", ",", "accuracy", "=", "accuracy", ",", "major_loop_miter", "=", "major_loop_miter", ",", "minor_loop_miter", "=", "minor_loop_miter", ",", "all_on_gpu", "=", "all_on_gpu", ",", "decom_mode", "=", "decom_mode", ",", "core_count", "=", "core_count", ",", "conv_device", "=", "conv_device", ",", "conv_mode", "=", "conv_mode", ",", "extraction_mode", "=", "extraction_mode", ",", "enforce_positivity", "=", "enforce_positivity", ",", "edge_suppression", "=", "edge_suppression", ",", "edge_offset", "=", "edge_offset", ",", "flux_threshold", "=", "flux_threshold", ",", "neg_comp", "=", "neg_comp", ",", "edge_excl", "=", "edge_excl", ",", "int_excl", "=", "int_excl", ")", "self", ".", "dirty_data", "=", "self", ".", "residual", "scale_count", "+=", "1", "if", "(", "scale_count", ">", "(", "np", ".", "log2", "(", "self", ".", "dirty_data", ".", "shape", "[", "0", "]", ")", ")", "-", "1", ")", ":", "logger", ".", "info", "(", "\"Maximum scale reached - finished.\"", ")", "break", "if", "(", "scale_count", ">", "stop_scale", ")", ":", "logger", ".", "info", "(", "\"Maximum scale reached - finished.\"", ")", "break", "# Restores the original dirty image.", "self", ".", "dirty_data", "=", "dirty_data", "self", ".", "complete", "=", "False" ]
Extension of the MORESANE algorithm. This takes a scale-by-scale approach, attempting to remove all sources at the lower scales before moving onto the higher ones. At each step the algorithm may return to previous scales to remove the sources uncovered by the deconvolution. INPUTS: start_scale (default=1) The first scale which is to be considered. stop_scale (default=20) The maximum scale which is to be considered. Optional. subregion (default=None): Size, in pixels, of the central region to be analyzed and deconvolved. sigma_level (default=4) Number of sigma at which thresholding is to be performed. loop_gain (default=0.1): Loop gain for the deconvolution. tolerance (default=0.75): Tolerance level for object extraction. Significant objects contain wavelet coefficients greater than the tolerance multiplied by the maximum wavelet coefficient in the scale under consideration. accuracy (default=1e-6): Threshold on the standard deviation of the residual noise. Exit main loop when this threshold is reached. major_loop_miter (default=100): Maximum number of iterations allowed in the major loop. Exit condition. minor_loop_miter (default=30): Maximum number of iterations allowed in the minor loop. Serves as an exit condition when the SNR does not reach a maximum. all_on_gpu (default=False): Boolean specifier to toggle all gpu modes on. decom_mode (default='ser'): Specifier for decomposition mode - serial, multiprocessing, or gpu. core_count (default=1): In the event that multiprocessing, specifies the number of cores. conv_device (default='cpu'): Specifier for device to be used - cpu or gpu. conv_mode (default='linear'): Specifier for convolution mode - linear or circular. extraction_mode (default='cpu'): Specifier for mode to be used - cpu or gpu. enforce_positivity (default=False): Boolean specifier for whether or not a model must be strictly positive. edge_suppression (default=False): Boolean specifier for whether or not the edges are to be suprressed. edge_offset (default=0): Numeric value for an additional user-specified number of edge pixels to be ignored. This is added to the minimum suppression. OUTPUTS: self.model (no default): Model extracted by the algorithm. self.residual (no default): Residual signal after deconvolution.
[ "Extension", "of", "the", "MORESANE", "algorithm", ".", "This", "takes", "a", "scale", "-", "by", "-", "scale", "approach", "attempting", "to", "remove", "all", "sources", "at", "the", "lower", "scales", "before", "moving", "onto", "the", "higher", "ones", ".", "At", "each", "step", "the", "algorithm", "may", "return", "to", "previous", "scales", "to", "remove", "the", "sources", "uncovered", "by", "the", "deconvolution", "." ]
b024591ad0bbb69320d08841f28a2c27f62ae1af
https://github.com/ratt-ru/PyMORESANE/blob/b024591ad0bbb69320d08841f28a2c27f62ae1af/pymoresane/main.py#L523-L599
train
ratt-ru/PyMORESANE
pymoresane/main.py
DataImage.restore
def restore(self): """ This method constructs the restoring beam and then adds the convolution to the residual. """ clean_beam, beam_params = beam_fit(self.psf_data, self.cdelt1, self.cdelt2) if np.all(np.array(self.psf_data_shape)==2*np.array(self.dirty_data_shape)): self.restored = np.fft.fftshift(np.fft.irfft2(np.fft.rfft2(conv.pad_array(self.model))*np.fft.rfft2(clean_beam))) self.restored = self.restored[self.dirty_data_shape[0]/2:-self.dirty_data_shape[0]/2, self.dirty_data_shape[1]/2:-self.dirty_data_shape[1]/2] else: self.restored = np.fft.fftshift(np.fft.irfft2(np.fft.rfft2(self.model)*np.fft.rfft2(clean_beam))) self.restored += self.residual self.restored = self.restored.astype(np.float32) return beam_params
python
def restore(self): """ This method constructs the restoring beam and then adds the convolution to the residual. """ clean_beam, beam_params = beam_fit(self.psf_data, self.cdelt1, self.cdelt2) if np.all(np.array(self.psf_data_shape)==2*np.array(self.dirty_data_shape)): self.restored = np.fft.fftshift(np.fft.irfft2(np.fft.rfft2(conv.pad_array(self.model))*np.fft.rfft2(clean_beam))) self.restored = self.restored[self.dirty_data_shape[0]/2:-self.dirty_data_shape[0]/2, self.dirty_data_shape[1]/2:-self.dirty_data_shape[1]/2] else: self.restored = np.fft.fftshift(np.fft.irfft2(np.fft.rfft2(self.model)*np.fft.rfft2(clean_beam))) self.restored += self.residual self.restored = self.restored.astype(np.float32) return beam_params
[ "def", "restore", "(", "self", ")", ":", "clean_beam", ",", "beam_params", "=", "beam_fit", "(", "self", ".", "psf_data", ",", "self", ".", "cdelt1", ",", "self", ".", "cdelt2", ")", "if", "np", ".", "all", "(", "np", ".", "array", "(", "self", ".", "psf_data_shape", ")", "==", "2", "*", "np", ".", "array", "(", "self", ".", "dirty_data_shape", ")", ")", ":", "self", ".", "restored", "=", "np", ".", "fft", ".", "fftshift", "(", "np", ".", "fft", ".", "irfft2", "(", "np", ".", "fft", ".", "rfft2", "(", "conv", ".", "pad_array", "(", "self", ".", "model", ")", ")", "*", "np", ".", "fft", ".", "rfft2", "(", "clean_beam", ")", ")", ")", "self", ".", "restored", "=", "self", ".", "restored", "[", "self", ".", "dirty_data_shape", "[", "0", "]", "/", "2", ":", "-", "self", ".", "dirty_data_shape", "[", "0", "]", "/", "2", ",", "self", ".", "dirty_data_shape", "[", "1", "]", "/", "2", ":", "-", "self", ".", "dirty_data_shape", "[", "1", "]", "/", "2", "]", "else", ":", "self", ".", "restored", "=", "np", ".", "fft", ".", "fftshift", "(", "np", ".", "fft", ".", "irfft2", "(", "np", ".", "fft", ".", "rfft2", "(", "self", ".", "model", ")", "*", "np", ".", "fft", ".", "rfft2", "(", "clean_beam", ")", ")", ")", "self", ".", "restored", "+=", "self", ".", "residual", "self", ".", "restored", "=", "self", ".", "restored", ".", "astype", "(", "np", ".", "float32", ")", "return", "beam_params" ]
This method constructs the restoring beam and then adds the convolution to the residual.
[ "This", "method", "constructs", "the", "restoring", "beam", "and", "then", "adds", "the", "convolution", "to", "the", "residual", "." ]
b024591ad0bbb69320d08841f28a2c27f62ae1af
https://github.com/ratt-ru/PyMORESANE/blob/b024591ad0bbb69320d08841f28a2c27f62ae1af/pymoresane/main.py#L601-L616
train
ratt-ru/PyMORESANE
pymoresane/main.py
DataImage.handle_input
def handle_input(self, input_hdr): """ This method tries to ensure that the input data has the correct dimensions. INPUTS: input_hdr (no default) Header from which data shape is to be extracted. """ input_slice = input_hdr['NAXIS']*[0] for i in range(input_hdr['NAXIS']): if input_hdr['CTYPE%d'%(i+1)].startswith("RA"): input_slice[-1] = slice(None) if input_hdr['CTYPE%d'%(i+1)].startswith("DEC"): input_slice[-2] = slice(None) return input_slice
python
def handle_input(self, input_hdr): """ This method tries to ensure that the input data has the correct dimensions. INPUTS: input_hdr (no default) Header from which data shape is to be extracted. """ input_slice = input_hdr['NAXIS']*[0] for i in range(input_hdr['NAXIS']): if input_hdr['CTYPE%d'%(i+1)].startswith("RA"): input_slice[-1] = slice(None) if input_hdr['CTYPE%d'%(i+1)].startswith("DEC"): input_slice[-2] = slice(None) return input_slice
[ "def", "handle_input", "(", "self", ",", "input_hdr", ")", ":", "input_slice", "=", "input_hdr", "[", "'NAXIS'", "]", "*", "[", "0", "]", "for", "i", "in", "range", "(", "input_hdr", "[", "'NAXIS'", "]", ")", ":", "if", "input_hdr", "[", "'CTYPE%d'", "%", "(", "i", "+", "1", ")", "]", ".", "startswith", "(", "\"RA\"", ")", ":", "input_slice", "[", "-", "1", "]", "=", "slice", "(", "None", ")", "if", "input_hdr", "[", "'CTYPE%d'", "%", "(", "i", "+", "1", ")", "]", ".", "startswith", "(", "\"DEC\"", ")", ":", "input_slice", "[", "-", "2", "]", "=", "slice", "(", "None", ")", "return", "input_slice" ]
This method tries to ensure that the input data has the correct dimensions. INPUTS: input_hdr (no default) Header from which data shape is to be extracted.
[ "This", "method", "tries", "to", "ensure", "that", "the", "input", "data", "has", "the", "correct", "dimensions", "." ]
b024591ad0bbb69320d08841f28a2c27f62ae1af
https://github.com/ratt-ru/PyMORESANE/blob/b024591ad0bbb69320d08841f28a2c27f62ae1af/pymoresane/main.py#L618-L634
train
ratt-ru/PyMORESANE
pymoresane/main.py
DataImage.save_fits
def save_fits(self, data, name): """ This method simply saves the model components and the residual. INPUTS: data (no default) Data which is to be saved. name (no default) File name for new .fits file. Will overwrite. """ data = data.reshape(1, 1, data.shape[0], data.shape[0]) new_file = pyfits.PrimaryHDU(data,self.img_hdu_list[0].header) new_file.writeto("{}".format(name), overwrite=True)
python
def save_fits(self, data, name): """ This method simply saves the model components and the residual. INPUTS: data (no default) Data which is to be saved. name (no default) File name for new .fits file. Will overwrite. """ data = data.reshape(1, 1, data.shape[0], data.shape[0]) new_file = pyfits.PrimaryHDU(data,self.img_hdu_list[0].header) new_file.writeto("{}".format(name), overwrite=True)
[ "def", "save_fits", "(", "self", ",", "data", ",", "name", ")", ":", "data", "=", "data", ".", "reshape", "(", "1", ",", "1", ",", "data", ".", "shape", "[", "0", "]", ",", "data", ".", "shape", "[", "0", "]", ")", "new_file", "=", "pyfits", ".", "PrimaryHDU", "(", "data", ",", "self", ".", "img_hdu_list", "[", "0", "]", ".", "header", ")", "new_file", ".", "writeto", "(", "\"{}\"", ".", "format", "(", "name", ")", ",", "overwrite", "=", "True", ")" ]
This method simply saves the model components and the residual. INPUTS: data (no default) Data which is to be saved. name (no default) File name for new .fits file. Will overwrite.
[ "This", "method", "simply", "saves", "the", "model", "components", "and", "the", "residual", "." ]
b024591ad0bbb69320d08841f28a2c27f62ae1af
https://github.com/ratt-ru/PyMORESANE/blob/b024591ad0bbb69320d08841f28a2c27f62ae1af/pymoresane/main.py#L636-L646
train
ratt-ru/PyMORESANE
pymoresane/main.py
DataImage.make_logger
def make_logger(self, level="INFO"): """ Convenience function which creates a logger for the module. INPUTS: level (default="INFO"): Minimum log level for logged/streamed messages. OUTPUTS: logger Logger for the function. NOTE: Must be bound to variable named logger. """ level = getattr(logging, level.upper()) logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) fh = logging.FileHandler('PyMORESANE.log', mode='w') fh.setLevel(level) ch = logging.StreamHandler() ch.setLevel(level) formatter = logging.Formatter('%(asctime)s [%(levelname)s]: %(''message)s', datefmt='[%m/%d/%Y] [%I:%M:%S]') fh.setFormatter(formatter) ch.setFormatter(formatter) logger.addHandler(fh) logger.addHandler(ch) return logger
python
def make_logger(self, level="INFO"): """ Convenience function which creates a logger for the module. INPUTS: level (default="INFO"): Minimum log level for logged/streamed messages. OUTPUTS: logger Logger for the function. NOTE: Must be bound to variable named logger. """ level = getattr(logging, level.upper()) logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) fh = logging.FileHandler('PyMORESANE.log', mode='w') fh.setLevel(level) ch = logging.StreamHandler() ch.setLevel(level) formatter = logging.Formatter('%(asctime)s [%(levelname)s]: %(''message)s', datefmt='[%m/%d/%Y] [%I:%M:%S]') fh.setFormatter(formatter) ch.setFormatter(formatter) logger.addHandler(fh) logger.addHandler(ch) return logger
[ "def", "make_logger", "(", "self", ",", "level", "=", "\"INFO\"", ")", ":", "level", "=", "getattr", "(", "logging", ",", "level", ".", "upper", "(", ")", ")", "logger", "=", "logging", ".", "getLogger", "(", "__name__", ")", "logger", ".", "setLevel", "(", "logging", ".", "DEBUG", ")", "fh", "=", "logging", ".", "FileHandler", "(", "'PyMORESANE.log'", ",", "mode", "=", "'w'", ")", "fh", ".", "setLevel", "(", "level", ")", "ch", "=", "logging", ".", "StreamHandler", "(", ")", "ch", ".", "setLevel", "(", "level", ")", "formatter", "=", "logging", ".", "Formatter", "(", "'%(asctime)s [%(levelname)s]: %('", "'message)s'", ",", "datefmt", "=", "'[%m/%d/%Y] [%I:%M:%S]'", ")", "fh", ".", "setFormatter", "(", "formatter", ")", "ch", ".", "setFormatter", "(", "formatter", ")", "logger", ".", "addHandler", "(", "fh", ")", "logger", ".", "addHandler", "(", "ch", ")", "return", "logger" ]
Convenience function which creates a logger for the module. INPUTS: level (default="INFO"): Minimum log level for logged/streamed messages. OUTPUTS: logger Logger for the function. NOTE: Must be bound to variable named logger.
[ "Convenience", "function", "which", "creates", "a", "logger", "for", "the", "module", "." ]
b024591ad0bbb69320d08841f28a2c27f62ae1af
https://github.com/ratt-ru/PyMORESANE/blob/b024591ad0bbb69320d08841f28a2c27f62ae1af/pymoresane/main.py#L648-L676
train
tuomas2/automate
src/automate/services/textui.py
TextUIService.text_ui
def text_ui(self): """ Start Text UI main loop """ self.logger.info("Starting command line interface") self.help() try: self.ipython_ui() except ImportError: self.fallback_ui() self.system.cleanup()
python
def text_ui(self): """ Start Text UI main loop """ self.logger.info("Starting command line interface") self.help() try: self.ipython_ui() except ImportError: self.fallback_ui() self.system.cleanup()
[ "def", "text_ui", "(", "self", ")", ":", "self", ".", "logger", ".", "info", "(", "\"Starting command line interface\"", ")", "self", ".", "help", "(", ")", "try", ":", "self", ".", "ipython_ui", "(", ")", "except", "ImportError", ":", "self", ".", "fallback_ui", "(", ")", "self", ".", "system", ".", "cleanup", "(", ")" ]
Start Text UI main loop
[ "Start", "Text", "UI", "main", "loop" ]
d8a8cd03cd0da047e033a2d305f3f260f8c4e017
https://github.com/tuomas2/automate/blob/d8a8cd03cd0da047e033a2d305f3f260f8c4e017/src/automate/services/textui.py#L96-L106
train
utek/pyseaweed
pyseaweed/utils.py
Connection._prepare_headers
def _prepare_headers(self, additional_headers=None, **kwargs): """Prepare headers for http communication. Return dict of header to be used in requests. Args: .. versionadded:: 0.3.2 **additional_headers**: (optional) Additional headers to be used with request Returns: Headers dict. Key and values are string """ user_agent = "pyseaweed/{version}".format(version=__version__) headers = {"User-Agent": user_agent} if additional_headers is not None: headers.update(additional_headers) return headers
python
def _prepare_headers(self, additional_headers=None, **kwargs): """Prepare headers for http communication. Return dict of header to be used in requests. Args: .. versionadded:: 0.3.2 **additional_headers**: (optional) Additional headers to be used with request Returns: Headers dict. Key and values are string """ user_agent = "pyseaweed/{version}".format(version=__version__) headers = {"User-Agent": user_agent} if additional_headers is not None: headers.update(additional_headers) return headers
[ "def", "_prepare_headers", "(", "self", ",", "additional_headers", "=", "None", ",", "*", "*", "kwargs", ")", ":", "user_agent", "=", "\"pyseaweed/{version}\"", ".", "format", "(", "version", "=", "__version__", ")", "headers", "=", "{", "\"User-Agent\"", ":", "user_agent", "}", "if", "additional_headers", "is", "not", "None", ":", "headers", ".", "update", "(", "additional_headers", ")", "return", "headers" ]
Prepare headers for http communication. Return dict of header to be used in requests. Args: .. versionadded:: 0.3.2 **additional_headers**: (optional) Additional headers to be used with request Returns: Headers dict. Key and values are string
[ "Prepare", "headers", "for", "http", "communication", "." ]
218049329885425a2b8370157fa44952e64516be
https://github.com/utek/pyseaweed/blob/218049329885425a2b8370157fa44952e64516be/pyseaweed/utils.py#L21-L39
train
utek/pyseaweed
pyseaweed/utils.py
Connection.head
def head(self, url, *args, **kwargs): """Returns response to http HEAD on provided url """ res = self._conn.head(url, headers=self._prepare_headers(**kwargs)) if res.status_code == 200: return res return None
python
def head(self, url, *args, **kwargs): """Returns response to http HEAD on provided url """ res = self._conn.head(url, headers=self._prepare_headers(**kwargs)) if res.status_code == 200: return res return None
[ "def", "head", "(", "self", ",", "url", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "res", "=", "self", ".", "_conn", ".", "head", "(", "url", ",", "headers", "=", "self", ".", "_prepare_headers", "(", "*", "*", "kwargs", ")", ")", "if", "res", ".", "status_code", "==", "200", ":", "return", "res", "return", "None" ]
Returns response to http HEAD on provided url
[ "Returns", "response", "to", "http", "HEAD", "on", "provided", "url" ]
218049329885425a2b8370157fa44952e64516be
https://github.com/utek/pyseaweed/blob/218049329885425a2b8370157fa44952e64516be/pyseaweed/utils.py#L41-L48
train
utek/pyseaweed
pyseaweed/utils.py
Connection.get_data
def get_data(self, url, *args, **kwargs): """Gets data from url as text Returns content under the provided url as text Args: **url**: address of the wanted data .. versionadded:: 0.3.2 **additional_headers**: (optional) Additional headers to be used with request Returns: string """ res = self._conn.get(url, headers=self._prepare_headers(**kwargs)) if res.status_code == 200: return res.text else: return None
python
def get_data(self, url, *args, **kwargs): """Gets data from url as text Returns content under the provided url as text Args: **url**: address of the wanted data .. versionadded:: 0.3.2 **additional_headers**: (optional) Additional headers to be used with request Returns: string """ res = self._conn.get(url, headers=self._prepare_headers(**kwargs)) if res.status_code == 200: return res.text else: return None
[ "def", "get_data", "(", "self", ",", "url", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "res", "=", "self", ".", "_conn", ".", "get", "(", "url", ",", "headers", "=", "self", ".", "_prepare_headers", "(", "*", "*", "kwargs", ")", ")", "if", "res", ".", "status_code", "==", "200", ":", "return", "res", ".", "text", "else", ":", "return", "None" ]
Gets data from url as text Returns content under the provided url as text Args: **url**: address of the wanted data .. versionadded:: 0.3.2 **additional_headers**: (optional) Additional headers to be used with request Returns: string
[ "Gets", "data", "from", "url", "as", "text" ]
218049329885425a2b8370157fa44952e64516be
https://github.com/utek/pyseaweed/blob/218049329885425a2b8370157fa44952e64516be/pyseaweed/utils.py#L50-L70
train
utek/pyseaweed
pyseaweed/utils.py
Connection.get_raw_data
def get_raw_data(self, url, *args, **kwargs): """Gets data from url as bytes Returns content under the provided url as bytes ie. for binary data Args: **url**: address of the wanted data .. versionadded:: 0.3.2 **additional_headers**: (optional) Additional headers to be used with request Returns: bytes """ res = self._conn.get(url, headers=self._prepare_headers(**kwargs)) if res.status_code == 200: return res.content else: return None
python
def get_raw_data(self, url, *args, **kwargs): """Gets data from url as bytes Returns content under the provided url as bytes ie. for binary data Args: **url**: address of the wanted data .. versionadded:: 0.3.2 **additional_headers**: (optional) Additional headers to be used with request Returns: bytes """ res = self._conn.get(url, headers=self._prepare_headers(**kwargs)) if res.status_code == 200: return res.content else: return None
[ "def", "get_raw_data", "(", "self", ",", "url", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "res", "=", "self", ".", "_conn", ".", "get", "(", "url", ",", "headers", "=", "self", ".", "_prepare_headers", "(", "*", "*", "kwargs", ")", ")", "if", "res", ".", "status_code", "==", "200", ":", "return", "res", ".", "content", "else", ":", "return", "None" ]
Gets data from url as bytes Returns content under the provided url as bytes ie. for binary data Args: **url**: address of the wanted data .. versionadded:: 0.3.2 **additional_headers**: (optional) Additional headers to be used with request Returns: bytes
[ "Gets", "data", "from", "url", "as", "bytes" ]
218049329885425a2b8370157fa44952e64516be
https://github.com/utek/pyseaweed/blob/218049329885425a2b8370157fa44952e64516be/pyseaweed/utils.py#L72-L93
train
utek/pyseaweed
pyseaweed/utils.py
Connection.post_file
def post_file(self, url, filename, file_stream, *args, **kwargs): """Uploads file to provided url. Returns contents as text Args: **url**: address where to upload file **filename**: Name of the uploaded file **file_stream**: file like object to upload .. versionadded:: 0.3.2 **additional_headers**: (optional) Additional headers to be used with request Returns: string """ res = self._conn.post(url, files={filename: file_stream}, headers=self._prepare_headers(**kwargs)) if res.status_code == 200 or res.status_code == 201: return res.text else: return None
python
def post_file(self, url, filename, file_stream, *args, **kwargs): """Uploads file to provided url. Returns contents as text Args: **url**: address where to upload file **filename**: Name of the uploaded file **file_stream**: file like object to upload .. versionadded:: 0.3.2 **additional_headers**: (optional) Additional headers to be used with request Returns: string """ res = self._conn.post(url, files={filename: file_stream}, headers=self._prepare_headers(**kwargs)) if res.status_code == 200 or res.status_code == 201: return res.text else: return None
[ "def", "post_file", "(", "self", ",", "url", ",", "filename", ",", "file_stream", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "res", "=", "self", ".", "_conn", ".", "post", "(", "url", ",", "files", "=", "{", "filename", ":", "file_stream", "}", ",", "headers", "=", "self", ".", "_prepare_headers", "(", "*", "*", "kwargs", ")", ")", "if", "res", ".", "status_code", "==", "200", "or", "res", ".", "status_code", "==", "201", ":", "return", "res", ".", "text", "else", ":", "return", "None" ]
Uploads file to provided url. Returns contents as text Args: **url**: address where to upload file **filename**: Name of the uploaded file **file_stream**: file like object to upload .. versionadded:: 0.3.2 **additional_headers**: (optional) Additional headers to be used with request Returns: string
[ "Uploads", "file", "to", "provided", "url", "." ]
218049329885425a2b8370157fa44952e64516be
https://github.com/utek/pyseaweed/blob/218049329885425a2b8370157fa44952e64516be/pyseaweed/utils.py#L95-L119
train
utek/pyseaweed
pyseaweed/utils.py
Connection.delete_data
def delete_data(self, url, *args, **kwargs): """Deletes data under provided url Returns status as boolean. Args: **url**: address of file to be deleted .. versionadded:: 0.3.2 **additional_headers**: (optional) Additional headers to be used with request Returns: Boolean. True if request was successful. False if not. """ res = self._conn.delete(url, headers=self._prepare_headers(**kwargs)) if res.status_code == 200 or res.status_code == 202: return True else: return False
python
def delete_data(self, url, *args, **kwargs): """Deletes data under provided url Returns status as boolean. Args: **url**: address of file to be deleted .. versionadded:: 0.3.2 **additional_headers**: (optional) Additional headers to be used with request Returns: Boolean. True if request was successful. False if not. """ res = self._conn.delete(url, headers=self._prepare_headers(**kwargs)) if res.status_code == 200 or res.status_code == 202: return True else: return False
[ "def", "delete_data", "(", "self", ",", "url", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "res", "=", "self", ".", "_conn", ".", "delete", "(", "url", ",", "headers", "=", "self", ".", "_prepare_headers", "(", "*", "*", "kwargs", ")", ")", "if", "res", ".", "status_code", "==", "200", "or", "res", ".", "status_code", "==", "202", ":", "return", "True", "else", ":", "return", "False" ]
Deletes data under provided url Returns status as boolean. Args: **url**: address of file to be deleted .. versionadded:: 0.3.2 **additional_headers**: (optional) Additional headers to be used with request Returns: Boolean. True if request was successful. False if not.
[ "Deletes", "data", "under", "provided", "url" ]
218049329885425a2b8370157fa44952e64516be
https://github.com/utek/pyseaweed/blob/218049329885425a2b8370157fa44952e64516be/pyseaweed/utils.py#L121-L140
train
jtauber/greek-accentuation
greek_accentuation/characters.py
remove_diacritic
def remove_diacritic(*diacritics): """ Given a collection of Unicode diacritics, return a function that takes a string and returns the string without those diacritics. """ def _(text): return unicodedata.normalize("NFC", "".join( ch for ch in unicodedata.normalize("NFD", text) if ch not in diacritics) ) return _
python
def remove_diacritic(*diacritics): """ Given a collection of Unicode diacritics, return a function that takes a string and returns the string without those diacritics. """ def _(text): return unicodedata.normalize("NFC", "".join( ch for ch in unicodedata.normalize("NFD", text) if ch not in diacritics) ) return _
[ "def", "remove_diacritic", "(", "*", "diacritics", ")", ":", "def", "_", "(", "text", ")", ":", "return", "unicodedata", ".", "normalize", "(", "\"NFC\"", ",", "\"\"", ".", "join", "(", "ch", "for", "ch", "in", "unicodedata", ".", "normalize", "(", "\"NFD\"", ",", "text", ")", "if", "ch", "not", "in", "diacritics", ")", ")", "return", "_" ]
Given a collection of Unicode diacritics, return a function that takes a string and returns the string without those diacritics.
[ "Given", "a", "collection", "of", "Unicode", "diacritics", "return", "a", "function", "that", "takes", "a", "string", "and", "returns", "the", "string", "without", "those", "diacritics", "." ]
330796cd97f7c7adcbecbd05bd91be984f9b9f67
https://github.com/jtauber/greek-accentuation/blob/330796cd97f7c7adcbecbd05bd91be984f9b9f67/greek_accentuation/characters.py#L42-L53
train
praekeltfoundation/seaworthy
seaworthy/definitions.py
deep_merge
def deep_merge(*dicts): """ Recursively merge all input dicts into a single dict. """ result = {} for d in dicts: if not isinstance(d, dict): raise Exception('Can only deep_merge dicts, got {}'.format(d)) for k, v in d.items(): # Whenever the value is a dict, we deep_merge it. This ensures that # (a) we only ever merge dicts with dicts and (b) we always get a # deep(ish) copy of the dicts and are thus safe from accidental # mutations to shared state. if isinstance(v, dict): v = deep_merge(result.get(k, {}), v) result[k] = v return result
python
def deep_merge(*dicts): """ Recursively merge all input dicts into a single dict. """ result = {} for d in dicts: if not isinstance(d, dict): raise Exception('Can only deep_merge dicts, got {}'.format(d)) for k, v in d.items(): # Whenever the value is a dict, we deep_merge it. This ensures that # (a) we only ever merge dicts with dicts and (b) we always get a # deep(ish) copy of the dicts and are thus safe from accidental # mutations to shared state. if isinstance(v, dict): v = deep_merge(result.get(k, {}), v) result[k] = v return result
[ "def", "deep_merge", "(", "*", "dicts", ")", ":", "result", "=", "{", "}", "for", "d", "in", "dicts", ":", "if", "not", "isinstance", "(", "d", ",", "dict", ")", ":", "raise", "Exception", "(", "'Can only deep_merge dicts, got {}'", ".", "format", "(", "d", ")", ")", "for", "k", ",", "v", "in", "d", ".", "items", "(", ")", ":", "# Whenever the value is a dict, we deep_merge it. This ensures that", "# (a) we only ever merge dicts with dicts and (b) we always get a", "# deep(ish) copy of the dicts and are thus safe from accidental", "# mutations to shared state.", "if", "isinstance", "(", "v", ",", "dict", ")", ":", "v", "=", "deep_merge", "(", "result", ".", "get", "(", "k", ",", "{", "}", ")", ",", "v", ")", "result", "[", "k", "]", "=", "v", "return", "result" ]
Recursively merge all input dicts into a single dict.
[ "Recursively", "merge", "all", "input", "dicts", "into", "a", "single", "dict", "." ]
6f10a19b45d4ea1dc3bd0553cc4d0438696c079c
https://github.com/praekeltfoundation/seaworthy/blob/6f10a19b45d4ea1dc3bd0553cc4d0438696c079c/seaworthy/definitions.py#L21-L37
train
praekeltfoundation/seaworthy
seaworthy/definitions.py
_DefinitionBase.create
def create(self, **kwargs): """ Create an instance of this resource definition. Only one instance may exist at any given time. """ if self.created: raise RuntimeError( '{} already created.'.format(self.__model_type__.__name__)) kwargs = self.merge_kwargs(self._create_kwargs, kwargs) self._inner = self.helper.create( self.name, *self._create_args, **kwargs)
python
def create(self, **kwargs): """ Create an instance of this resource definition. Only one instance may exist at any given time. """ if self.created: raise RuntimeError( '{} already created.'.format(self.__model_type__.__name__)) kwargs = self.merge_kwargs(self._create_kwargs, kwargs) self._inner = self.helper.create( self.name, *self._create_args, **kwargs)
[ "def", "create", "(", "self", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "created", ":", "raise", "RuntimeError", "(", "'{} already created.'", ".", "format", "(", "self", ".", "__model_type__", ".", "__name__", ")", ")", "kwargs", "=", "self", ".", "merge_kwargs", "(", "self", ".", "_create_kwargs", ",", "kwargs", ")", "self", ".", "_inner", "=", "self", ".", "helper", ".", "create", "(", "self", ".", "name", ",", "*", "self", ".", "_create_args", ",", "*", "*", "kwargs", ")" ]
Create an instance of this resource definition. Only one instance may exist at any given time.
[ "Create", "an", "instance", "of", "this", "resource", "definition", "." ]
6f10a19b45d4ea1dc3bd0553cc4d0438696c079c
https://github.com/praekeltfoundation/seaworthy/blob/6f10a19b45d4ea1dc3bd0553cc4d0438696c079c/seaworthy/definitions.py#L54-L67
train
praekeltfoundation/seaworthy
seaworthy/definitions.py
_DefinitionBase.remove
def remove(self, **kwargs): """ Remove an instance of this resource definition. """ self.helper.remove(self.inner(), **kwargs) self._inner = None
python
def remove(self, **kwargs): """ Remove an instance of this resource definition. """ self.helper.remove(self.inner(), **kwargs) self._inner = None
[ "def", "remove", "(", "self", ",", "*", "*", "kwargs", ")", ":", "self", ".", "helper", ".", "remove", "(", "self", ".", "inner", "(", ")", ",", "*", "*", "kwargs", ")", "self", ".", "_inner", "=", "None" ]
Remove an instance of this resource definition.
[ "Remove", "an", "instance", "of", "this", "resource", "definition", "." ]
6f10a19b45d4ea1dc3bd0553cc4d0438696c079c
https://github.com/praekeltfoundation/seaworthy/blob/6f10a19b45d4ea1dc3bd0553cc4d0438696c079c/seaworthy/definitions.py#L69-L74
train
praekeltfoundation/seaworthy
seaworthy/definitions.py
_DefinitionBase.setup
def setup(self, helper=None, **create_kwargs): """ Setup this resource so that is ready to be used in a test. If the resource has already been created, this call does nothing. For most resources, this just involves creating the resource in Docker. :param helper: The resource helper to use, if one was not provided when this resource definition was created. :param **create_kwargs: Keyword arguments passed to :meth:`.create`. :returns: This definition instance. Useful for creating and setting up a resource in a single step:: volume = VolumeDefinition('volly').setup(helper=docker_helper) """ if self.created: return self.set_helper(helper) self.create(**create_kwargs) return self
python
def setup(self, helper=None, **create_kwargs): """ Setup this resource so that is ready to be used in a test. If the resource has already been created, this call does nothing. For most resources, this just involves creating the resource in Docker. :param helper: The resource helper to use, if one was not provided when this resource definition was created. :param **create_kwargs: Keyword arguments passed to :meth:`.create`. :returns: This definition instance. Useful for creating and setting up a resource in a single step:: volume = VolumeDefinition('volly').setup(helper=docker_helper) """ if self.created: return self.set_helper(helper) self.create(**create_kwargs) return self
[ "def", "setup", "(", "self", ",", "helper", "=", "None", ",", "*", "*", "create_kwargs", ")", ":", "if", "self", ".", "created", ":", "return", "self", ".", "set_helper", "(", "helper", ")", "self", ".", "create", "(", "*", "*", "create_kwargs", ")", "return", "self" ]
Setup this resource so that is ready to be used in a test. If the resource has already been created, this call does nothing. For most resources, this just involves creating the resource in Docker. :param helper: The resource helper to use, if one was not provided when this resource definition was created. :param **create_kwargs: Keyword arguments passed to :meth:`.create`. :returns: This definition instance. Useful for creating and setting up a resource in a single step:: volume = VolumeDefinition('volly').setup(helper=docker_helper)
[ "Setup", "this", "resource", "so", "that", "is", "ready", "to", "be", "used", "in", "a", "test", ".", "If", "the", "resource", "has", "already", "been", "created", "this", "call", "does", "nothing", "." ]
6f10a19b45d4ea1dc3bd0553cc4d0438696c079c
https://github.com/praekeltfoundation/seaworthy/blob/6f10a19b45d4ea1dc3bd0553cc4d0438696c079c/seaworthy/definitions.py#L76-L99
train
praekeltfoundation/seaworthy
seaworthy/definitions.py
_DefinitionBase.as_fixture
def as_fixture(self, name=None): """ A decorator to inject this container into a function as a test fixture. """ if name is None: name = self.name def deco(f): @functools.wraps(f) def wrapper(*args, **kw): with self: kw[name] = self return f(*args, **kw) return wrapper return deco
python
def as_fixture(self, name=None): """ A decorator to inject this container into a function as a test fixture. """ if name is None: name = self.name def deco(f): @functools.wraps(f) def wrapper(*args, **kw): with self: kw[name] = self return f(*args, **kw) return wrapper return deco
[ "def", "as_fixture", "(", "self", ",", "name", "=", "None", ")", ":", "if", "name", "is", "None", ":", "name", "=", "self", ".", "name", "def", "deco", "(", "f", ")", ":", "@", "functools", ".", "wraps", "(", "f", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kw", ")", ":", "with", "self", ":", "kw", "[", "name", "]", "=", "self", "return", "f", "(", "*", "args", ",", "*", "*", "kw", ")", "return", "wrapper", "return", "deco" ]
A decorator to inject this container into a function as a test fixture.
[ "A", "decorator", "to", "inject", "this", "container", "into", "a", "function", "as", "a", "test", "fixture", "." ]
6f10a19b45d4ea1dc3bd0553cc4d0438696c079c
https://github.com/praekeltfoundation/seaworthy/blob/6f10a19b45d4ea1dc3bd0553cc4d0438696c079c/seaworthy/definitions.py#L147-L161
train
praekeltfoundation/seaworthy
seaworthy/definitions.py
ContainerDefinition.setup
def setup(self, helper=None, **run_kwargs): """ Creates the container, starts it, and waits for it to completely start. :param helper: The resource helper to use, if one was not provided when this container definition was created. :param **run_kwargs: Keyword arguments passed to :meth:`.run`. :returns: This container definition instance. Useful for creating and setting up a container in a single step:: con = ContainerDefinition('conny', 'nginx').setup(helper=dh) """ if self.created: return self.set_helper(helper) self.run(**run_kwargs) self.wait_for_start() return self
python
def setup(self, helper=None, **run_kwargs): """ Creates the container, starts it, and waits for it to completely start. :param helper: The resource helper to use, if one was not provided when this container definition was created. :param **run_kwargs: Keyword arguments passed to :meth:`.run`. :returns: This container definition instance. Useful for creating and setting up a container in a single step:: con = ContainerDefinition('conny', 'nginx').setup(helper=dh) """ if self.created: return self.set_helper(helper) self.run(**run_kwargs) self.wait_for_start() return self
[ "def", "setup", "(", "self", ",", "helper", "=", "None", ",", "*", "*", "run_kwargs", ")", ":", "if", "self", ".", "created", ":", "return", "self", ".", "set_helper", "(", "helper", ")", "self", ".", "run", "(", "*", "*", "run_kwargs", ")", "self", ".", "wait_for_start", "(", ")", "return", "self" ]
Creates the container, starts it, and waits for it to completely start. :param helper: The resource helper to use, if one was not provided when this container definition was created. :param **run_kwargs: Keyword arguments passed to :meth:`.run`. :returns: This container definition instance. Useful for creating and setting up a container in a single step:: con = ContainerDefinition('conny', 'nginx').setup(helper=dh)
[ "Creates", "the", "container", "starts", "it", "and", "waits", "for", "it", "to", "completely", "start", "." ]
6f10a19b45d4ea1dc3bd0553cc4d0438696c079c
https://github.com/praekeltfoundation/seaworthy/blob/6f10a19b45d4ea1dc3bd0553cc4d0438696c079c/seaworthy/definitions.py#L246-L267
train
praekeltfoundation/seaworthy
seaworthy/definitions.py
ContainerDefinition.teardown
def teardown(self): """ Stop and remove the container if it exists. """ while self._http_clients: self._http_clients.pop().close() if self.created: self.halt()
python
def teardown(self): """ Stop and remove the container if it exists. """ while self._http_clients: self._http_clients.pop().close() if self.created: self.halt()
[ "def", "teardown", "(", "self", ")", ":", "while", "self", ".", "_http_clients", ":", "self", ".", "_http_clients", ".", "pop", "(", ")", ".", "close", "(", ")", "if", "self", ".", "created", ":", "self", ".", "halt", "(", ")" ]
Stop and remove the container if it exists.
[ "Stop", "and", "remove", "the", "container", "if", "it", "exists", "." ]
6f10a19b45d4ea1dc3bd0553cc4d0438696c079c
https://github.com/praekeltfoundation/seaworthy/blob/6f10a19b45d4ea1dc3bd0553cc4d0438696c079c/seaworthy/definitions.py#L269-L276
train
praekeltfoundation/seaworthy
seaworthy/definitions.py
ContainerDefinition.status
def status(self): """ Get the container's current status from Docker. If the container does not exist (before creation and after removal), the status is ``None``. """ if not self.created: return None self.inner().reload() return self.inner().status
python
def status(self): """ Get the container's current status from Docker. If the container does not exist (before creation and after removal), the status is ``None``. """ if not self.created: return None self.inner().reload() return self.inner().status
[ "def", "status", "(", "self", ")", ":", "if", "not", "self", ".", "created", ":", "return", "None", "self", ".", "inner", "(", ")", ".", "reload", "(", ")", "return", "self", ".", "inner", "(", ")", ".", "status" ]
Get the container's current status from Docker. If the container does not exist (before creation and after removal), the status is ``None``.
[ "Get", "the", "container", "s", "current", "status", "from", "Docker", "." ]
6f10a19b45d4ea1dc3bd0553cc4d0438696c079c
https://github.com/praekeltfoundation/seaworthy/blob/6f10a19b45d4ea1dc3bd0553cc4d0438696c079c/seaworthy/definitions.py#L278-L288
train
praekeltfoundation/seaworthy
seaworthy/definitions.py
ContainerDefinition.stop
def stop(self, timeout=5): """ Stop the container. The container must have been created. :param timeout: Timeout in seconds to wait for the container to stop before sending a ``SIGKILL``. Default: 5 (half the Docker default) """ self.inner().stop(timeout=timeout) self.inner().reload()
python
def stop(self, timeout=5): """ Stop the container. The container must have been created. :param timeout: Timeout in seconds to wait for the container to stop before sending a ``SIGKILL``. Default: 5 (half the Docker default) """ self.inner().stop(timeout=timeout) self.inner().reload()
[ "def", "stop", "(", "self", ",", "timeout", "=", "5", ")", ":", "self", ".", "inner", "(", ")", ".", "stop", "(", "timeout", "=", "timeout", ")", "self", ".", "inner", "(", ")", ".", "reload", "(", ")" ]
Stop the container. The container must have been created. :param timeout: Timeout in seconds to wait for the container to stop before sending a ``SIGKILL``. Default: 5 (half the Docker default)
[ "Stop", "the", "container", ".", "The", "container", "must", "have", "been", "created", "." ]
6f10a19b45d4ea1dc3bd0553cc4d0438696c079c
https://github.com/praekeltfoundation/seaworthy/blob/6f10a19b45d4ea1dc3bd0553cc4d0438696c079c/seaworthy/definitions.py#L297-L306
train
praekeltfoundation/seaworthy
seaworthy/definitions.py
ContainerDefinition.run
def run(self, fetch_image=True, **kwargs): """ Create the container and start it. Similar to ``docker run``. :param fetch_image: Whether to try pull the image if it's not found. The behaviour here is similar to ``docker run`` and this parameter defaults to ``True``. :param **kwargs: Keyword arguments passed to :meth:`.create`. """ self.create(fetch_image=fetch_image, **kwargs) self.start()
python
def run(self, fetch_image=True, **kwargs): """ Create the container and start it. Similar to ``docker run``. :param fetch_image: Whether to try pull the image if it's not found. The behaviour here is similar to ``docker run`` and this parameter defaults to ``True``. :param **kwargs: Keyword arguments passed to :meth:`.create`. """ self.create(fetch_image=fetch_image, **kwargs) self.start()
[ "def", "run", "(", "self", ",", "fetch_image", "=", "True", ",", "*", "*", "kwargs", ")", ":", "self", ".", "create", "(", "fetch_image", "=", "fetch_image", ",", "*", "*", "kwargs", ")", "self", ".", "start", "(", ")" ]
Create the container and start it. Similar to ``docker run``. :param fetch_image: Whether to try pull the image if it's not found. The behaviour here is similar to ``docker run`` and this parameter defaults to ``True``. :param **kwargs: Keyword arguments passed to :meth:`.create`.
[ "Create", "the", "container", "and", "start", "it", ".", "Similar", "to", "docker", "run", "." ]
6f10a19b45d4ea1dc3bd0553cc4d0438696c079c
https://github.com/praekeltfoundation/seaworthy/blob/6f10a19b45d4ea1dc3bd0553cc4d0438696c079c/seaworthy/definitions.py#L308-L319
train
praekeltfoundation/seaworthy
seaworthy/definitions.py
ContainerDefinition.wait_for_start
def wait_for_start(self): """ Wait for the container to start. By default this will wait for the log lines matching the patterns passed in the ``wait_patterns`` parameter of the constructor using an UnorderedMatcher. For more advanced checks for container startup, this method should be overridden. """ if self.wait_matchers: matcher = UnorderedMatcher(*self.wait_matchers) self.wait_for_logs_matching(matcher, timeout=self.wait_timeout)
python
def wait_for_start(self): """ Wait for the container to start. By default this will wait for the log lines matching the patterns passed in the ``wait_patterns`` parameter of the constructor using an UnorderedMatcher. For more advanced checks for container startup, this method should be overridden. """ if self.wait_matchers: matcher = UnorderedMatcher(*self.wait_matchers) self.wait_for_logs_matching(matcher, timeout=self.wait_timeout)
[ "def", "wait_for_start", "(", "self", ")", ":", "if", "self", ".", "wait_matchers", ":", "matcher", "=", "UnorderedMatcher", "(", "*", "self", ".", "wait_matchers", ")", "self", ".", "wait_for_logs_matching", "(", "matcher", ",", "timeout", "=", "self", ".", "wait_timeout", ")" ]
Wait for the container to start. By default this will wait for the log lines matching the patterns passed in the ``wait_patterns`` parameter of the constructor using an UnorderedMatcher. For more advanced checks for container startup, this method should be overridden.
[ "Wait", "for", "the", "container", "to", "start", "." ]
6f10a19b45d4ea1dc3bd0553cc4d0438696c079c
https://github.com/praekeltfoundation/seaworthy/blob/6f10a19b45d4ea1dc3bd0553cc4d0438696c079c/seaworthy/definitions.py#L321-L332
train
praekeltfoundation/seaworthy
seaworthy/definitions.py
ContainerDefinition.get_logs
def get_logs(self, stdout=True, stderr=True, timestamps=False, tail='all', since=None): """ Get container logs. This method does not support streaming, use :meth:`stream_logs` for that. """ return self.inner().logs( stdout=stdout, stderr=stderr, timestamps=timestamps, tail=tail, since=since)
python
def get_logs(self, stdout=True, stderr=True, timestamps=False, tail='all', since=None): """ Get container logs. This method does not support streaming, use :meth:`stream_logs` for that. """ return self.inner().logs( stdout=stdout, stderr=stderr, timestamps=timestamps, tail=tail, since=since)
[ "def", "get_logs", "(", "self", ",", "stdout", "=", "True", ",", "stderr", "=", "True", ",", "timestamps", "=", "False", ",", "tail", "=", "'all'", ",", "since", "=", "None", ")", ":", "return", "self", ".", "inner", "(", ")", ".", "logs", "(", "stdout", "=", "stdout", ",", "stderr", "=", "stderr", ",", "timestamps", "=", "timestamps", ",", "tail", "=", "tail", ",", "since", "=", "since", ")" ]
Get container logs. This method does not support streaming, use :meth:`stream_logs` for that.
[ "Get", "container", "logs", "." ]
6f10a19b45d4ea1dc3bd0553cc4d0438696c079c
https://github.com/praekeltfoundation/seaworthy/blob/6f10a19b45d4ea1dc3bd0553cc4d0438696c079c/seaworthy/definitions.py#L400-L410
train
praekeltfoundation/seaworthy
seaworthy/definitions.py
ContainerDefinition.stream_logs
def stream_logs(self, stdout=True, stderr=True, tail='all', timeout=10.0): """ Stream container output. """ return stream_logs( self.inner(), stdout=stdout, stderr=stderr, tail=tail, timeout=timeout)
python
def stream_logs(self, stdout=True, stderr=True, tail='all', timeout=10.0): """ Stream container output. """ return stream_logs( self.inner(), stdout=stdout, stderr=stderr, tail=tail, timeout=timeout)
[ "def", "stream_logs", "(", "self", ",", "stdout", "=", "True", ",", "stderr", "=", "True", ",", "tail", "=", "'all'", ",", "timeout", "=", "10.0", ")", ":", "return", "stream_logs", "(", "self", ".", "inner", "(", ")", ",", "stdout", "=", "stdout", ",", "stderr", "=", "stderr", ",", "tail", "=", "tail", ",", "timeout", "=", "timeout", ")" ]
Stream container output.
[ "Stream", "container", "output", "." ]
6f10a19b45d4ea1dc3bd0553cc4d0438696c079c
https://github.com/praekeltfoundation/seaworthy/blob/6f10a19b45d4ea1dc3bd0553cc4d0438696c079c/seaworthy/definitions.py#L412-L418
train
praekeltfoundation/seaworthy
seaworthy/definitions.py
ContainerDefinition.wait_for_logs_matching
def wait_for_logs_matching(self, matcher, timeout=10, encoding='utf-8', **logs_kwargs): """ Wait for logs matching the given matcher. """ wait_for_logs_matching( self.inner(), matcher, timeout=timeout, encoding=encoding, **logs_kwargs)
python
def wait_for_logs_matching(self, matcher, timeout=10, encoding='utf-8', **logs_kwargs): """ Wait for logs matching the given matcher. """ wait_for_logs_matching( self.inner(), matcher, timeout=timeout, encoding=encoding, **logs_kwargs)
[ "def", "wait_for_logs_matching", "(", "self", ",", "matcher", ",", "timeout", "=", "10", ",", "encoding", "=", "'utf-8'", ",", "*", "*", "logs_kwargs", ")", ":", "wait_for_logs_matching", "(", "self", ".", "inner", "(", ")", ",", "matcher", ",", "timeout", "=", "timeout", ",", "encoding", "=", "encoding", ",", "*", "*", "logs_kwargs", ")" ]
Wait for logs matching the given matcher.
[ "Wait", "for", "logs", "matching", "the", "given", "matcher", "." ]
6f10a19b45d4ea1dc3bd0553cc4d0438696c079c
https://github.com/praekeltfoundation/seaworthy/blob/6f10a19b45d4ea1dc3bd0553cc4d0438696c079c/seaworthy/definitions.py#L420-L427
train
praekeltfoundation/seaworthy
seaworthy/definitions.py
ContainerDefinition.http_client
def http_client(self, port=None): """ Construct an HTTP client for this container. """ # Local import to avoid potential circularity. from seaworthy.client import ContainerHttpClient client = ContainerHttpClient.for_container(self, container_port=port) self._http_clients.append(client) return client
python
def http_client(self, port=None): """ Construct an HTTP client for this container. """ # Local import to avoid potential circularity. from seaworthy.client import ContainerHttpClient client = ContainerHttpClient.for_container(self, container_port=port) self._http_clients.append(client) return client
[ "def", "http_client", "(", "self", ",", "port", "=", "None", ")", ":", "# Local import to avoid potential circularity.", "from", "seaworthy", ".", "client", "import", "ContainerHttpClient", "client", "=", "ContainerHttpClient", ".", "for_container", "(", "self", ",", "container_port", "=", "port", ")", "self", ".", "_http_clients", ".", "append", "(", "client", ")", "return", "client" ]
Construct an HTTP client for this container.
[ "Construct", "an", "HTTP", "client", "for", "this", "container", "." ]
6f10a19b45d4ea1dc3bd0553cc4d0438696c079c
https://github.com/praekeltfoundation/seaworthy/blob/6f10a19b45d4ea1dc3bd0553cc4d0438696c079c/seaworthy/definitions.py#L429-L437
train
tuomas2/automate
src/automate/traits_fixes.py
_dispatch_change_event
def _dispatch_change_event(self, object, trait_name, old, new, handler): """ Prepare and dispatch a trait change event to a listener. """ # Extract the arguments needed from the handler. args = self.argument_transform(object, trait_name, old, new) # Send a description of the event to the change event tracer. if tnotifier._pre_change_event_tracer is not None: tnotifier._pre_change_event_tracer(object, trait_name, old, new, handler) # Dispatch the event to the listener. from automate.common import SystemNotReady try: self.dispatch(handler, *args) except SystemNotReady: pass except Exception as e: if tnotifier._post_change_event_tracer is not None: tnotifier._post_change_event_tracer(object, trait_name, old, new, handler, exception=e) # This call needs to be made inside the `except` block in case # the handler wants to re-raise the exception. tnotifier.handle_exception(object, trait_name, old, new) else: if tnotifier._post_change_event_tracer is not None: tnotifier._post_change_event_tracer(object, trait_name, old, new, handler, exception=None)
python
def _dispatch_change_event(self, object, trait_name, old, new, handler): """ Prepare and dispatch a trait change event to a listener. """ # Extract the arguments needed from the handler. args = self.argument_transform(object, trait_name, old, new) # Send a description of the event to the change event tracer. if tnotifier._pre_change_event_tracer is not None: tnotifier._pre_change_event_tracer(object, trait_name, old, new, handler) # Dispatch the event to the listener. from automate.common import SystemNotReady try: self.dispatch(handler, *args) except SystemNotReady: pass except Exception as e: if tnotifier._post_change_event_tracer is not None: tnotifier._post_change_event_tracer(object, trait_name, old, new, handler, exception=e) # This call needs to be made inside the `except` block in case # the handler wants to re-raise the exception. tnotifier.handle_exception(object, trait_name, old, new) else: if tnotifier._post_change_event_tracer is not None: tnotifier._post_change_event_tracer(object, trait_name, old, new, handler, exception=None)
[ "def", "_dispatch_change_event", "(", "self", ",", "object", ",", "trait_name", ",", "old", ",", "new", ",", "handler", ")", ":", "# Extract the arguments needed from the handler.", "args", "=", "self", ".", "argument_transform", "(", "object", ",", "trait_name", ",", "old", ",", "new", ")", "# Send a description of the event to the change event tracer.", "if", "tnotifier", ".", "_pre_change_event_tracer", "is", "not", "None", ":", "tnotifier", ".", "_pre_change_event_tracer", "(", "object", ",", "trait_name", ",", "old", ",", "new", ",", "handler", ")", "# Dispatch the event to the listener.", "from", "automate", ".", "common", "import", "SystemNotReady", "try", ":", "self", ".", "dispatch", "(", "handler", ",", "*", "args", ")", "except", "SystemNotReady", ":", "pass", "except", "Exception", "as", "e", ":", "if", "tnotifier", ".", "_post_change_event_tracer", "is", "not", "None", ":", "tnotifier", ".", "_post_change_event_tracer", "(", "object", ",", "trait_name", ",", "old", ",", "new", ",", "handler", ",", "exception", "=", "e", ")", "# This call needs to be made inside the `except` block in case", "# the handler wants to re-raise the exception.", "tnotifier", ".", "handle_exception", "(", "object", ",", "trait_name", ",", "old", ",", "new", ")", "else", ":", "if", "tnotifier", ".", "_post_change_event_tracer", "is", "not", "None", ":", "tnotifier", ".", "_post_change_event_tracer", "(", "object", ",", "trait_name", ",", "old", ",", "new", ",", "handler", ",", "exception", "=", "None", ")" ]
Prepare and dispatch a trait change event to a listener.
[ "Prepare", "and", "dispatch", "a", "trait", "change", "event", "to", "a", "listener", "." ]
d8a8cd03cd0da047e033a2d305f3f260f8c4e017
https://github.com/tuomas2/automate/blob/d8a8cd03cd0da047e033a2d305f3f260f8c4e017/src/automate/traits_fixes.py#L59-L85
train
cfobel/si-prefix
si_prefix/__init__.py
split
def split(value, precision=1): ''' Split `value` into value and "exponent-of-10", where "exponent-of-10" is a multiple of 3. This corresponds to SI prefixes. Returns tuple, where the second value is the "exponent-of-10" and the first value is `value` divided by the "exponent-of-10". Args ---- value : int, float Input value. precision : int Number of digits after decimal place to include. Returns ------- tuple The second value is the "exponent-of-10" and the first value is `value` divided by the "exponent-of-10". Examples -------- .. code-block:: python si_prefix.split(0.04781) -> (47.8, -3) si_prefix.split(4781.123) -> (4.8, 3) See :func:`si_format` for more examples. ''' negative = False digits = precision + 1 if value < 0.: value = -value negative = True elif value == 0.: return 0., 0 expof10 = int(math.log10(value)) if expof10 > 0: expof10 = (expof10 // 3) * 3 else: expof10 = (-expof10 + 3) // 3 * (-3) value *= 10 ** (-expof10) if value >= 1000.: value /= 1000.0 expof10 += 3 elif value >= 100.0: digits -= 2 elif value >= 10.0: digits -= 1 if negative: value *= -1 return value, int(expof10)
python
def split(value, precision=1): ''' Split `value` into value and "exponent-of-10", where "exponent-of-10" is a multiple of 3. This corresponds to SI prefixes. Returns tuple, where the second value is the "exponent-of-10" and the first value is `value` divided by the "exponent-of-10". Args ---- value : int, float Input value. precision : int Number of digits after decimal place to include. Returns ------- tuple The second value is the "exponent-of-10" and the first value is `value` divided by the "exponent-of-10". Examples -------- .. code-block:: python si_prefix.split(0.04781) -> (47.8, -3) si_prefix.split(4781.123) -> (4.8, 3) See :func:`si_format` for more examples. ''' negative = False digits = precision + 1 if value < 0.: value = -value negative = True elif value == 0.: return 0., 0 expof10 = int(math.log10(value)) if expof10 > 0: expof10 = (expof10 // 3) * 3 else: expof10 = (-expof10 + 3) // 3 * (-3) value *= 10 ** (-expof10) if value >= 1000.: value /= 1000.0 expof10 += 3 elif value >= 100.0: digits -= 2 elif value >= 10.0: digits -= 1 if negative: value *= -1 return value, int(expof10)
[ "def", "split", "(", "value", ",", "precision", "=", "1", ")", ":", "negative", "=", "False", "digits", "=", "precision", "+", "1", "if", "value", "<", "0.", ":", "value", "=", "-", "value", "negative", "=", "True", "elif", "value", "==", "0.", ":", "return", "0.", ",", "0", "expof10", "=", "int", "(", "math", ".", "log10", "(", "value", ")", ")", "if", "expof10", ">", "0", ":", "expof10", "=", "(", "expof10", "//", "3", ")", "*", "3", "else", ":", "expof10", "=", "(", "-", "expof10", "+", "3", ")", "//", "3", "*", "(", "-", "3", ")", "value", "*=", "10", "**", "(", "-", "expof10", ")", "if", "value", ">=", "1000.", ":", "value", "/=", "1000.0", "expof10", "+=", "3", "elif", "value", ">=", "100.0", ":", "digits", "-=", "2", "elif", "value", ">=", "10.0", ":", "digits", "-=", "1", "if", "negative", ":", "value", "*=", "-", "1", "return", "value", ",", "int", "(", "expof10", ")" ]
Split `value` into value and "exponent-of-10", where "exponent-of-10" is a multiple of 3. This corresponds to SI prefixes. Returns tuple, where the second value is the "exponent-of-10" and the first value is `value` divided by the "exponent-of-10". Args ---- value : int, float Input value. precision : int Number of digits after decimal place to include. Returns ------- tuple The second value is the "exponent-of-10" and the first value is `value` divided by the "exponent-of-10". Examples -------- .. code-block:: python si_prefix.split(0.04781) -> (47.8, -3) si_prefix.split(4781.123) -> (4.8, 3) See :func:`si_format` for more examples.
[ "Split", "value", "into", "value", "and", "exponent", "-", "of", "-", "10", "where", "exponent", "-", "of", "-", "10", "is", "a", "multiple", "of", "3", ".", "This", "corresponds", "to", "SI", "prefixes", "." ]
274fdf47f65d87d0b7a2e3c80f267db63d042c59
https://github.com/cfobel/si-prefix/blob/274fdf47f65d87d0b7a2e3c80f267db63d042c59/si_prefix/__init__.py#L47-L106
train