text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def merge(self, other, merge_body=True): """ Default merge method. Args: other: another MujocoXML instance raises XML error if @other is not a MujocoXML instance. merges <worldbody/>, <actuator/> and <asset/> of @other into @self merge_body: True if merging child bodies of @other. Defaults to True. """ if not isinstance(other, MujocoXML): raise XMLError("{} is not a MujocoXML instance.".format(type(other))) if merge_body: for body in other.worldbody: self.worldbody.append(body) self.merge_asset(other) for one_actuator in other.actuator: self.actuator.append(one_actuator) for one_equality in other.equality: self.equality.append(one_equality) for one_contact in other.contact: self.contact.append(one_contact) for one_default in other.default: self.default.append(one_default)
[ "def", "merge", "(", "self", ",", "other", ",", "merge_body", "=", "True", ")", ":", "if", "not", "isinstance", "(", "other", ",", "MujocoXML", ")", ":", "raise", "XMLError", "(", "\"{} is not a MujocoXML instance.\"", ".", "format", "(", "type", "(", "other", ")", ")", ")", "if", "merge_body", ":", "for", "body", "in", "other", ".", "worldbody", ":", "self", ".", "worldbody", ".", "append", "(", "body", ")", "self", ".", "merge_asset", "(", "other", ")", "for", "one_actuator", "in", "other", ".", "actuator", ":", "self", ".", "actuator", ".", "append", "(", "one_actuator", ")", "for", "one_equality", "in", "other", ".", "equality", ":", "self", ".", "equality", ".", "append", "(", "one_equality", ")", "for", "one_contact", "in", "other", ".", "contact", ":", "self", ".", "contact", ".", "append", "(", "one_contact", ")", "for", "one_default", "in", "other", ".", "default", ":", "self", ".", "default", ".", "append", "(", "one_default", ")" ]
41.333333
12.5
def _subspan(self, s, span, nextspan): """Recursively subdivide spans based on a series of rules.""" text = s[span[0]:span[1]] lowertext = text.lower() # Skip if only a single character or a split sequence if span[1] - span[0] < 2 or text in self.SPLIT or text in self.SPLIT_END_WORD or text in self.SPLIT_START_WORD or lowertext in self.NO_SPLIT: return [span] # Skip if it looks like URL if text.startswith('http://') or text.startswith('ftp://') or text.startswith('www.'): return [span] # Split full stop at end of final token (allow certain characters to follow) unless ellipsis if self.split_last_stop and nextspan is None and text not in self.NO_SPLIT_STOP and not text[-3:] == '...': if text[-1] == '.': return self._split_span(span, -1) ind = text.rfind('.') if ind > -1 and all(t in '\'‘’"“”)]}' for t in text[ind + 1:]): return self._split_span(span, ind, 1) # Split off certain sequences at the end of a word for spl in self.SPLIT_END_WORD: if text.endswith(spl) and len(text) > len(spl) and text[-len(spl) - 1].isalpha(): return self._split_span(span, -len(spl), 0) # Split off certain sequences at the start of a word for spl in self.SPLIT_START_WORD: if text.startswith(spl) and len(text) > len(spl) and text[-len(spl) - 1].isalpha(): return self._split_span(span, len(spl), 0) # Split around certain sequences for spl in self.SPLIT: ind = text.find(spl) if ind > -1: return self._split_span(span, ind, len(spl)) # Split around certain sequences unless followed by a digit for spl in self.SPLIT_NO_DIGIT: ind = text.rfind(spl) if ind > -1 and (len(text) <= ind + len(spl) or not text[ind + len(spl)].isdigit()): return self._split_span(span, ind, len(spl)) # Characters to split around, but with exceptions for i, char in enumerate(text): if char == '-': before = lowertext[:i] after = lowertext[i+1:] # By default we split on hyphens split = True if before in self.NO_SPLIT_PREFIX or after in self.NO_SPLIT_SUFFIX: split = False # Don't split if prefix or suffix in list elif not before.strip(self.NO_SPLIT_CHARS) or not after.strip(self.NO_SPLIT_CHARS): split = False # Don't split if prefix or suffix entirely consist of certain characters if split: return self._split_span(span, i, 1) # Split contraction words for contraction in self.CONTRACTIONS: if lowertext == contraction[0]: return self._split_span(span, contraction[1]) return [span]
[ "def", "_subspan", "(", "self", ",", "s", ",", "span", ",", "nextspan", ")", ":", "text", "=", "s", "[", "span", "[", "0", "]", ":", "span", "[", "1", "]", "]", "lowertext", "=", "text", ".", "lower", "(", ")", "# Skip if only a single character or a split sequence", "if", "span", "[", "1", "]", "-", "span", "[", "0", "]", "<", "2", "or", "text", "in", "self", ".", "SPLIT", "or", "text", "in", "self", ".", "SPLIT_END_WORD", "or", "text", "in", "self", ".", "SPLIT_START_WORD", "or", "lowertext", "in", "self", ".", "NO_SPLIT", ":", "return", "[", "span", "]", "# Skip if it looks like URL", "if", "text", ".", "startswith", "(", "'http://'", ")", "or", "text", ".", "startswith", "(", "'ftp://'", ")", "or", "text", ".", "startswith", "(", "'www.'", ")", ":", "return", "[", "span", "]", "# Split full stop at end of final token (allow certain characters to follow) unless ellipsis", "if", "self", ".", "split_last_stop", "and", "nextspan", "is", "None", "and", "text", "not", "in", "self", ".", "NO_SPLIT_STOP", "and", "not", "text", "[", "-", "3", ":", "]", "==", "'...'", ":", "if", "text", "[", "-", "1", "]", "==", "'.'", ":", "return", "self", ".", "_split_span", "(", "span", ",", "-", "1", ")", "ind", "=", "text", ".", "rfind", "(", "'.'", ")", "if", "ind", ">", "-", "1", "and", "all", "(", "t", "in", "'\\'‘’\"“”)]}' for t i", " te", "t", "in", " + 1", ":", "]):", "", "", "", "", "", "", "return", "self", ".", "_split_span", "(", "span", ",", "ind", ",", "1", ")", "# Split off certain sequences at the end of a word", "for", "spl", "in", "self", ".", "SPLIT_END_WORD", ":", "if", "text", ".", "endswith", "(", "spl", ")", "and", "len", "(", "text", ")", ">", "len", "(", "spl", ")", "and", "text", "[", "-", "len", "(", "spl", ")", "-", "1", "]", ".", "isalpha", "(", ")", ":", "return", "self", ".", "_split_span", "(", "span", ",", "-", "len", "(", "spl", ")", ",", "0", ")", "# Split off certain sequences at the start of a word", "for", "spl", "in", "self", ".", "SPLIT_START_WORD", ":", "if", "text", ".", "startswith", "(", "spl", ")", "and", "len", "(", "text", ")", ">", "len", "(", "spl", ")", "and", "text", "[", "-", "len", "(", "spl", ")", "-", "1", "]", ".", "isalpha", "(", ")", ":", "return", "self", ".", "_split_span", "(", "span", ",", "len", "(", "spl", ")", ",", "0", ")", "# Split around certain sequences", "for", "spl", "in", "self", ".", "SPLIT", ":", "ind", "=", "text", ".", "find", "(", "spl", ")", "if", "ind", ">", "-", "1", ":", "return", "self", ".", "_split_span", "(", "span", ",", "ind", ",", "len", "(", "spl", ")", ")", "# Split around certain sequences unless followed by a digit", "for", "spl", "in", "self", ".", "SPLIT_NO_DIGIT", ":", "ind", "=", "text", ".", "rfind", "(", "spl", ")", "if", "ind", ">", "-", "1", "and", "(", "len", "(", "text", ")", "<=", "ind", "+", "len", "(", "spl", ")", "or", "not", "text", "[", "ind", "+", "len", "(", "spl", ")", "]", ".", "isdigit", "(", ")", ")", ":", "return", "self", ".", "_split_span", "(", "span", ",", "ind", ",", "len", "(", "spl", ")", ")", "# Characters to split around, but with exceptions", "for", "i", ",", "char", "in", "enumerate", "(", "text", ")", ":", "if", "char", "==", "'-'", ":", "before", "=", "lowertext", "[", ":", "i", "]", "after", "=", "lowertext", "[", "i", "+", "1", ":", "]", "# By default we split on hyphens", "split", "=", "True", "if", "before", "in", "self", ".", "NO_SPLIT_PREFIX", "or", "after", "in", "self", ".", "NO_SPLIT_SUFFIX", ":", "split", "=", "False", "# Don't split if prefix or suffix in list", "elif", "not", "before", ".", "strip", "(", "self", ".", "NO_SPLIT_CHARS", ")", "or", "not", "after", ".", "strip", "(", "self", ".", "NO_SPLIT_CHARS", ")", ":", "split", "=", "False", "# Don't split if prefix or suffix entirely consist of certain characters", "if", "split", ":", "return", "self", ".", "_split_span", "(", "span", ",", "i", ",", "1", ")", "# Split contraction words", "for", "contraction", "in", "self", ".", "CONTRACTIONS", ":", "if", "lowertext", "==", "contraction", "[", "0", "]", ":", "return", "self", ".", "_split_span", "(", "span", ",", "contraction", "[", "1", "]", ")", "return", "[", "span", "]" ]
47.177419
24.16129
def CHOLESKY(A, B, method='scipy'): """Solve linear system `AX=B` using CHOLESKY method. :param A: an input Hermitian matrix :param B: an array :param str method: a choice of method in [numpy, scipy, numpy_solver] * `numpy_solver` relies entirely on numpy.solver (no cholesky decomposition) * `numpy` relies on the numpy.linalg.cholesky for the decomposition and numpy.linalg.solve for the inversion. * `scipy` uses scipy.linalg.cholesky for the decomposition and scipy.linalg.cho_solve for the inversion. .. rubric:: Description When a matrix is square and Hermitian (symmetric with lower part being the complex conjugate of the upper one), then the usual triangular factorization takes on the special form: .. math:: A = R R^H where :math:`R` is a lower triangular matrix with nonzero real principal diagonal element. The input matrix can be made of complex data. Then, the inversion to find :math:`x` is made as follows: .. math:: Ry = B and .. math:: Rx = y .. doctest:: >>> import numpy >>> from spectrum import CHOLESKY >>> A = numpy.array([[ 2.0+0.j , 0.5-0.5j, -0.2+0.1j], ... [ 0.5+0.5j, 1.0+0.j , 0.3-0.2j], ... [-0.2-0.1j, 0.3+0.2j, 0.5+0.j ]]) >>> B = numpy.array([ 1.0+3.j , 2.0-1.j , 0.5+0.8j]) >>> CHOLESKY(A, B) array([ 0.95945946+5.25675676j, 4.41891892-7.04054054j, -5.13513514+6.35135135j]) """ if method == 'numpy_solver': X = _numpy_solver(A,B) return X elif method == 'numpy': X, _L = _numpy_cholesky(A, B) return X elif method == 'scipy': import scipy.linalg L = scipy.linalg.cholesky(A) X = scipy.linalg.cho_solve((L, False), B) else: raise ValueError('method must be numpy_solver, numpy_cholesky or cholesky_inplace') return X
[ "def", "CHOLESKY", "(", "A", ",", "B", ",", "method", "=", "'scipy'", ")", ":", "if", "method", "==", "'numpy_solver'", ":", "X", "=", "_numpy_solver", "(", "A", ",", "B", ")", "return", "X", "elif", "method", "==", "'numpy'", ":", "X", ",", "_L", "=", "_numpy_cholesky", "(", "A", ",", "B", ")", "return", "X", "elif", "method", "==", "'scipy'", ":", "import", "scipy", ".", "linalg", "L", "=", "scipy", ".", "linalg", ".", "cholesky", "(", "A", ")", "X", "=", "scipy", ".", "linalg", ".", "cho_solve", "(", "(", "L", ",", "False", ")", ",", "B", ")", "else", ":", "raise", "ValueError", "(", "'method must be numpy_solver, numpy_cholesky or cholesky_inplace'", ")", "return", "X" ]
33.315789
22.701754
def load(abspath, default=None, enable_verbose=True): """Load Json from file. If file are not exists, returns ``default``. :param abspath: file path. use absolute path as much as you can. extension has to be ``.json`` or ``.gz`` (for compressed Json). :type abspath: string :param default: default ``dict()``, if ``abspath`` not exists, return the default Python object instead. :param enable_verbose: default ``True``, help-message-display trigger. :type enable_verbose: boolean Usage:: >>> from dataIO import js >>> js.load("test.json") # if you have a json file Load from 'test.json' ... Complete! Elapse 0.000432 sec. {'a': 1, 'b': 2} **中文文档** 从Json文件中读取数据 :param abspath: Json文件绝对路径, 扩展名需为 ``.json`` 或 ``.gz``, 其中 ``.gz`` 是被压缩后的Json文件 :type abspath: ``字符串`` :param default: 默认 ``dict()``, 如果文件路径不存在, 则会返回指定的默认值 :param enable_verbose: 默认 ``True``, 信息提示的开关, 批处理时建议关闭 :type enable_verbose: ``布尔值`` """ if default is None: default = dict() prt("\nLoad from '%s' ..." % abspath, enable_verbose) abspath = lower_ext(str(abspath)) is_json = is_json_file(abspath) if not os.path.exists(abspath): prt(" File not found, use default value: %r" % default, enable_verbose) return default st = time.clock() if is_json: data = json.loads(textfile.read(abspath, encoding="utf-8")) else: data = json.loads(compress.read_gzip(abspath).decode("utf-8")) prt(" Complete! Elapse %.6f sec." % (time.clock() - st), enable_verbose) return data
[ "def", "load", "(", "abspath", ",", "default", "=", "None", ",", "enable_verbose", "=", "True", ")", ":", "if", "default", "is", "None", ":", "default", "=", "dict", "(", ")", "prt", "(", "\"\\nLoad from '%s' ...\"", "%", "abspath", ",", "enable_verbose", ")", "abspath", "=", "lower_ext", "(", "str", "(", "abspath", ")", ")", "is_json", "=", "is_json_file", "(", "abspath", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "abspath", ")", ":", "prt", "(", "\" File not found, use default value: %r\"", "%", "default", ",", "enable_verbose", ")", "return", "default", "st", "=", "time", ".", "clock", "(", ")", "if", "is_json", ":", "data", "=", "json", ".", "loads", "(", "textfile", ".", "read", "(", "abspath", ",", "encoding", "=", "\"utf-8\"", ")", ")", "else", ":", "data", "=", "json", ".", "loads", "(", "compress", ".", "read_gzip", "(", "abspath", ")", ".", "decode", "(", "\"utf-8\"", ")", ")", "prt", "(", "\" Complete! Elapse %.6f sec.\"", "%", "(", "time", ".", "clock", "(", ")", "-", "st", ")", ",", "enable_verbose", ")", "return", "data" ]
29.236364
23.654545
def fix_grpc_import(): ''' Snippet to fix the gRPC import path ''' with open(GARUDA_GRPC_PATH, 'r') as f: filedata = f.read() filedata = filedata.replace( 'import garuda_pb2 as garuda__pb2', f'import {GARUDA_DIR}.garuda_pb2 as garuda__pb2') with open(GARUDA_GRPC_PATH, 'w') as f: f.write(filedata)
[ "def", "fix_grpc_import", "(", ")", ":", "with", "open", "(", "GARUDA_GRPC_PATH", ",", "'r'", ")", "as", "f", ":", "filedata", "=", "f", ".", "read", "(", ")", "filedata", "=", "filedata", ".", "replace", "(", "'import garuda_pb2 as garuda__pb2'", ",", "f'import {GARUDA_DIR}.garuda_pb2 as garuda__pb2'", ")", "with", "open", "(", "GARUDA_GRPC_PATH", ",", "'w'", ")", "as", "f", ":", "f", ".", "write", "(", "filedata", ")" ]
31.181818
13.181818
def move_tab(self, index_from, index_to): """Move tab.""" client = self.clients.pop(index_from) self.clients.insert(index_to, client)
[ "def", "move_tab", "(", "self", ",", "index_from", ",", "index_to", ")", ":", "client", "=", "self", ".", "clients", ".", "pop", "(", "index_from", ")", "self", ".", "clients", ".", "insert", "(", "index_to", ",", "client", ")" ]
39.25
3.25
def _send_ack(self, transaction): """ Sends an ACK message for the request. :param transaction: the transaction that owns the request """ ack = Message() ack.type = defines.Types['ACK'] # TODO handle mutex on transaction if not transaction.request.acknowledged and transaction.request.type == defines.Types["CON"]: ack = self._messageLayer.send_empty(transaction, transaction.request, ack) self.send_datagram(ack)
[ "def", "_send_ack", "(", "self", ",", "transaction", ")", ":", "ack", "=", "Message", "(", ")", "ack", ".", "type", "=", "defines", ".", "Types", "[", "'ACK'", "]", "# TODO handle mutex on transaction", "if", "not", "transaction", ".", "request", ".", "acknowledged", "and", "transaction", ".", "request", ".", "type", "==", "defines", ".", "Types", "[", "\"CON\"", "]", ":", "ack", "=", "self", ".", "_messageLayer", ".", "send_empty", "(", "transaction", ",", "transaction", ".", "request", ",", "ack", ")", "self", ".", "send_datagram", "(", "ack", ")" ]
37.769231
19.153846
def handle(self, *args, **options): """ Lists all the items in a container to stdout. """ self._connection = Auth()._get_connection() if len(args) == 0: containers = self._connection.list_containers() if not containers: print("No containers were found for this account.") elif len(args) == 1: containers = self._connection.list_container_object_names(args[0]) if not containers: print("No matching container found.") else: raise CommandError("Pass one and only one [container_name] as an argument") for container in containers: print(container)
[ "def", "handle", "(", "self", ",", "*", "args", ",", "*", "*", "options", ")", ":", "self", ".", "_connection", "=", "Auth", "(", ")", ".", "_get_connection", "(", ")", "if", "len", "(", "args", ")", "==", "0", ":", "containers", "=", "self", ".", "_connection", ".", "list_containers", "(", ")", "if", "not", "containers", ":", "print", "(", "\"No containers were found for this account.\"", ")", "elif", "len", "(", "args", ")", "==", "1", ":", "containers", "=", "self", ".", "_connection", ".", "list_container_object_names", "(", "args", "[", "0", "]", ")", "if", "not", "containers", ":", "print", "(", "\"No matching container found.\"", ")", "else", ":", "raise", "CommandError", "(", "\"Pass one and only one [container_name] as an argument\"", ")", "for", "container", "in", "containers", ":", "print", "(", "container", ")" ]
36.631579
18
def ancestors(self): """Returns list of ancestor task specs based on inputs""" results = [] def recursive_find_ancestors(task, stack): for input in task.inputs: if input not in stack: stack.append(input) recursive_find_ancestors(input, stack) recursive_find_ancestors(self, results) return results
[ "def", "ancestors", "(", "self", ")", ":", "results", "=", "[", "]", "def", "recursive_find_ancestors", "(", "task", ",", "stack", ")", ":", "for", "input", "in", "task", ".", "inputs", ":", "if", "input", "not", "in", "stack", ":", "stack", ".", "append", "(", "input", ")", "recursive_find_ancestors", "(", "input", ",", "stack", ")", "recursive_find_ancestors", "(", "self", ",", "results", ")", "return", "results" ]
33
14.916667
def run_genesippr(self): """ Run GeneSippr on each of the samples """ from pathlib import Path home = str(Path.home()) logging.info('GeneSippr') # These unfortunate hard coded paths appear to be necessary miniconda_path = os.path.join(home, 'miniconda3') miniconda_path = miniconda_path if os.path.isdir(miniconda_path) else os.path.join(home, 'miniconda') logging.debug(miniconda_path) activate = 'source {mp}/bin/activate {mp}/envs/sipprverse'.format(mp=miniconda_path) sippr_path = '{mp}/envs/sipprverse/bin/sippr.py'.format(mp=miniconda_path) for sample in self.metadata: logging.info(sample.name) # Run the pipeline. Check to make sure that the serosippr report, which is created last doesn't exist if not os.path.isfile(os.path.join(sample.genesippr_dir, 'reports', 'genesippr.csv')): cmd = 'python {py_path} -o {outpath} -s {seqpath} -r {refpath} -F'\ .format(py_path=sippr_path, outpath=sample.genesippr_dir, seqpath=sample.genesippr_dir, refpath=self.referencefilepath ) logging.critical(cmd) # Create another shell script to execute within the PlasmidExtractor conda environment template = "#!/bin/bash\n{activate} && {cmd}".format(activate=activate, cmd=cmd) genesippr_script = os.path.join(sample.genesippr_dir, 'run_genesippr.sh') with open(genesippr_script, 'w+') as file: file.write(template) # Modify the permissions of the script to allow it to be run on the node self.make_executable(genesippr_script) # Run shell script os.system('/bin/bash {}'.format(genesippr_script))
[ "def", "run_genesippr", "(", "self", ")", ":", "from", "pathlib", "import", "Path", "home", "=", "str", "(", "Path", ".", "home", "(", ")", ")", "logging", ".", "info", "(", "'GeneSippr'", ")", "# These unfortunate hard coded paths appear to be necessary", "miniconda_path", "=", "os", ".", "path", ".", "join", "(", "home", ",", "'miniconda3'", ")", "miniconda_path", "=", "miniconda_path", "if", "os", ".", "path", ".", "isdir", "(", "miniconda_path", ")", "else", "os", ".", "path", ".", "join", "(", "home", ",", "'miniconda'", ")", "logging", ".", "debug", "(", "miniconda_path", ")", "activate", "=", "'source {mp}/bin/activate {mp}/envs/sipprverse'", ".", "format", "(", "mp", "=", "miniconda_path", ")", "sippr_path", "=", "'{mp}/envs/sipprverse/bin/sippr.py'", ".", "format", "(", "mp", "=", "miniconda_path", ")", "for", "sample", "in", "self", ".", "metadata", ":", "logging", ".", "info", "(", "sample", ".", "name", ")", "# Run the pipeline. Check to make sure that the serosippr report, which is created last doesn't exist", "if", "not", "os", ".", "path", ".", "isfile", "(", "os", ".", "path", ".", "join", "(", "sample", ".", "genesippr_dir", ",", "'reports'", ",", "'genesippr.csv'", ")", ")", ":", "cmd", "=", "'python {py_path} -o {outpath} -s {seqpath} -r {refpath} -F'", ".", "format", "(", "py_path", "=", "sippr_path", ",", "outpath", "=", "sample", ".", "genesippr_dir", ",", "seqpath", "=", "sample", ".", "genesippr_dir", ",", "refpath", "=", "self", ".", "referencefilepath", ")", "logging", ".", "critical", "(", "cmd", ")", "# Create another shell script to execute within the PlasmidExtractor conda environment", "template", "=", "\"#!/bin/bash\\n{activate} && {cmd}\"", ".", "format", "(", "activate", "=", "activate", ",", "cmd", "=", "cmd", ")", "genesippr_script", "=", "os", ".", "path", ".", "join", "(", "sample", ".", "genesippr_dir", ",", "'run_genesippr.sh'", ")", "with", "open", "(", "genesippr_script", ",", "'w+'", ")", "as", "file", ":", "file", ".", "write", "(", "template", ")", "# Modify the permissions of the script to allow it to be run on the node", "self", ".", "make_executable", "(", "genesippr_script", ")", "# Run shell script", "os", ".", "system", "(", "'/bin/bash {}'", ".", "format", "(", "genesippr_script", ")", ")" ]
56.485714
24.428571
def save(self, f): """Save pickled model to file.""" return pickle.dump((self.perceptron.weights, self.tagdict, self.classes, self.clusters), f, protocol=pickle.HIGHEST_PROTOCOL)
[ "def", "save", "(", "self", ",", "f", ")", ":", "return", "pickle", ".", "dump", "(", "(", "self", ".", "perceptron", ".", "weights", ",", "self", ".", "tagdict", ",", "self", ".", "classes", ",", "self", ".", "clusters", ")", ",", "f", ",", "protocol", "=", "pickle", ".", "HIGHEST_PROTOCOL", ")" ]
64
38.333333
def make_bands(self, ax): """Draw shaded horizontal bands for each plotter.""" y_vals, y_prev, is_zero = [0], None, False prev_color_index = 0 for plotter in self.plotters.values(): for y, *_, color in plotter.iterator(): if self.colors.index(color) < prev_color_index: if not is_zero and y_prev is not None: y_vals.append((y + y_prev) * 0.5) is_zero = True else: is_zero = False prev_color_index = self.colors.index(color) y_prev = y offset = plotter.group_offset # pylint: disable=undefined-loop-variable y_vals.append(y_prev + offset) for idx, (y_start, y_stop) in enumerate(pairwise(y_vals)): ax.axhspan(y_start, y_stop, color="k", alpha=0.1 * (idx % 2)) return ax
[ "def", "make_bands", "(", "self", ",", "ax", ")", ":", "y_vals", ",", "y_prev", ",", "is_zero", "=", "[", "0", "]", ",", "None", ",", "False", "prev_color_index", "=", "0", "for", "plotter", "in", "self", ".", "plotters", ".", "values", "(", ")", ":", "for", "y", ",", "*", "_", ",", "color", "in", "plotter", ".", "iterator", "(", ")", ":", "if", "self", ".", "colors", ".", "index", "(", "color", ")", "<", "prev_color_index", ":", "if", "not", "is_zero", "and", "y_prev", "is", "not", "None", ":", "y_vals", ".", "append", "(", "(", "y", "+", "y_prev", ")", "*", "0.5", ")", "is_zero", "=", "True", "else", ":", "is_zero", "=", "False", "prev_color_index", "=", "self", ".", "colors", ".", "index", "(", "color", ")", "y_prev", "=", "y", "offset", "=", "plotter", ".", "group_offset", "# pylint: disable=undefined-loop-variable", "y_vals", ".", "append", "(", "y_prev", "+", "offset", ")", "for", "idx", ",", "(", "y_start", ",", "y_stop", ")", "in", "enumerate", "(", "pairwise", "(", "y_vals", ")", ")", ":", "ax", ".", "axhspan", "(", "y_start", ",", "y_stop", ",", "color", "=", "\"k\"", ",", "alpha", "=", "0.1", "*", "(", "idx", "%", "2", ")", ")", "return", "ax" ]
42.428571
17.857143
def get(self, floating_ip_id): """Fetches the floating IP. :returns: FloatingIp object corresponding to floating_ip_id """ fip = self.client.show_floatingip(floating_ip_id).get('floatingip') self._set_instance_info(fip) return FloatingIp(fip)
[ "def", "get", "(", "self", ",", "floating_ip_id", ")", ":", "fip", "=", "self", ".", "client", ".", "show_floatingip", "(", "floating_ip_id", ")", ".", "get", "(", "'floatingip'", ")", "self", ".", "_set_instance_info", "(", "fip", ")", "return", "FloatingIp", "(", "fip", ")" ]
35.5
15.75
def env_string(name, required=False, default=empty): """Pulls an environment variable out of the environment returning it as a string. If not present in the environment and no default is specified, an empty string is returned. :param name: The name of the environment variable be pulled :type name: str :param required: Whether the environment variable is required. If ``True`` and the variable is not present, a ``KeyError`` is raised. :type required: bool :param default: The value to return if the environment variable is not present. (Providing a default alongside setting ``required=True`` will raise a ``ValueError``) :type default: bool """ value = get_env_value(name, default=default, required=required) if value is empty: value = '' return value
[ "def", "env_string", "(", "name", ",", "required", "=", "False", ",", "default", "=", "empty", ")", ":", "value", "=", "get_env_value", "(", "name", ",", "default", "=", "default", ",", "required", "=", "required", ")", "if", "value", "is", "empty", ":", "value", "=", "''", "return", "value" ]
38.52381
23.857143
def prefetch(self, bucket, key): """镜像回源预取文件: 从镜像源站抓取资源到空间中,如果空间中已经存在,则覆盖该资源,具体规格参考 http://developer.qiniu.com/docs/v6/api/reference/rs/prefetch.html Args: bucket: 待获取资源所在的空间 key: 代获取资源文件名 Returns: 一个dict变量,成功返回NULL,失败返回{"error": "<errMsg string>"} 一个ResponseInfo对象 """ resource = entry(bucket, key) return self.__io_do(bucket, 'prefetch', resource)
[ "def", "prefetch", "(", "self", ",", "bucket", ",", "key", ")", ":", "resource", "=", "entry", "(", "bucket", ",", "key", ")", "return", "self", ".", "__io_do", "(", "bucket", ",", "'prefetch'", ",", "resource", ")" ]
28.25
18.3125
def tune(runner, kernel_options, device_options, tuning_options): """ Tune a random sample of sample_fraction fraction in the parameter space :params runner: A runner from kernel_tuner.runners :type runner: kernel_tuner.runner :param kernel_options: A dictionary with all options for the kernel. :type kernel_options: kernel_tuner.interface.Options :param device_options: A dictionary with all options for the device on which the kernel should be tuned. :type device_options: kernel_tuner.interface.Options :param tuning_options: A dictionary with all options regarding the tuning process. :type tuning_options: kernel_tuner.interface.Options :returns: A list of dictionaries for executed kernel configurations and their execution times. And a dictionary that contains a information about the hardware/software environment on which the tuning took place. :rtype: list(dict()), dict() """ tune_params = tuning_options.tune_params #compute cartesian product of all tunable parameters parameter_space = itertools.product(*tune_params.values()) #check for search space restrictions if tuning_options.restrictions is not None: parameter_space = filter(lambda p: util.check_restrictions(tuning_options.restrictions, p, tune_params.keys(), tuning_options.verbose), parameter_space) #reduce parameter space to a random sample using sample_fraction parameter_space = numpy.array(list(parameter_space)) size = len(parameter_space) fraction = int(numpy.ceil(size * float(tuning_options.sample_fraction))) sample_indices = numpy.random.choice(range(size), size=fraction, replace=False) parameter_space = parameter_space[sample_indices] #call the runner results, env = runner.run(parameter_space, kernel_options, tuning_options) return results, env
[ "def", "tune", "(", "runner", ",", "kernel_options", ",", "device_options", ",", "tuning_options", ")", ":", "tune_params", "=", "tuning_options", ".", "tune_params", "#compute cartesian product of all tunable parameters", "parameter_space", "=", "itertools", ".", "product", "(", "*", "tune_params", ".", "values", "(", ")", ")", "#check for search space restrictions", "if", "tuning_options", ".", "restrictions", "is", "not", "None", ":", "parameter_space", "=", "filter", "(", "lambda", "p", ":", "util", ".", "check_restrictions", "(", "tuning_options", ".", "restrictions", ",", "p", ",", "tune_params", ".", "keys", "(", ")", ",", "tuning_options", ".", "verbose", ")", ",", "parameter_space", ")", "#reduce parameter space to a random sample using sample_fraction", "parameter_space", "=", "numpy", ".", "array", "(", "list", "(", "parameter_space", ")", ")", "size", "=", "len", "(", "parameter_space", ")", "fraction", "=", "int", "(", "numpy", ".", "ceil", "(", "size", "*", "float", "(", "tuning_options", ".", "sample_fraction", ")", ")", ")", "sample_indices", "=", "numpy", ".", "random", ".", "choice", "(", "range", "(", "size", ")", ",", "size", "=", "fraction", ",", "replace", "=", "False", ")", "parameter_space", "=", "parameter_space", "[", "sample_indices", "]", "#call the runner", "results", ",", "env", "=", "runner", ".", "run", "(", "parameter_space", ",", "kernel_options", ",", "tuning_options", ")", "return", "results", ",", "env" ]
42.808511
26.553191
def parse_atom_site(self, name, attributes): '''Parse the atom tag attributes. Most atom tags do not have attributes.''' if name == "PDBx:pdbx_PDB_ins_code": assert(not(self.current_atom_site.ATOMResidueiCodeIsNull)) if attributes.get('xsi:nil') == 'true': self.current_atom_site.ATOMResidueiCodeIsNull = True if name == "PDBx:auth_asym_id": assert(not(self.current_atom_site.PDBChainIDIsNull)) if attributes.get('xsi:nil') == 'true': self.current_atom_site.PDBChainIDIsNull = True
[ "def", "parse_atom_site", "(", "self", ",", "name", ",", "attributes", ")", ":", "if", "name", "==", "\"PDBx:pdbx_PDB_ins_code\"", ":", "assert", "(", "not", "(", "self", ".", "current_atom_site", ".", "ATOMResidueiCodeIsNull", ")", ")", "if", "attributes", ".", "get", "(", "'xsi:nil'", ")", "==", "'true'", ":", "self", ".", "current_atom_site", ".", "ATOMResidueiCodeIsNull", "=", "True", "if", "name", "==", "\"PDBx:auth_asym_id\"", ":", "assert", "(", "not", "(", "self", ".", "current_atom_site", ".", "PDBChainIDIsNull", ")", ")", "if", "attributes", ".", "get", "(", "'xsi:nil'", ")", "==", "'true'", ":", "self", ".", "current_atom_site", ".", "PDBChainIDIsNull", "=", "True" ]
57.6
17.8
def generate_anchors( stride=16, sizes=(32, 64, 128, 256, 512), aspect_ratios=(0.5, 1, 2) ): """Generates a matrix of anchor boxes in (x1, y1, x2, y2) format. Anchors are centered on stride / 2, have (approximate) sqrt areas of the specified sizes, and aspect ratios as given. """ return _generate_anchors( stride, np.array(sizes, dtype=np.float) / stride, np.array(aspect_ratios, dtype=np.float), )
[ "def", "generate_anchors", "(", "stride", "=", "16", ",", "sizes", "=", "(", "32", ",", "64", ",", "128", ",", "256", ",", "512", ")", ",", "aspect_ratios", "=", "(", "0.5", ",", "1", ",", "2", ")", ")", ":", "return", "_generate_anchors", "(", "stride", ",", "np", ".", "array", "(", "sizes", ",", "dtype", "=", "np", ".", "float", ")", "/", "stride", ",", "np", ".", "array", "(", "aspect_ratios", ",", "dtype", "=", "np", ".", "float", ")", ",", ")" ]
36.666667
18
def characterize_psf(self): """ Get support size and drift polynomial for current set of params """ # there may be an issue with the support and characterization-- # it might be best to do the characterization with the same support # as the calculated psf. l,u = max(self.zrange[0], self.param_dict['psf-zslab']), self.zrange[1] size_l, drift_l = self.measure_size_drift(l) size_u, drift_u = self.measure_size_drift(u) # must be odd for now or have a better system for getting the center self.support = util.oddify(2*self.support_factor*size_u.astype('int')) self.drift_poly = np.polyfit([l, u], [drift_l, drift_u], 1) if self.cutoffval is not None: psf, vec, size_l = self.psf_slice(l, size=51, zoffset=drift_l, getextent=True) psf, vec, size_u = self.psf_slice(u, size=51, zoffset=drift_u, getextent=True) ss = [np.abs(i).sum(axis=-1) for i in [size_l, size_u]] self.support = util.oddify(util.amax(*ss))
[ "def", "characterize_psf", "(", "self", ")", ":", "# there may be an issue with the support and characterization--", "# it might be best to do the characterization with the same support", "# as the calculated psf.", "l", ",", "u", "=", "max", "(", "self", ".", "zrange", "[", "0", "]", ",", "self", ".", "param_dict", "[", "'psf-zslab'", "]", ")", ",", "self", ".", "zrange", "[", "1", "]", "size_l", ",", "drift_l", "=", "self", ".", "measure_size_drift", "(", "l", ")", "size_u", ",", "drift_u", "=", "self", ".", "measure_size_drift", "(", "u", ")", "# must be odd for now or have a better system for getting the center", "self", ".", "support", "=", "util", ".", "oddify", "(", "2", "*", "self", ".", "support_factor", "*", "size_u", ".", "astype", "(", "'int'", ")", ")", "self", ".", "drift_poly", "=", "np", ".", "polyfit", "(", "[", "l", ",", "u", "]", ",", "[", "drift_l", ",", "drift_u", "]", ",", "1", ")", "if", "self", ".", "cutoffval", "is", "not", "None", ":", "psf", ",", "vec", ",", "size_l", "=", "self", ".", "psf_slice", "(", "l", ",", "size", "=", "51", ",", "zoffset", "=", "drift_l", ",", "getextent", "=", "True", ")", "psf", ",", "vec", ",", "size_u", "=", "self", ".", "psf_slice", "(", "u", ",", "size", "=", "51", ",", "zoffset", "=", "drift_u", ",", "getextent", "=", "True", ")", "ss", "=", "[", "np", ".", "abs", "(", "i", ")", ".", "sum", "(", "axis", "=", "-", "1", ")", "for", "i", "in", "[", "size_l", ",", "size_u", "]", "]", "self", ".", "support", "=", "util", ".", "oddify", "(", "util", ".", "amax", "(", "*", "ss", ")", ")" ]
51.35
27.7
def freeze(proto_dataset_uri): """Convert a proto dataset into a dataset. This step is carried out after all files have been added to the dataset. Freezing a dataset finalizes it with a stamp marking it as frozen. """ proto_dataset = dtoolcore.ProtoDataSet.from_uri( uri=proto_dataset_uri, config_path=CONFIG_PATH ) num_items = len(list(proto_dataset._identifiers())) max_files_limit = int(dtoolcore.utils.get_config_value( "DTOOL_MAX_FILES_LIMIT", CONFIG_PATH, 10000 )) assert isinstance(max_files_limit, int) if num_items > max_files_limit: click.secho( "Too many items ({} > {}) in proto dataset".format( num_items, max_files_limit ), fg="red" ) click.secho("1. Consider splitting the dataset into smaller datasets") click.secho("2. Consider packaging small files using tar") click.secho("3. Increase the limit using the DTOOL_MAX_FILES_LIMIT") click.secho(" environment variable") sys.exit(2) handles = [h for h in proto_dataset._storage_broker.iter_item_handles()] for h in handles: if not valid_handle(h): click.secho( "Invalid item name: {}".format(h), fg="red" ) click.secho("1. Consider renaming the item") click.secho("2. Consider removing the item") sys.exit(3) with click.progressbar(length=len(list(proto_dataset._identifiers())), label="Generating manifest") as progressbar: try: proto_dataset.freeze(progressbar=progressbar) except dtoolcore.storagebroker.DiskStorageBrokerValidationWarning as e: click.secho("") click.secho(str(e), fg="red", nl=False) sys.exit(4) click.secho("Dataset frozen ", nl=False, fg="green") click.secho(proto_dataset_uri)
[ "def", "freeze", "(", "proto_dataset_uri", ")", ":", "proto_dataset", "=", "dtoolcore", ".", "ProtoDataSet", ".", "from_uri", "(", "uri", "=", "proto_dataset_uri", ",", "config_path", "=", "CONFIG_PATH", ")", "num_items", "=", "len", "(", "list", "(", "proto_dataset", ".", "_identifiers", "(", ")", ")", ")", "max_files_limit", "=", "int", "(", "dtoolcore", ".", "utils", ".", "get_config_value", "(", "\"DTOOL_MAX_FILES_LIMIT\"", ",", "CONFIG_PATH", ",", "10000", ")", ")", "assert", "isinstance", "(", "max_files_limit", ",", "int", ")", "if", "num_items", ">", "max_files_limit", ":", "click", ".", "secho", "(", "\"Too many items ({} > {}) in proto dataset\"", ".", "format", "(", "num_items", ",", "max_files_limit", ")", ",", "fg", "=", "\"red\"", ")", "click", ".", "secho", "(", "\"1. Consider splitting the dataset into smaller datasets\"", ")", "click", ".", "secho", "(", "\"2. Consider packaging small files using tar\"", ")", "click", ".", "secho", "(", "\"3. Increase the limit using the DTOOL_MAX_FILES_LIMIT\"", ")", "click", ".", "secho", "(", "\" environment variable\"", ")", "sys", ".", "exit", "(", "2", ")", "handles", "=", "[", "h", "for", "h", "in", "proto_dataset", ".", "_storage_broker", ".", "iter_item_handles", "(", ")", "]", "for", "h", "in", "handles", ":", "if", "not", "valid_handle", "(", "h", ")", ":", "click", ".", "secho", "(", "\"Invalid item name: {}\"", ".", "format", "(", "h", ")", ",", "fg", "=", "\"red\"", ")", "click", ".", "secho", "(", "\"1. Consider renaming the item\"", ")", "click", ".", "secho", "(", "\"2. Consider removing the item\"", ")", "sys", ".", "exit", "(", "3", ")", "with", "click", ".", "progressbar", "(", "length", "=", "len", "(", "list", "(", "proto_dataset", ".", "_identifiers", "(", ")", ")", ")", ",", "label", "=", "\"Generating manifest\"", ")", "as", "progressbar", ":", "try", ":", "proto_dataset", ".", "freeze", "(", "progressbar", "=", "progressbar", ")", "except", "dtoolcore", ".", "storagebroker", ".", "DiskStorageBrokerValidationWarning", "as", "e", ":", "click", ".", "secho", "(", "\"\"", ")", "click", ".", "secho", "(", "str", "(", "e", ")", ",", "fg", "=", "\"red\"", ",", "nl", "=", "False", ")", "sys", ".", "exit", "(", "4", ")", "click", ".", "secho", "(", "\"Dataset frozen \"", ",", "nl", "=", "False", ",", "fg", "=", "\"green\"", ")", "click", ".", "secho", "(", "proto_dataset_uri", ")" ]
35.851852
21.055556
def _exit_session(self): """ Exits session to Hetzner account and returns. """ api = self.api[self.account] response = self._get(api['exit']['GET']['url']) if not Provider._filter_dom(response.text, api['filter']): LOGGER.info('Hetzner => Exit session') else: LOGGER.warning('Hetzner => Unable to exit session') self.session = None return True
[ "def", "_exit_session", "(", "self", ")", ":", "api", "=", "self", ".", "api", "[", "self", ".", "account", "]", "response", "=", "self", ".", "_get", "(", "api", "[", "'exit'", "]", "[", "'GET'", "]", "[", "'url'", "]", ")", "if", "not", "Provider", ".", "_filter_dom", "(", "response", ".", "text", ",", "api", "[", "'filter'", "]", ")", ":", "LOGGER", ".", "info", "(", "'Hetzner => Exit session'", ")", "else", ":", "LOGGER", ".", "warning", "(", "'Hetzner => Unable to exit session'", ")", "self", ".", "session", "=", "None", "return", "True" ]
35.666667
14
def sample_dynamic_posterior(self, inputs, samples, static_sample=None): """Sample the static latent posterior. Args: inputs: A batch of intermediate representations of image frames across all timesteps, of shape [..., batch_size, timesteps, hidden_size]. samples: Number of samples to draw from the latent distribution. static_sample: A tensor sample of the static latent variable `f` of shape [..., batch_size, latent_size]. Only used for the full dynamic posterior formulation. Returns: A tuple of a sample tensor of shape [samples, batch_size, length latent_size], and a MultivariateNormalDiag distribution from which the tensor was sampled, with event shape [latent_size], and batch shape [broadcasted_shape, batch_size, length], where `broadcasted_shape` is the broadcasted sampled shape between the inputs and static sample. Raises: ValueError: If the "full" latent posterior formulation is being used, yet a static latent sample was not provided. """ if self.latent_posterior == "factorized": dist = self.dynamic_encoder(inputs) samples = dist.sample(samples) # (s, N, T, lat) else: # full if static_sample is None: raise ValueError( "The full dynamic posterior requires a static latent sample") dist = self.dynamic_encoder((inputs, static_sample)) samples = dist.sample() # (samples, N, latent) return samples, dist
[ "def", "sample_dynamic_posterior", "(", "self", ",", "inputs", ",", "samples", ",", "static_sample", "=", "None", ")", ":", "if", "self", ".", "latent_posterior", "==", "\"factorized\"", ":", "dist", "=", "self", ".", "dynamic_encoder", "(", "inputs", ")", "samples", "=", "dist", ".", "sample", "(", "samples", ")", "# (s, N, T, lat)", "else", ":", "# full", "if", "static_sample", "is", "None", ":", "raise", "ValueError", "(", "\"The full dynamic posterior requires a static latent sample\"", ")", "dist", "=", "self", ".", "dynamic_encoder", "(", "(", "inputs", ",", "static_sample", ")", ")", "samples", "=", "dist", ".", "sample", "(", ")", "# (samples, N, latent)", "return", "samples", ",", "dist" ]
43.5
22
def get_params(job_inis, **kw): """ Parse one or more INI-style config files. :param job_inis: List of configuration files (or list containing a single zip archive) :param kw: Optionally override some parameters :returns: A dictionary of parameters """ input_zip = None if len(job_inis) == 1 and job_inis[0].endswith('.zip'): input_zip = job_inis[0] job_inis = extract_from_zip( job_inis[0], ['job_hazard.ini', 'job_haz.ini', 'job.ini', 'job_risk.ini']) not_found = [ini for ini in job_inis if not os.path.exists(ini)] if not_found: # something was not found raise IOError('File not found: %s' % not_found[0]) cp = configparser.ConfigParser() cp.read(job_inis) # directory containing the config files we're parsing job_ini = os.path.abspath(job_inis[0]) base_path = decode(os.path.dirname(job_ini)) params = dict(base_path=base_path, inputs={'job_ini': job_ini}) if input_zip: params['inputs']['input_zip'] = os.path.abspath(input_zip) for sect in cp.sections(): _update(params, cp.items(sect), base_path) _update(params, kw.items(), base_path) # override on demand if params['inputs'].get('reqv'): # using pointsource_distance=0 because of the reqv approximation params['pointsource_distance'] = '0' return params
[ "def", "get_params", "(", "job_inis", ",", "*", "*", "kw", ")", ":", "input_zip", "=", "None", "if", "len", "(", "job_inis", ")", "==", "1", "and", "job_inis", "[", "0", "]", ".", "endswith", "(", "'.zip'", ")", ":", "input_zip", "=", "job_inis", "[", "0", "]", "job_inis", "=", "extract_from_zip", "(", "job_inis", "[", "0", "]", ",", "[", "'job_hazard.ini'", ",", "'job_haz.ini'", ",", "'job.ini'", ",", "'job_risk.ini'", "]", ")", "not_found", "=", "[", "ini", "for", "ini", "in", "job_inis", "if", "not", "os", ".", "path", ".", "exists", "(", "ini", ")", "]", "if", "not_found", ":", "# something was not found", "raise", "IOError", "(", "'File not found: %s'", "%", "not_found", "[", "0", "]", ")", "cp", "=", "configparser", ".", "ConfigParser", "(", ")", "cp", ".", "read", "(", "job_inis", ")", "# directory containing the config files we're parsing", "job_ini", "=", "os", ".", "path", ".", "abspath", "(", "job_inis", "[", "0", "]", ")", "base_path", "=", "decode", "(", "os", ".", "path", ".", "dirname", "(", "job_ini", ")", ")", "params", "=", "dict", "(", "base_path", "=", "base_path", ",", "inputs", "=", "{", "'job_ini'", ":", "job_ini", "}", ")", "if", "input_zip", ":", "params", "[", "'inputs'", "]", "[", "'input_zip'", "]", "=", "os", ".", "path", ".", "abspath", "(", "input_zip", ")", "for", "sect", "in", "cp", ".", "sections", "(", ")", ":", "_update", "(", "params", ",", "cp", ".", "items", "(", "sect", ")", ",", "base_path", ")", "_update", "(", "params", ",", "kw", ".", "items", "(", ")", ",", "base_path", ")", "# override on demand", "if", "params", "[", "'inputs'", "]", ".", "get", "(", "'reqv'", ")", ":", "# using pointsource_distance=0 because of the reqv approximation", "params", "[", "'pointsource_distance'", "]", "=", "'0'", "return", "params" ]
34.625
18.475
def set_group_name(group, old_name, new_name): """ Group was renamed. """ for datastore in _get_datastores(): datastore.set_group_name(group, old_name, new_name)
[ "def", "set_group_name", "(", "group", ",", "old_name", ",", "new_name", ")", ":", "for", "datastore", "in", "_get_datastores", "(", ")", ":", "datastore", ".", "set_group_name", "(", "group", ",", "old_name", ",", "new_name", ")" ]
43.5
6.5
def false_positives(links_true, links_pred): """Count the number of False Positives. Returns the number of incorrect predictions of true non-links. (true non- links, but predicted as links). This value is known as the number of False Positives (FP). Parameters ---------- links_true: pandas.MultiIndex, pandas.DataFrame, pandas.Series The true (or actual) links. links_pred: pandas.MultiIndex, pandas.DataFrame, pandas.Series The predicted links. Returns ------- int The number of false positives. """ links_true = _get_multiindex(links_true) links_pred = _get_multiindex(links_pred) return len(links_pred.difference(links_true))
[ "def", "false_positives", "(", "links_true", ",", "links_pred", ")", ":", "links_true", "=", "_get_multiindex", "(", "links_true", ")", "links_pred", "=", "_get_multiindex", "(", "links_pred", ")", "return", "len", "(", "links_pred", ".", "difference", "(", "links_true", ")", ")" ]
27.8
22.84
def build_tree(self): """Bulids the tree with all the fields converted to Elements """ if self.built: return self.doc_root = self.root.element() for key in self.sorted_fields(): if key not in self._fields: continue field = self._fields[key] if field != self.root: if isinstance(field, XmlModel): field.build_tree() if (self.drop_empty and field.drop_empty and len(field.doc_root) == 0): continue self.doc_root.append(field.doc_root) elif isinstance(field, list): # we just allow XmlFields and XmlModels # Also xml as str for memory management for item in field: if isinstance(item, XmlField): ele = item.element() if self.drop_empty and len(ele) == 0: continue self.doc_root.append(ele) elif isinstance(item, XmlModel): item.build_tree() if self.drop_empty and len(item.doc_root) == 0: continue self.doc_root.append(item.doc_root) elif isinstance(item, (six.text_type, six.string_types)): ele = etree.fromstring(clean_xml(item)) self.doc_root.append(ele) item = None elif (field.parent or self.root.name) == self.root.name: ele = field.element() if self.drop_empty and len(ele) == 0 and not ele.text: continue ele = field.element(parent=self.doc_root) else: nodes = [n for n in self.doc_root.iterdescendants( tag=field.parent)] if nodes: ele = field.element() if (self.drop_empty and len(ele) == 0 and not ele.text): continue ele = field.element(parent=nodes[0]) #else: # raise RuntimeError("No parent found!") self.built = True
[ "def", "build_tree", "(", "self", ")", ":", "if", "self", ".", "built", ":", "return", "self", ".", "doc_root", "=", "self", ".", "root", ".", "element", "(", ")", "for", "key", "in", "self", ".", "sorted_fields", "(", ")", ":", "if", "key", "not", "in", "self", ".", "_fields", ":", "continue", "field", "=", "self", ".", "_fields", "[", "key", "]", "if", "field", "!=", "self", ".", "root", ":", "if", "isinstance", "(", "field", ",", "XmlModel", ")", ":", "field", ".", "build_tree", "(", ")", "if", "(", "self", ".", "drop_empty", "and", "field", ".", "drop_empty", "and", "len", "(", "field", ".", "doc_root", ")", "==", "0", ")", ":", "continue", "self", ".", "doc_root", ".", "append", "(", "field", ".", "doc_root", ")", "elif", "isinstance", "(", "field", ",", "list", ")", ":", "# we just allow XmlFields and XmlModels", "# Also xml as str for memory management", "for", "item", "in", "field", ":", "if", "isinstance", "(", "item", ",", "XmlField", ")", ":", "ele", "=", "item", ".", "element", "(", ")", "if", "self", ".", "drop_empty", "and", "len", "(", "ele", ")", "==", "0", ":", "continue", "self", ".", "doc_root", ".", "append", "(", "ele", ")", "elif", "isinstance", "(", "item", ",", "XmlModel", ")", ":", "item", ".", "build_tree", "(", ")", "if", "self", ".", "drop_empty", "and", "len", "(", "item", ".", "doc_root", ")", "==", "0", ":", "continue", "self", ".", "doc_root", ".", "append", "(", "item", ".", "doc_root", ")", "elif", "isinstance", "(", "item", ",", "(", "six", ".", "text_type", ",", "six", ".", "string_types", ")", ")", ":", "ele", "=", "etree", ".", "fromstring", "(", "clean_xml", "(", "item", ")", ")", "self", ".", "doc_root", ".", "append", "(", "ele", ")", "item", "=", "None", "elif", "(", "field", ".", "parent", "or", "self", ".", "root", ".", "name", ")", "==", "self", ".", "root", ".", "name", ":", "ele", "=", "field", ".", "element", "(", ")", "if", "self", ".", "drop_empty", "and", "len", "(", "ele", ")", "==", "0", "and", "not", "ele", ".", "text", ":", "continue", "ele", "=", "field", ".", "element", "(", "parent", "=", "self", ".", "doc_root", ")", "else", ":", "nodes", "=", "[", "n", "for", "n", "in", "self", ".", "doc_root", ".", "iterdescendants", "(", "tag", "=", "field", ".", "parent", ")", "]", "if", "nodes", ":", "ele", "=", "field", ".", "element", "(", ")", "if", "(", "self", ".", "drop_empty", "and", "len", "(", "ele", ")", "==", "0", "and", "not", "ele", ".", "text", ")", ":", "continue", "ele", "=", "field", ".", "element", "(", "parent", "=", "nodes", "[", "0", "]", ")", "#else:", "# raise RuntimeError(\"No parent found!\")", "self", ".", "built", "=", "True" ]
47.392157
14.196078
def process_request(self, request): """ Lazy set user and token """ request.token = get_token(request) request.user = SimpleLazyObject(lambda: get_user(request)) request._dont_enforce_csrf_checks = dont_enforce_csrf_checks(request)
[ "def", "process_request", "(", "self", ",", "request", ")", ":", "request", ".", "token", "=", "get_token", "(", "request", ")", "request", ".", "user", "=", "SimpleLazyObject", "(", "lambda", ":", "get_user", "(", "request", ")", ")", "request", ".", "_dont_enforce_csrf_checks", "=", "dont_enforce_csrf_checks", "(", "request", ")" ]
39
11.285714
def resources_availability(self): """Return the percentage of availability for resources.""" # Flatten the list. availabilities = list( chain( *[org.check_availability() for org in self.organizations] ) ) # Filter out the unknown availabilities = [a for a in availabilities if type(a) is bool] if availabilities: # Trick will work because it's a sum() of booleans. return round(100. * sum(availabilities) / len(availabilities), 2) # if nothing is unavailable, everything is considered OK return 100
[ "def", "resources_availability", "(", "self", ")", ":", "# Flatten the list.", "availabilities", "=", "list", "(", "chain", "(", "*", "[", "org", ".", "check_availability", "(", ")", "for", "org", "in", "self", ".", "organizations", "]", ")", ")", "# Filter out the unknown", "availabilities", "=", "[", "a", "for", "a", "in", "availabilities", "if", "type", "(", "a", ")", "is", "bool", "]", "if", "availabilities", ":", "# Trick will work because it's a sum() of booleans.", "return", "round", "(", "100.", "*", "sum", "(", "availabilities", ")", "/", "len", "(", "availabilities", ")", ",", "2", ")", "# if nothing is unavailable, everything is considered OK", "return", "100" ]
41.333333
20.133333
def get_logs(self): """Gets the log list resulting from a search. return: (osid.logging.LogList) - the log list raise: IllegalState - list already retrieved *compliance: mandatory -- This method must be implemented.* """ if self.retrieved: raise errors.IllegalState('List has already been retrieved.') self.retrieved = True return objects.LogList(self._results, runtime=self._runtime)
[ "def", "get_logs", "(", "self", ")", ":", "if", "self", ".", "retrieved", ":", "raise", "errors", ".", "IllegalState", "(", "'List has already been retrieved.'", ")", "self", ".", "retrieved", "=", "True", "return", "objects", ".", "LogList", "(", "self", ".", "_results", ",", "runtime", "=", "self", ".", "_runtime", ")" ]
37.666667
20
def parse_job_files(self): """Check for job definitions in known zuul files.""" repo_jobs = [] for rel_job_file_path, job_info in self.job_files.items(): LOGGER.debug("Checking for job definitions in %s", rel_job_file_path) jobs = self.parse_job_definitions(rel_job_file_path, job_info) LOGGER.debug("Found %d job definitions in %s", len(jobs), rel_job_file_path) repo_jobs.extend(jobs) if not repo_jobs: LOGGER.info("No job definitions found in repo '%s'", self.repo) else: LOGGER.info( "Found %d job definitions in repo '%s'", len(repo_jobs), self.repo ) # LOGGER.debug(json.dumps(repo_jobs, indent=4)) return repo_jobs
[ "def", "parse_job_files", "(", "self", ")", ":", "repo_jobs", "=", "[", "]", "for", "rel_job_file_path", ",", "job_info", "in", "self", ".", "job_files", ".", "items", "(", ")", ":", "LOGGER", ".", "debug", "(", "\"Checking for job definitions in %s\"", ",", "rel_job_file_path", ")", "jobs", "=", "self", ".", "parse_job_definitions", "(", "rel_job_file_path", ",", "job_info", ")", "LOGGER", ".", "debug", "(", "\"Found %d job definitions in %s\"", ",", "len", "(", "jobs", ")", ",", "rel_job_file_path", ")", "repo_jobs", ".", "extend", "(", "jobs", ")", "if", "not", "repo_jobs", ":", "LOGGER", ".", "info", "(", "\"No job definitions found in repo '%s'\"", ",", "self", ".", "repo", ")", "else", ":", "LOGGER", ".", "info", "(", "\"Found %d job definitions in repo '%s'\"", ",", "len", "(", "repo_jobs", ")", ",", "self", ".", "repo", ")", "# LOGGER.debug(json.dumps(repo_jobs, indent=4))", "return", "repo_jobs" ]
47.875
24
def _find_usage_instances(self): """find usage for DB Instances and related limits""" paginator = self.conn.get_paginator('describe_db_instances') for page in paginator.paginate(): for instance in page['DBInstances']: self.limits['Read replicas per master']._add_current_usage( len(instance['ReadReplicaDBInstanceIdentifiers']), aws_type='AWS::RDS::DBInstance', resource_id=instance['DBInstanceIdentifier'] )
[ "def", "_find_usage_instances", "(", "self", ")", ":", "paginator", "=", "self", ".", "conn", ".", "get_paginator", "(", "'describe_db_instances'", ")", "for", "page", "in", "paginator", ".", "paginate", "(", ")", ":", "for", "instance", "in", "page", "[", "'DBInstances'", "]", ":", "self", ".", "limits", "[", "'Read replicas per master'", "]", ".", "_add_current_usage", "(", "len", "(", "instance", "[", "'ReadReplicaDBInstanceIdentifiers'", "]", ")", ",", "aws_type", "=", "'AWS::RDS::DBInstance'", ",", "resource_id", "=", "instance", "[", "'DBInstanceIdentifier'", "]", ")" ]
52.7
16.9
def from_body(self, param_name, schema): """ A decorator that converts the request body into a function parameter based on the specified schema. :param param_name: The parameter which receives the argument. :param schema: The schema class or instance used to deserialize the request body toa Python object. :return: A function """ schema = schema() if isclass(schema) else schema def decorator(func): @functools.wraps(func) def wrapper(*args, **kwargs): kwargs[param_name] = self.__parse_body(schema) return func(*args, **kwargs) return wrapper return decorator
[ "def", "from_body", "(", "self", ",", "param_name", ",", "schema", ")", ":", "schema", "=", "schema", "(", ")", "if", "isclass", "(", "schema", ")", "else", "schema", "def", "decorator", "(", "func", ")", ":", "@", "functools", ".", "wraps", "(", "func", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "param_name", "]", "=", "self", ".", "__parse_body", "(", "schema", ")", "return", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "wrapper", "return", "decorator" ]
38.166667
21.5
def update_after_verification(self, user): """ Updates a job's state after being verified by a sheriff """ if not self.is_fully_verified(): return classification = 'autoclassified intermittent' already_classified = (JobNote.objects.filter(job=self) .exclude(failure_classification__name=classification) .exists()) if already_classified: # Don't add an autoclassification note if a Human already # classified this job. return JobNote.create_autoclassify_job_note(job=self, user=user)
[ "def", "update_after_verification", "(", "self", ",", "user", ")", ":", "if", "not", "self", ".", "is_fully_verified", "(", ")", ":", "return", "classification", "=", "'autoclassified intermittent'", "already_classified", "=", "(", "JobNote", ".", "objects", ".", "filter", "(", "job", "=", "self", ")", ".", "exclude", "(", "failure_classification__name", "=", "classification", ")", ".", "exists", "(", ")", ")", "if", "already_classified", ":", "# Don't add an autoclassification note if a Human already", "# classified this job.", "return", "JobNote", ".", "create_autoclassify_job_note", "(", "job", "=", "self", ",", "user", "=", "user", ")" ]
37.222222
20.444444
def _merge_layout_objs(obj, subobj): """ Merge layout objects recursively Note: This function mutates the input obj dict, but it does not mutate the subobj dict Parameters ---------- obj: dict dict into which the sub-figure dict will be merged subobj: dict dict that sill be copied and merged into `obj` """ for prop, val in subobj.items(): if isinstance(val, dict) and prop in obj: # recursion _merge_layout_objs(obj[prop], val) elif (isinstance(val, list) and obj.get(prop, None) and isinstance(obj[prop][0], dict)): # append obj[prop].extend(val) else: # init/overwrite obj[prop] = copy.deepcopy(val)
[ "def", "_merge_layout_objs", "(", "obj", ",", "subobj", ")", ":", "for", "prop", ",", "val", "in", "subobj", ".", "items", "(", ")", ":", "if", "isinstance", "(", "val", ",", "dict", ")", "and", "prop", "in", "obj", ":", "# recursion", "_merge_layout_objs", "(", "obj", "[", "prop", "]", ",", "val", ")", "elif", "(", "isinstance", "(", "val", ",", "list", ")", "and", "obj", ".", "get", "(", "prop", ",", "None", ")", "and", "isinstance", "(", "obj", "[", "prop", "]", "[", "0", "]", ",", "dict", ")", ")", ":", "# append", "obj", "[", "prop", "]", ".", "extend", "(", "val", ")", "else", ":", "# init/overwrite", "obj", "[", "prop", "]", "=", "copy", ".", "deepcopy", "(", "val", ")" ]
28.148148
16
def create(cidr_block, instance_tenancy=None, vpc_name=None, enable_dns_support=None, enable_dns_hostnames=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a valid CIDR block, create a VPC. An optional instance_tenancy argument can be provided. If provided, the valid values are 'default' or 'dedicated' An optional vpc_name argument can be provided. Returns {created: true} if the VPC was created and returns {created: False} if the VPC was not created. CLI Example: .. code-block:: bash salt myminion boto_vpc.create '10.0.0.0/24' ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) vpc = conn.create_vpc(cidr_block, instance_tenancy=instance_tenancy) if vpc: log.info('The newly created VPC id is %s', vpc.id) _maybe_set_name_tag(vpc_name, vpc) _maybe_set_tags(tags, vpc) _maybe_set_dns(conn, vpc.id, enable_dns_support, enable_dns_hostnames) _maybe_name_route_table(conn, vpc.id, vpc_name) if vpc_name: _cache_id(vpc_name, vpc.id, region=region, key=key, keyid=keyid, profile=profile) return {'created': True, 'id': vpc.id} else: log.warning('VPC was not created') return {'created': False} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)}
[ "def", "create", "(", "cidr_block", ",", "instance_tenancy", "=", "None", ",", "vpc_name", "=", "None", ",", "enable_dns_support", "=", "None", ",", "enable_dns_hostnames", "=", "None", ",", "tags", "=", "None", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "try", ":", "conn", "=", "_get_conn", "(", "region", "=", "region", ",", "key", "=", "key", ",", "keyid", "=", "keyid", ",", "profile", "=", "profile", ")", "vpc", "=", "conn", ".", "create_vpc", "(", "cidr_block", ",", "instance_tenancy", "=", "instance_tenancy", ")", "if", "vpc", ":", "log", ".", "info", "(", "'The newly created VPC id is %s'", ",", "vpc", ".", "id", ")", "_maybe_set_name_tag", "(", "vpc_name", ",", "vpc", ")", "_maybe_set_tags", "(", "tags", ",", "vpc", ")", "_maybe_set_dns", "(", "conn", ",", "vpc", ".", "id", ",", "enable_dns_support", ",", "enable_dns_hostnames", ")", "_maybe_name_route_table", "(", "conn", ",", "vpc", ".", "id", ",", "vpc_name", ")", "if", "vpc_name", ":", "_cache_id", "(", "vpc_name", ",", "vpc", ".", "id", ",", "region", "=", "region", ",", "key", "=", "key", ",", "keyid", "=", "keyid", ",", "profile", "=", "profile", ")", "return", "{", "'created'", ":", "True", ",", "'id'", ":", "vpc", ".", "id", "}", "else", ":", "log", ".", "warning", "(", "'VPC was not created'", ")", "return", "{", "'created'", ":", "False", "}", "except", "BotoServerError", "as", "e", ":", "return", "{", "'created'", ":", "False", ",", "'error'", ":", "__utils__", "[", "'boto.get_error'", "]", "(", "e", ")", "}" ]
35.904762
23.47619
def line_print(self): """ Return the message as a one-line string. :return: the string representing the message """ inv_types = {v: k for k, v in defines.Types.items()} if self._code is None: self._code = defines.Codes.EMPTY.number msg = "From {source}, To {destination}, {type}-{mid}, {code}-{token}, ["\ .format(source=self._source, destination=self._destination, type=inv_types[self._type], mid=self._mid, code=defines.Codes.LIST[self._code].name, token=self._token) for opt in self._options: msg += "{name}: {value}, ".format(name=opt.name, value=opt.value) msg += "]" if self.payload is not None: if isinstance(self.payload, dict): tmp = list(self.payload.values())[0][0:20] else: tmp = self.payload[0:20] msg += " {payload}...{length} bytes".format(payload=tmp, length=len(self.payload)) else: msg += " No payload" return msg
[ "def", "line_print", "(", "self", ")", ":", "inv_types", "=", "{", "v", ":", "k", "for", "k", ",", "v", "in", "defines", ".", "Types", ".", "items", "(", ")", "}", "if", "self", ".", "_code", "is", "None", ":", "self", ".", "_code", "=", "defines", ".", "Codes", ".", "EMPTY", ".", "number", "msg", "=", "\"From {source}, To {destination}, {type}-{mid}, {code}-{token}, [\"", ".", "format", "(", "source", "=", "self", ".", "_source", ",", "destination", "=", "self", ".", "_destination", ",", "type", "=", "inv_types", "[", "self", ".", "_type", "]", ",", "mid", "=", "self", ".", "_mid", ",", "code", "=", "defines", ".", "Codes", ".", "LIST", "[", "self", ".", "_code", "]", ".", "name", ",", "token", "=", "self", ".", "_token", ")", "for", "opt", "in", "self", ".", "_options", ":", "msg", "+=", "\"{name}: {value}, \"", ".", "format", "(", "name", "=", "opt", ".", "name", ",", "value", "=", "opt", ".", "value", ")", "msg", "+=", "\"]\"", "if", "self", ".", "payload", "is", "not", "None", ":", "if", "isinstance", "(", "self", ".", "payload", ",", "dict", ")", ":", "tmp", "=", "list", "(", "self", ".", "payload", ".", "values", "(", ")", ")", "[", "0", "]", "[", "0", ":", "20", "]", "else", ":", "tmp", "=", "self", ".", "payload", "[", "0", ":", "20", "]", "msg", "+=", "\" {payload}...{length} bytes\"", ".", "format", "(", "payload", "=", "tmp", ",", "length", "=", "len", "(", "self", ".", "payload", ")", ")", "else", ":", "msg", "+=", "\" No payload\"", "return", "msg" ]
40.038462
22.423077
def _add_metadata_element(self, md, subsection, mdtype, mode="mdwrap", **kwargs): """ :param md: Value to pass to the MDWrap/MDRef :param str subsection: Metadata tag to create. See :const:`SubSection.ALLOWED_SUBSECTIONS` :param str mdtype: Value for mdWrap/mdRef @MDTYPE :param str mode: 'mdwrap' or 'mdref' :param str loctype: Required if mode is 'mdref'. LOCTYPE of a mdRef :param str label: Optional. Label of a mdRef :param str otherloctype: Optional. OTHERLOCTYPE of a mdRef. :param str othermdtype: Optional. OTHERMDTYPE of a mdWrap. """ # HELP how handle multiple amdSecs? # When adding *MD which amdSec to add to? if mode.lower() == "mdwrap": othermdtype = kwargs.get("othermdtype") mdsec = MDWrap(md, mdtype, othermdtype) elif mode.lower() == "mdref": loctype = kwargs.get("loctype") label = kwargs.get("label") otherloctype = kwargs.get("otherloctype") mdsec = MDRef(md, mdtype, loctype, label, otherloctype) subsection = SubSection(subsection, mdsec) if subsection.subsection == "dmdSec": self.dmdsecs.append(subsection) else: try: amdsec = self.amdsecs[0] except IndexError: amdsec = AMDSec() self.amdsecs.append(amdsec) amdsec.subsections.append(subsection) return subsection
[ "def", "_add_metadata_element", "(", "self", ",", "md", ",", "subsection", ",", "mdtype", ",", "mode", "=", "\"mdwrap\"", ",", "*", "*", "kwargs", ")", ":", "# HELP how handle multiple amdSecs?", "# When adding *MD which amdSec to add to?", "if", "mode", ".", "lower", "(", ")", "==", "\"mdwrap\"", ":", "othermdtype", "=", "kwargs", ".", "get", "(", "\"othermdtype\"", ")", "mdsec", "=", "MDWrap", "(", "md", ",", "mdtype", ",", "othermdtype", ")", "elif", "mode", ".", "lower", "(", ")", "==", "\"mdref\"", ":", "loctype", "=", "kwargs", ".", "get", "(", "\"loctype\"", ")", "label", "=", "kwargs", ".", "get", "(", "\"label\"", ")", "otherloctype", "=", "kwargs", ".", "get", "(", "\"otherloctype\"", ")", "mdsec", "=", "MDRef", "(", "md", ",", "mdtype", ",", "loctype", ",", "label", ",", "otherloctype", ")", "subsection", "=", "SubSection", "(", "subsection", ",", "mdsec", ")", "if", "subsection", ".", "subsection", "==", "\"dmdSec\"", ":", "self", ".", "dmdsecs", ".", "append", "(", "subsection", ")", "else", ":", "try", ":", "amdsec", "=", "self", ".", "amdsecs", "[", "0", "]", "except", "IndexError", ":", "amdsec", "=", "AMDSec", "(", ")", "self", ".", "amdsecs", ".", "append", "(", "amdsec", ")", "amdsec", ".", "subsections", ".", "append", "(", "subsection", ")", "return", "subsection" ]
44.575758
14.272727
def _handle_recv(self, msg): """callback for stream.on_recv unpacks message, and calls handlers with it. """ ident,smsg = self.session.feed_identities(msg) self.call_handlers(self.session.unserialize(smsg))
[ "def", "_handle_recv", "(", "self", ",", "msg", ")", ":", "ident", ",", "smsg", "=", "self", ".", "session", ".", "feed_identities", "(", "msg", ")", "self", ".", "call_handlers", "(", "self", ".", "session", ".", "unserialize", "(", "smsg", ")", ")" ]
35.571429
12.571429
def bpMagnitudeErrorEoM(G, vmini, nobs=70): """ Calculate the end-of-mission photometric standard error in the BP band as a function of G and (V-I). Note: this refers to the integrated flux from the BP spectrophotometer. A margin of 20% is included. Parameters ---------- G - Value(s) of G-band magnitude. vmini - Value(s) of (V-I) colour. Keywords -------- nobs - Number of observations collected (default 70). Returns ------- The BP band photometric standard error in units of magnitude. """ return sqrt( (power(bpMagnitudeError(G, vmini)/_scienceMargin,2) + _eomCalibrationFloorBP*_eomCalibrationFloorBP)/nobs ) * _scienceMargin
[ "def", "bpMagnitudeErrorEoM", "(", "G", ",", "vmini", ",", "nobs", "=", "70", ")", ":", "return", "sqrt", "(", "(", "power", "(", "bpMagnitudeError", "(", "G", ",", "vmini", ")", "/", "_scienceMargin", ",", "2", ")", "+", "_eomCalibrationFloorBP", "*", "_eomCalibrationFloorBP", ")", "/", "nobs", ")", "*", "_scienceMargin" ]
28.521739
28.434783
def create_page(self, build_dir, filepath, context={}, content=None, template=None, markup=None, layout=None): """ To dynamically create a page and save it in the build_dir :param build_dir: (path) The base directory that will hold the created page :param filepath: (string) the name of the file to create. May contain slash to indicate directory It will also create the url based on that name If the filename doesn't end with .html, it will create a subdirectory and create `index.html` If file contains `.html` it will stays as is ie: post/waldo/where-is-waldo/ -> post/waldo/where-is-waldo/index.html another/music/new-rap-song.html -> another/music/new-rap-song.html post/page/5 -> post/page/5/index.html :param context: (dict) context data :param content: (text) The content of the file to be created. Will be overriden by template :param template: (path) if source is not provided, template can be used to create the page. Along with context it allows to create dynamic pages. The file is relative to `/templates/` file can be in html|jade|md :param markup: (string: html|jade|md), when using content. To indicate which markup to use. based on the markup it will parse the data html: will render as is jade and md: convert to the appropriate format :param layout: (string) when using content. The layout to use. The file location is relative to `/templates/` file can be in html|jade|md :return: """ build_dir = build_dir.rstrip("/") filepath = filepath.lstrip("/").rstrip("/") if not filepath.endswith(".html"): filepath += "/index.html" dest_file = os.path.join(build_dir, filepath) dest_dir = os.path.dirname(dest_file) if not os.path.isdir(dest_dir): os.makedirs(dest_dir) _context = context if "page" not in _context: _context["page"] = self.default_page_meta.copy() if "url" not in _context["page"]: _context["page"]["url"] = "/" + filepath.lstrip("/").replace( "index.html", "") if template: if template not in self._templates: self._templates[template] = self.tpl_env.get_template(template) tpl = self._templates[template] else: if markup == "md": _context["page"]["__toc__"] = md.get_toc(content) content = md.convert(content) elif markup == "jade": content = jade.convert(content) # Page must be extended by a layout and have a block 'body' # These tags will be included if they are missing if re.search(self.RE_EXTENDS, content) is None: layout = layout or self.default_layout content = "\n{% extends '{}' %} \n\n".replace("{}", layout) + content if re.search(self.RE_BLOCK_BODY, content) is None: _layout_block = re.search(self.RE_EXTENDS, content).group(0) content = content.replace(_layout_block, "") content = "\n" + _layout_block + "\n" + \ "{% block body %} \n" + content.strip() + "\n{% endblock %}" tpl = self.tpl_env.from_string(content) with open(dest_file, "w") as fw: fw.write(tpl.render(**_context))
[ "def", "create_page", "(", "self", ",", "build_dir", ",", "filepath", ",", "context", "=", "{", "}", ",", "content", "=", "None", ",", "template", "=", "None", ",", "markup", "=", "None", ",", "layout", "=", "None", ")", ":", "build_dir", "=", "build_dir", ".", "rstrip", "(", "\"/\"", ")", "filepath", "=", "filepath", ".", "lstrip", "(", "\"/\"", ")", ".", "rstrip", "(", "\"/\"", ")", "if", "not", "filepath", ".", "endswith", "(", "\".html\"", ")", ":", "filepath", "+=", "\"/index.html\"", "dest_file", "=", "os", ".", "path", ".", "join", "(", "build_dir", ",", "filepath", ")", "dest_dir", "=", "os", ".", "path", ".", "dirname", "(", "dest_file", ")", "if", "not", "os", ".", "path", ".", "isdir", "(", "dest_dir", ")", ":", "os", ".", "makedirs", "(", "dest_dir", ")", "_context", "=", "context", "if", "\"page\"", "not", "in", "_context", ":", "_context", "[", "\"page\"", "]", "=", "self", ".", "default_page_meta", ".", "copy", "(", ")", "if", "\"url\"", "not", "in", "_context", "[", "\"page\"", "]", ":", "_context", "[", "\"page\"", "]", "[", "\"url\"", "]", "=", "\"/\"", "+", "filepath", ".", "lstrip", "(", "\"/\"", ")", ".", "replace", "(", "\"index.html\"", ",", "\"\"", ")", "if", "template", ":", "if", "template", "not", "in", "self", ".", "_templates", ":", "self", ".", "_templates", "[", "template", "]", "=", "self", ".", "tpl_env", ".", "get_template", "(", "template", ")", "tpl", "=", "self", ".", "_templates", "[", "template", "]", "else", ":", "if", "markup", "==", "\"md\"", ":", "_context", "[", "\"page\"", "]", "[", "\"__toc__\"", "]", "=", "md", ".", "get_toc", "(", "content", ")", "content", "=", "md", ".", "convert", "(", "content", ")", "elif", "markup", "==", "\"jade\"", ":", "content", "=", "jade", ".", "convert", "(", "content", ")", "# Page must be extended by a layout and have a block 'body'", "# These tags will be included if they are missing", "if", "re", ".", "search", "(", "self", ".", "RE_EXTENDS", ",", "content", ")", "is", "None", ":", "layout", "=", "layout", "or", "self", ".", "default_layout", "content", "=", "\"\\n{% extends '{}' %} \\n\\n\"", ".", "replace", "(", "\"{}\"", ",", "layout", ")", "+", "content", "if", "re", ".", "search", "(", "self", ".", "RE_BLOCK_BODY", ",", "content", ")", "is", "None", ":", "_layout_block", "=", "re", ".", "search", "(", "self", ".", "RE_EXTENDS", ",", "content", ")", ".", "group", "(", "0", ")", "content", "=", "content", ".", "replace", "(", "_layout_block", ",", "\"\"", ")", "content", "=", "\"\\n\"", "+", "_layout_block", "+", "\"\\n\"", "+", "\"{% block body %} \\n\"", "+", "content", ".", "strip", "(", ")", "+", "\"\\n{% endblock %}\"", "tpl", "=", "self", ".", "tpl_env", ".", "from_string", "(", "content", ")", "with", "open", "(", "dest_file", ",", "\"w\"", ")", "as", "fw", ":", "fw", ".", "write", "(", "tpl", ".", "render", "(", "*", "*", "_context", ")", ")" ]
50.864865
24.027027
def boolean(name=None): """ Creates the grammar for a Boolean (B) field, accepting only 'Y' or 'N' :param name: name for the field :return: grammar for the flag field """ if name is None: name = 'Boolean Field' # Basic field field = pp.Regex('[YN]') # Parse action field.setParseAction(lambda b: _to_boolean(b[0])) # Name field.setName(name) return field
[ "def", "boolean", "(", "name", "=", "None", ")", ":", "if", "name", "is", "None", ":", "name", "=", "'Boolean Field'", "# Basic field", "field", "=", "pp", ".", "Regex", "(", "'[YN]'", ")", "# Parse action", "field", ".", "setParseAction", "(", "lambda", "b", ":", "_to_boolean", "(", "b", "[", "0", "]", ")", ")", "# Name", "field", ".", "setName", "(", "name", ")", "return", "field" ]
19.047619
22.285714
def verify_realms(self, token, realms, request): """Verify if the realms match the requested realms.""" log.debug('Verify realms %r', realms) tok = request.request_token or self._grantgetter(token=token) if not tok: return False request.request_token = tok if not hasattr(tok, 'realms'): # realms not enabled return True return set(tok.realms) == set(realms)
[ "def", "verify_realms", "(", "self", ",", "token", ",", "realms", ",", "request", ")", ":", "log", ".", "debug", "(", "'Verify realms %r'", ",", "realms", ")", "tok", "=", "request", ".", "request_token", "or", "self", ".", "_grantgetter", "(", "token", "=", "token", ")", "if", "not", "tok", ":", "return", "False", "request", ".", "request_token", "=", "tok", "if", "not", "hasattr", "(", "tok", ",", "'realms'", ")", ":", "# realms not enabled", "return", "True", "return", "set", "(", "tok", ".", "realms", ")", "==", "set", "(", "realms", ")" ]
36.666667
13
def _add_post_data(self, request: Request): '''Add data to the payload.''' if self._item_session.url_record.post_data: data = wpull.string.to_bytes(self._item_session.url_record.post_data) else: data = wpull.string.to_bytes( self._processor.fetch_params.post_data ) request.method = 'POST' request.fields['Content-Type'] = 'application/x-www-form-urlencoded' request.fields['Content-Length'] = str(len(data)) _logger.debug('Posting with data {0}.', data) if not request.body: request.body = Body(io.BytesIO()) with wpull.util.reset_file_offset(request.body): request.body.write(data)
[ "def", "_add_post_data", "(", "self", ",", "request", ":", "Request", ")", ":", "if", "self", ".", "_item_session", ".", "url_record", ".", "post_data", ":", "data", "=", "wpull", ".", "string", ".", "to_bytes", "(", "self", ".", "_item_session", ".", "url_record", ".", "post_data", ")", "else", ":", "data", "=", "wpull", ".", "string", ".", "to_bytes", "(", "self", ".", "_processor", ".", "fetch_params", ".", "post_data", ")", "request", ".", "method", "=", "'POST'", "request", ".", "fields", "[", "'Content-Type'", "]", "=", "'application/x-www-form-urlencoded'", "request", ".", "fields", "[", "'Content-Length'", "]", "=", "str", "(", "len", "(", "data", ")", ")", "_logger", ".", "debug", "(", "'Posting with data {0}.'", ",", "data", ")", "if", "not", "request", ".", "body", ":", "request", ".", "body", "=", "Body", "(", "io", ".", "BytesIO", "(", ")", ")", "with", "wpull", ".", "util", ".", "reset_file_offset", "(", "request", ".", "body", ")", ":", "request", ".", "body", ".", "write", "(", "data", ")" ]
35.8
19.9
def client_side(func): """ Decorator to designate an API method applicable only to client-side instances. This allows us to use the same APIRequest and APIResponse subclasses on the client and server sides without too much confusion. """ def inner(*args, **kwargs): if args and hasattr(args[0], 'is_server') and voltron.debugger: raise ClientSideOnlyException("This method can only be called on a client-side instance") return func(*args, **kwargs) return inner
[ "def", "client_side", "(", "func", ")", ":", "def", "inner", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "args", "and", "hasattr", "(", "args", "[", "0", "]", ",", "'is_server'", ")", "and", "voltron", ".", "debugger", ":", "raise", "ClientSideOnlyException", "(", "\"This method can only be called on a client-side instance\"", ")", "return", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "inner" ]
39.230769
22.923077
def bash_checker(code, working_directory): """Return checker.""" run = run_in_subprocess(code, '.bash', ['bash', '-n'], working_directory=working_directory) def run_check(): """Yield errors.""" result = run() if result: (output, filename) = result prefix = filename + ': line ' for line in output.splitlines(): if not line.startswith(prefix): continue message = line[len(prefix):] split_message = message.split(':', 1) yield (int(split_message[0]) - 1, split_message[1].strip()) return run_check
[ "def", "bash_checker", "(", "code", ",", "working_directory", ")", ":", "run", "=", "run_in_subprocess", "(", "code", ",", "'.bash'", ",", "[", "'bash'", ",", "'-n'", "]", ",", "working_directory", "=", "working_directory", ")", "def", "run_check", "(", ")", ":", "\"\"\"Yield errors.\"\"\"", "result", "=", "run", "(", ")", "if", "result", ":", "(", "output", ",", "filename", ")", "=", "result", "prefix", "=", "filename", "+", "': line '", "for", "line", "in", "output", ".", "splitlines", "(", ")", ":", "if", "not", "line", ".", "startswith", "(", "prefix", ")", ":", "continue", "message", "=", "line", "[", "len", "(", "prefix", ")", ":", "]", "split_message", "=", "message", ".", "split", "(", "':'", ",", "1", ")", "yield", "(", "int", "(", "split_message", "[", "0", "]", ")", "-", "1", ",", "split_message", "[", "1", "]", ".", "strip", "(", ")", ")", "return", "run_check" ]
36.263158
11.736842
def get_member_profile(self, member_id): ''' a method to retrieve member profile details :param member_id: integer with member id from member profile :return: dictionary with member profile details inside [json] key profile_details = self.objects.profile.schema ''' # https://www.meetup.com/meetup_api/docs/members/:member_id/#get title = '%s.get_member_profile' % self.__class__.__name__ # validate inputs input_fields = { 'member_id': member_id } for key, value in input_fields.items(): if value: object_title = '%s(%s=%s)' % (title, key, str(value)) self.fields.validate(value, '.%s' % key, object_title) # construct member id if not member_id: raise IndexError('%s requires member id argument.' % title) # compose request fields url = '%s/members/%s' % (self.endpoint, str(member_id)) params = { 'fields': 'gender,birthday,last_event,messaging_pref,next_event,other_services,privacy,self,stats' } # send requests profile_details = self._get_request(url, params=params) # construct method output if profile_details['json']: profile_details['json'] = self._reconstruct_member(profile_details['json']) return profile_details
[ "def", "get_member_profile", "(", "self", ",", "member_id", ")", ":", "# https://www.meetup.com/meetup_api/docs/members/:member_id/#get\r", "title", "=", "'%s.get_member_profile'", "%", "self", ".", "__class__", ".", "__name__", "# validate inputs\r", "input_fields", "=", "{", "'member_id'", ":", "member_id", "}", "for", "key", ",", "value", "in", "input_fields", ".", "items", "(", ")", ":", "if", "value", ":", "object_title", "=", "'%s(%s=%s)'", "%", "(", "title", ",", "key", ",", "str", "(", "value", ")", ")", "self", ".", "fields", ".", "validate", "(", "value", ",", "'.%s'", "%", "key", ",", "object_title", ")", "# construct member id\r", "if", "not", "member_id", ":", "raise", "IndexError", "(", "'%s requires member id argument.'", "%", "title", ")", "# compose request fields\r", "url", "=", "'%s/members/%s'", "%", "(", "self", ".", "endpoint", ",", "str", "(", "member_id", ")", ")", "params", "=", "{", "'fields'", ":", "'gender,birthday,last_event,messaging_pref,next_event,other_services,privacy,self,stats'", "}", "# send requests\r", "profile_details", "=", "self", ".", "_get_request", "(", "url", ",", "params", "=", "params", ")", "# construct method output\r", "if", "profile_details", "[", "'json'", "]", ":", "profile_details", "[", "'json'", "]", "=", "self", ".", "_reconstruct_member", "(", "profile_details", "[", "'json'", "]", ")", "return", "profile_details" ]
33.658537
26.682927
def equipable_classes(self): """ Returns a list of classes that _can_ use the item. """ sitem = self._schema_item return [c for c in sitem.get("used_by_classes", self.equipped.keys()) if c]
[ "def", "equipable_classes", "(", "self", ")", ":", "sitem", "=", "self", ".", "_schema_item", "return", "[", "c", "for", "c", "in", "sitem", ".", "get", "(", "\"used_by_classes\"", ",", "self", ".", "equipped", ".", "keys", "(", ")", ")", "if", "c", "]" ]
42
20.4
def load_colormap(self, name=None): """ Loads a colormap of the supplied name. None means used the internal name. (See self.get_name()) """ if name == None: name = self.get_name() if name == "" or not type(name)==str: return "Error: Bad name." # assemble the path to the colormap path = _os.path.join(_settings.path_home, "colormaps", name+".cmap") # make sure the file exists if not _os.path.exists(path): print("load_colormap(): Colormap '"+name+"' does not exist. Creating.") self.save_colormap(name) return # open the file and get the lines f = open(path, 'r') x = f.read() f.close() try: self._colorpoint_list = eval(x) except: print("Invalid colormap. Overwriting.") self.save_colormap() # update the image self.update_image() return self
[ "def", "load_colormap", "(", "self", ",", "name", "=", "None", ")", ":", "if", "name", "==", "None", ":", "name", "=", "self", ".", "get_name", "(", ")", "if", "name", "==", "\"\"", "or", "not", "type", "(", "name", ")", "==", "str", ":", "return", "\"Error: Bad name.\"", "# assemble the path to the colormap", "path", "=", "_os", ".", "path", ".", "join", "(", "_settings", ".", "path_home", ",", "\"colormaps\"", ",", "name", "+", "\".cmap\"", ")", "# make sure the file exists", "if", "not", "_os", ".", "path", ".", "exists", "(", "path", ")", ":", "print", "(", "\"load_colormap(): Colormap '\"", "+", "name", "+", "\"' does not exist. Creating.\"", ")", "self", ".", "save_colormap", "(", "name", ")", "return", "# open the file and get the lines", "f", "=", "open", "(", "path", ",", "'r'", ")", "x", "=", "f", ".", "read", "(", ")", "f", ".", "close", "(", ")", "try", ":", "self", ".", "_colorpoint_list", "=", "eval", "(", "x", ")", "except", ":", "print", "(", "\"Invalid colormap. Overwriting.\"", ")", "self", ".", "save_colormap", "(", ")", "# update the image", "self", ".", "update_image", "(", ")", "return", "self" ]
28.575758
19.969697
def _propagate_glyph_anchors(self, ufo, parent, processed): """Propagate anchors for a single parent glyph.""" if parent.name in processed: return processed.add(parent.name) base_components = [] mark_components = [] anchor_names = set() to_add = {} for component in parent.components: try: glyph = ufo[component.baseGlyph] except KeyError: self.logger.warning( "Anchors not propagated for inexistent component {} in glyph {}".format( component.baseGlyph, parent.name ) ) else: _propagate_glyph_anchors(self, ufo, glyph, processed) if any(a.name.startswith("_") for a in glyph.anchors): mark_components.append(component) else: base_components.append(component) anchor_names |= {a.name for a in glyph.anchors} for anchor_name in anchor_names: # don't add if parent already contains this anchor OR any associated # ligature anchors (e.g. "top_1, top_2" for "top") if not any(a.name.startswith(anchor_name) for a in parent.anchors): _get_anchor_data(to_add, ufo, base_components, anchor_name) for component in mark_components: _adjust_anchors(to_add, ufo, component) # we sort propagated anchors to append in a deterministic order for name, (x, y) in sorted(to_add.items()): anchor_dict = {"name": name, "x": x, "y": y} parent.appendAnchor(glyph.anchorClass(anchorDict=anchor_dict))
[ "def", "_propagate_glyph_anchors", "(", "self", ",", "ufo", ",", "parent", ",", "processed", ")", ":", "if", "parent", ".", "name", "in", "processed", ":", "return", "processed", ".", "add", "(", "parent", ".", "name", ")", "base_components", "=", "[", "]", "mark_components", "=", "[", "]", "anchor_names", "=", "set", "(", ")", "to_add", "=", "{", "}", "for", "component", "in", "parent", ".", "components", ":", "try", ":", "glyph", "=", "ufo", "[", "component", ".", "baseGlyph", "]", "except", "KeyError", ":", "self", ".", "logger", ".", "warning", "(", "\"Anchors not propagated for inexistent component {} in glyph {}\"", ".", "format", "(", "component", ".", "baseGlyph", ",", "parent", ".", "name", ")", ")", "else", ":", "_propagate_glyph_anchors", "(", "self", ",", "ufo", ",", "glyph", ",", "processed", ")", "if", "any", "(", "a", ".", "name", ".", "startswith", "(", "\"_\"", ")", "for", "a", "in", "glyph", ".", "anchors", ")", ":", "mark_components", ".", "append", "(", "component", ")", "else", ":", "base_components", ".", "append", "(", "component", ")", "anchor_names", "|=", "{", "a", ".", "name", "for", "a", "in", "glyph", ".", "anchors", "}", "for", "anchor_name", "in", "anchor_names", ":", "# don't add if parent already contains this anchor OR any associated", "# ligature anchors (e.g. \"top_1, top_2\" for \"top\")", "if", "not", "any", "(", "a", ".", "name", ".", "startswith", "(", "anchor_name", ")", "for", "a", "in", "parent", ".", "anchors", ")", ":", "_get_anchor_data", "(", "to_add", ",", "ufo", ",", "base_components", ",", "anchor_name", ")", "for", "component", "in", "mark_components", ":", "_adjust_anchors", "(", "to_add", ",", "ufo", ",", "component", ")", "# we sort propagated anchors to append in a deterministic order", "for", "name", ",", "(", "x", ",", "y", ")", "in", "sorted", "(", "to_add", ".", "items", "(", ")", ")", ":", "anchor_dict", "=", "{", "\"name\"", ":", "name", ",", "\"x\"", ":", "x", ",", "\"y\"", ":", "y", "}", "parent", ".", "appendAnchor", "(", "glyph", ".", "anchorClass", "(", "anchorDict", "=", "anchor_dict", ")", ")" ]
37.926829
20.853659
def create_transcripts_xml(video_id, video_el, resource_fs, static_dir): """ Creates xml for transcripts. For each transcript element, an associated transcript file is also created in course OLX. Arguments: video_id (str): Video id of the video. video_el (Element): lxml Element object static_dir (str): The Directory to store transcript file. resource_fs (SubFS): The file system to store transcripts. Returns: lxml Element object with transcripts information """ video_transcripts = VideoTranscript.objects.filter(video__edx_video_id=video_id).order_by('language_code') # create transcripts node only when we have transcripts for a video if video_transcripts.exists(): transcripts_el = SubElement(video_el, 'transcripts') transcript_files_map = {} for video_transcript in video_transcripts: language_code = video_transcript.language_code file_format = video_transcript.file_format try: transcript_filename = create_transcript_file( video_id=video_id, language_code=language_code, file_format=file_format, resource_fs=resource_fs.delegate_fs(), static_dir=combine(u'course', static_dir) # File system should not start from /draft directory. ) transcript_files_map[language_code] = transcript_filename except TranscriptsGenerationException: # we don't want to halt export in this case, just log and move to the next transcript. logger.exception('[VAL] Error while generating "%s" transcript for video["%s"].', language_code, video_id) continue SubElement( transcripts_el, 'transcript', { 'language_code': language_code, 'file_format': Transcript.SRT, 'provider': video_transcript.provider, } ) return dict(xml=video_el, transcripts=transcript_files_map)
[ "def", "create_transcripts_xml", "(", "video_id", ",", "video_el", ",", "resource_fs", ",", "static_dir", ")", ":", "video_transcripts", "=", "VideoTranscript", ".", "objects", ".", "filter", "(", "video__edx_video_id", "=", "video_id", ")", ".", "order_by", "(", "'language_code'", ")", "# create transcripts node only when we have transcripts for a video", "if", "video_transcripts", ".", "exists", "(", ")", ":", "transcripts_el", "=", "SubElement", "(", "video_el", ",", "'transcripts'", ")", "transcript_files_map", "=", "{", "}", "for", "video_transcript", "in", "video_transcripts", ":", "language_code", "=", "video_transcript", ".", "language_code", "file_format", "=", "video_transcript", ".", "file_format", "try", ":", "transcript_filename", "=", "create_transcript_file", "(", "video_id", "=", "video_id", ",", "language_code", "=", "language_code", ",", "file_format", "=", "file_format", ",", "resource_fs", "=", "resource_fs", ".", "delegate_fs", "(", ")", ",", "static_dir", "=", "combine", "(", "u'course'", ",", "static_dir", ")", "# File system should not start from /draft directory.", ")", "transcript_files_map", "[", "language_code", "]", "=", "transcript_filename", "except", "TranscriptsGenerationException", ":", "# we don't want to halt export in this case, just log and move to the next transcript.", "logger", ".", "exception", "(", "'[VAL] Error while generating \"%s\" transcript for video[\"%s\"].'", ",", "language_code", ",", "video_id", ")", "continue", "SubElement", "(", "transcripts_el", ",", "'transcript'", ",", "{", "'language_code'", ":", "language_code", ",", "'file_format'", ":", "Transcript", ".", "SRT", ",", "'provider'", ":", "video_transcript", ".", "provider", ",", "}", ")", "return", "dict", "(", "xml", "=", "video_el", ",", "transcripts", "=", "transcript_files_map", ")" ]
40.897959
24.040816
def create_config_tree(config, modules, prefix=''): '''Cause every possible configuration sub-dictionary to exist. This is intended to be called very early in the configuration sequence. For each module, it checks that the corresponding configuration item exists in `config` and creates it as an empty dictionary if required, and then recurses into child configs/modules. :param dict config: configuration to populate :param modules: modules or Configurable instances to use :type modules: iterable of :class:`~yakonfig.configurable.Configurable` :param str prefix: prefix name of the config :return: `config` :raises yakonfig.ConfigurationError: if an expected name is present in the provided config, but that name is not a dictionary ''' def work_in(parent_config, config_name, prefix, module): if config_name not in parent_config: # this is the usual, expected case parent_config[config_name] = {} elif not isinstance(parent_config[config_name], collections.Mapping): raise ConfigurationError( '{0} must be an object configuration'.format(prefix)) else: # config_name is a pre-existing dictionary in parent_config pass _recurse_config(config, modules, work_in)
[ "def", "create_config_tree", "(", "config", ",", "modules", ",", "prefix", "=", "''", ")", ":", "def", "work_in", "(", "parent_config", ",", "config_name", ",", "prefix", ",", "module", ")", ":", "if", "config_name", "not", "in", "parent_config", ":", "# this is the usual, expected case", "parent_config", "[", "config_name", "]", "=", "{", "}", "elif", "not", "isinstance", "(", "parent_config", "[", "config_name", "]", ",", "collections", ".", "Mapping", ")", ":", "raise", "ConfigurationError", "(", "'{0} must be an object configuration'", ".", "format", "(", "prefix", ")", ")", "else", ":", "# config_name is a pre-existing dictionary in parent_config", "pass", "_recurse_config", "(", "config", ",", "modules", ",", "work_in", ")" ]
43.5
22.566667
def get_single_key(d): """Get a key from a dict which contains just one item.""" assert len(d) == 1, 'Single-item dict must have just one item, not %d.' % len(d) return next(six.iterkeys(d))
[ "def", "get_single_key", "(", "d", ")", ":", "assert", "len", "(", "d", ")", "==", "1", ",", "'Single-item dict must have just one item, not %d.'", "%", "len", "(", "d", ")", "return", "next", "(", "six", ".", "iterkeys", "(", "d", ")", ")" ]
49.75
17.5
def parse(argv, rules=None, config=None, **kwargs): """Parse the given arg vector with the default Splunk command rules.""" parser_ = parser(rules, **kwargs) if config is not None: parser_.loadrc(config) return parser_.parse(argv).result
[ "def", "parse", "(", "argv", ",", "rules", "=", "None", ",", "config", "=", "None", ",", "*", "*", "kwargs", ")", ":", "parser_", "=", "parser", "(", "rules", ",", "*", "*", "kwargs", ")", "if", "config", "is", "not", "None", ":", "parser_", ".", "loadrc", "(", "config", ")", "return", "parser_", ".", "parse", "(", "argv", ")", ".", "result" ]
49.8
5.2
def settings(self): """Return batch job settings.""" _settings = { 'action': self._action, # not supported in v2 batch # 'attributeWriteType': self._attribute_write_type, 'attributeWriteType': 'Replace', 'haltOnError': str(self._halt_on_error).lower(), 'owner': self._owner, 'version': 'V2', } if self._playbook_triggers_enabled is not None: _settings['playbookTriggersEnabled'] = str(self._playbook_triggers_enabled).lower() if self._hash_collision_mode is not None: _settings['hashCollisionMode'] = self._hash_collision_mode if self._file_merge_mode is not None: _settings['fileMergeMode'] = self._file_merge_mode return _settings
[ "def", "settings", "(", "self", ")", ":", "_settings", "=", "{", "'action'", ":", "self", ".", "_action", ",", "# not supported in v2 batch", "# 'attributeWriteType': self._attribute_write_type,", "'attributeWriteType'", ":", "'Replace'", ",", "'haltOnError'", ":", "str", "(", "self", ".", "_halt_on_error", ")", ".", "lower", "(", ")", ",", "'owner'", ":", "self", ".", "_owner", ",", "'version'", ":", "'V2'", ",", "}", "if", "self", ".", "_playbook_triggers_enabled", "is", "not", "None", ":", "_settings", "[", "'playbookTriggersEnabled'", "]", "=", "str", "(", "self", ".", "_playbook_triggers_enabled", ")", ".", "lower", "(", ")", "if", "self", ".", "_hash_collision_mode", "is", "not", "None", ":", "_settings", "[", "'hashCollisionMode'", "]", "=", "self", ".", "_hash_collision_mode", "if", "self", ".", "_file_merge_mode", "is", "not", "None", ":", "_settings", "[", "'fileMergeMode'", "]", "=", "self", ".", "_file_merge_mode", "return", "_settings" ]
43.944444
16.388889
def rssi_bars(self) -> int: """Received Signal Strength Indication, from 0 to 4 bars.""" rssi_db = self.rssi_db if rssi_db < 45: return 0 elif rssi_db < 60: return 1 elif rssi_db < 75: return 2 elif rssi_db < 90: return 3 return 4
[ "def", "rssi_bars", "(", "self", ")", "->", "int", ":", "rssi_db", "=", "self", ".", "rssi_db", "if", "rssi_db", "<", "45", ":", "return", "0", "elif", "rssi_db", "<", "60", ":", "return", "1", "elif", "rssi_db", "<", "75", ":", "return", "2", "elif", "rssi_db", "<", "90", ":", "return", "3", "return", "4" ]
26.916667
15.416667
def make_non_negative_axis(axis, rank): """Make (possibly negatively indexed) `axis` argument non-negative.""" axis = tf.convert_to_tensor(value=axis, name="axis") rank = tf.convert_to_tensor(value=rank, name="rank") axis_ = tf.get_static_value(axis) rank_ = tf.get_static_value(rank) # Static case. if axis_ is not None and rank_ is not None: is_scalar = axis_.ndim == 0 if is_scalar: axis_ = [axis_] positive_axis = [] for a_ in axis_: if a_ < 0: positive_axis.append(rank_ + a_) else: positive_axis.append(a_) if is_scalar: positive_axis = positive_axis[0] return tf.convert_to_tensor(value=positive_axis, dtype=axis.dtype) # Dynamic case. # Unfortunately static values are lost by this tf.where. return tf.where(axis < 0, rank + axis, axis)
[ "def", "make_non_negative_axis", "(", "axis", ",", "rank", ")", ":", "axis", "=", "tf", ".", "convert_to_tensor", "(", "value", "=", "axis", ",", "name", "=", "\"axis\"", ")", "rank", "=", "tf", ".", "convert_to_tensor", "(", "value", "=", "rank", ",", "name", "=", "\"rank\"", ")", "axis_", "=", "tf", ".", "get_static_value", "(", "axis", ")", "rank_", "=", "tf", ".", "get_static_value", "(", "rank", ")", "# Static case.", "if", "axis_", "is", "not", "None", "and", "rank_", "is", "not", "None", ":", "is_scalar", "=", "axis_", ".", "ndim", "==", "0", "if", "is_scalar", ":", "axis_", "=", "[", "axis_", "]", "positive_axis", "=", "[", "]", "for", "a_", "in", "axis_", ":", "if", "a_", "<", "0", ":", "positive_axis", ".", "append", "(", "rank_", "+", "a_", ")", "else", ":", "positive_axis", ".", "append", "(", "a_", ")", "if", "is_scalar", ":", "positive_axis", "=", "positive_axis", "[", "0", "]", "return", "tf", ".", "convert_to_tensor", "(", "value", "=", "positive_axis", ",", "dtype", "=", "axis", ".", "dtype", ")", "# Dynamic case.", "# Unfortunately static values are lost by this tf.where.", "return", "tf", ".", "where", "(", "axis", "<", "0", ",", "rank", "+", "axis", ",", "axis", ")" ]
32.24
16
def curve(self): """ Returns information about the curve used for an EC key :raises: ValueError - when the key is not an EC key :return: A two-element tuple, with the first element being a unicode string of "implicit_ca", "specified" or "named". If the first element is "implicit_ca", the second is None. If "specified", the second is an OrderedDict that is the native version of SpecifiedECDomain. If "named", the second is a unicode string of the curve name. """ if self.algorithm != 'ec': raise ValueError(unwrap( ''' Only EC keys have a curve, this key is %s ''', self.algorithm.upper() )) params = self['algorithm']['parameters'] chosen = params.chosen if params.name == 'implicit_ca': value = None else: value = chosen.native return (params.name, value)
[ "def", "curve", "(", "self", ")", ":", "if", "self", ".", "algorithm", "!=", "'ec'", ":", "raise", "ValueError", "(", "unwrap", "(", "'''\n Only EC keys have a curve, this key is %s\n '''", ",", "self", ".", "algorithm", ".", "upper", "(", ")", ")", ")", "params", "=", "self", "[", "'algorithm'", "]", "[", "'parameters'", "]", "chosen", "=", "params", ".", "chosen", "if", "params", ".", "name", "==", "'implicit_ca'", ":", "value", "=", "None", "else", ":", "value", "=", "chosen", ".", "native", "return", "(", "params", ".", "name", ",", "value", ")" ]
31.4375
21.75
def _parse_float_vec(vec): """ Parse a vector of float values representing IBM 8 byte floats into native 8 byte floats. """ dtype = np.dtype('>u4,>u4') vec1 = vec.view(dtype=dtype) xport1 = vec1['f0'] xport2 = vec1['f1'] # Start by setting first half of ieee number to first half of IBM # number sans exponent ieee1 = xport1 & 0x00ffffff # The fraction bit to the left of the binary point in the ieee # format was set and the number was shifted 0, 1, 2, or 3 # places. This will tell us how to adjust the ibm exponent to be a # power of 2 ieee exponent and how to shift the fraction bits to # restore the correct magnitude. shift = np.zeros(len(vec), dtype=np.uint8) shift[np.where(xport1 & 0x00200000)] = 1 shift[np.where(xport1 & 0x00400000)] = 2 shift[np.where(xport1 & 0x00800000)] = 3 # shift the ieee number down the correct number of places then # set the second half of the ieee number to be the second half # of the ibm number shifted appropriately, ored with the bits # from the first half that would have been shifted in if we # could shift a double. All we are worried about are the low # order 3 bits of the first half since we're only shifting by # 1, 2, or 3. ieee1 >>= shift ieee2 = (xport2 >> shift) | ((xport1 & 0x00000007) << (29 + (3 - shift))) # clear the 1 bit to the left of the binary point ieee1 &= 0xffefffff # set the exponent of the ieee number to be the actual exponent # plus the shift count + 1023. Or this into the first half of the # ieee number. The ibm exponent is excess 64 but is adjusted by 65 # since during conversion to ibm format the exponent is # incremented by 1 and the fraction bits left 4 positions to the # right of the radix point. (had to add >> 24 because C treats & # 0x7f as 0x7f000000 and Python doesn't) ieee1 |= ((((((xport1 >> 24) & 0x7f) - 65) << 2) + shift + 1023) << 20) | (xport1 & 0x80000000) ieee = np.empty((len(ieee1),), dtype='>u4,>u4') ieee['f0'] = ieee1 ieee['f1'] = ieee2 ieee = ieee.view(dtype='>f8') ieee = ieee.astype('f8') return ieee
[ "def", "_parse_float_vec", "(", "vec", ")", ":", "dtype", "=", "np", ".", "dtype", "(", "'>u4,>u4'", ")", "vec1", "=", "vec", ".", "view", "(", "dtype", "=", "dtype", ")", "xport1", "=", "vec1", "[", "'f0'", "]", "xport2", "=", "vec1", "[", "'f1'", "]", "# Start by setting first half of ieee number to first half of IBM", "# number sans exponent", "ieee1", "=", "xport1", "&", "0x00ffffff", "# The fraction bit to the left of the binary point in the ieee", "# format was set and the number was shifted 0, 1, 2, or 3", "# places. This will tell us how to adjust the ibm exponent to be a", "# power of 2 ieee exponent and how to shift the fraction bits to", "# restore the correct magnitude.", "shift", "=", "np", ".", "zeros", "(", "len", "(", "vec", ")", ",", "dtype", "=", "np", ".", "uint8", ")", "shift", "[", "np", ".", "where", "(", "xport1", "&", "0x00200000", ")", "]", "=", "1", "shift", "[", "np", ".", "where", "(", "xport1", "&", "0x00400000", ")", "]", "=", "2", "shift", "[", "np", ".", "where", "(", "xport1", "&", "0x00800000", ")", "]", "=", "3", "# shift the ieee number down the correct number of places then", "# set the second half of the ieee number to be the second half", "# of the ibm number shifted appropriately, ored with the bits", "# from the first half that would have been shifted in if we", "# could shift a double. All we are worried about are the low", "# order 3 bits of the first half since we're only shifting by", "# 1, 2, or 3.", "ieee1", ">>=", "shift", "ieee2", "=", "(", "xport2", ">>", "shift", ")", "|", "(", "(", "xport1", "&", "0x00000007", ")", "<<", "(", "29", "+", "(", "3", "-", "shift", ")", ")", ")", "# clear the 1 bit to the left of the binary point", "ieee1", "&=", "0xffefffff", "# set the exponent of the ieee number to be the actual exponent", "# plus the shift count + 1023. Or this into the first half of the", "# ieee number. The ibm exponent is excess 64 but is adjusted by 65", "# since during conversion to ibm format the exponent is", "# incremented by 1 and the fraction bits left 4 positions to the", "# right of the radix point. (had to add >> 24 because C treats &", "# 0x7f as 0x7f000000 and Python doesn't)", "ieee1", "|=", "(", "(", "(", "(", "(", "(", "xport1", ">>", "24", ")", "&", "0x7f", ")", "-", "65", ")", "<<", "2", ")", "+", "shift", "+", "1023", ")", "<<", "20", ")", "|", "(", "xport1", "&", "0x80000000", ")", "ieee", "=", "np", ".", "empty", "(", "(", "len", "(", "ieee1", ")", ",", ")", ",", "dtype", "=", "'>u4,>u4'", ")", "ieee", "[", "'f0'", "]", "=", "ieee1", "ieee", "[", "'f1'", "]", "=", "ieee2", "ieee", "=", "ieee", ".", "view", "(", "dtype", "=", "'>f8'", ")", "ieee", "=", "ieee", ".", "astype", "(", "'f8'", ")", "return", "ieee" ]
39.218182
21.072727
def delay(self, key): """Sleep only if elapsed time since `self.last[key]` < `self.delay[key]`.""" last_action, target_delay = self.last[key], self.delays[key] elapsed_time = time.time() - last_action if elapsed_time < target_delay: t_remaining = target_delay - elapsed_time time.sleep(t_remaining * random.uniform(0.25, 1.25)) self.last[key] = time.time()
[ "def", "delay", "(", "self", ",", "key", ")", ":", "last_action", ",", "target_delay", "=", "self", ".", "last", "[", "key", "]", ",", "self", ".", "delays", "[", "key", "]", "elapsed_time", "=", "time", ".", "time", "(", ")", "-", "last_action", "if", "elapsed_time", "<", "target_delay", ":", "t_remaining", "=", "target_delay", "-", "elapsed_time", "time", ".", "sleep", "(", "t_remaining", "*", "random", ".", "uniform", "(", "0.25", ",", "1.25", ")", ")", "self", ".", "last", "[", "key", "]", "=", "time", ".", "time", "(", ")" ]
51.625
12.125
def get_proficiency_query_session(self, proxy): """Gets the ``OsidSession`` associated with the proficiency query service. :param proxy: a proxy :type proxy: ``osid.proxy.Proxy`` :return: a ``ProficiencyQuerySession`` :rtype: ``osid.learning.ProficiencyQuerySession`` :raise: ``NullArgument`` -- ``proxy`` is ``null`` :raise: ``OperationFailed`` -- unable to complete request :raise: ``Unimplemented`` -- ``supports_proficiency_query()`` is ``false`` *compliance: optional -- This method must be implemented if ``supports_proficiency_query()`` is ``true``.* """ if not self.supports_proficiency_query(): raise Unimplemented() try: from . import sessions except ImportError: raise OperationFailed() proxy = self._convert_proxy(proxy) try: session = sessions.ProficiencyQuerySession(proxy=proxy, runtime=self._runtime) except AttributeError: raise OperationFailed() return session
[ "def", "get_proficiency_query_session", "(", "self", ",", "proxy", ")", ":", "if", "not", "self", ".", "supports_proficiency_query", "(", ")", ":", "raise", "Unimplemented", "(", ")", "try", ":", "from", ".", "import", "sessions", "except", "ImportError", ":", "raise", "OperationFailed", "(", ")", "proxy", "=", "self", ".", "_convert_proxy", "(", "proxy", ")", "try", ":", "session", "=", "sessions", ".", "ProficiencyQuerySession", "(", "proxy", "=", "proxy", ",", "runtime", "=", "self", ".", "_runtime", ")", "except", "AttributeError", ":", "raise", "OperationFailed", "(", ")", "return", "session" ]
40.461538
19.269231
def hil_actuator_controls_send(self, time_usec, controls, mode, flags, force_mavlink1=False): ''' Sent from autopilot to simulation. Hardware in the loop control outputs (replacement for HIL_CONTROLS) time_usec : Timestamp (microseconds since UNIX epoch or microseconds since system boot) (uint64_t) controls : Control outputs -1 .. 1. Channel assignment depends on the simulated hardware. (float) mode : System mode (MAV_MODE), includes arming state. (uint8_t) flags : Flags as bitfield, reserved for future use. (uint64_t) ''' return self.send(self.hil_actuator_controls_encode(time_usec, controls, mode, flags), force_mavlink1=force_mavlink1)
[ "def", "hil_actuator_controls_send", "(", "self", ",", "time_usec", ",", "controls", ",", "mode", ",", "flags", ",", "force_mavlink1", "=", "False", ")", ":", "return", "self", ".", "send", "(", "self", ".", "hil_actuator_controls_encode", "(", "time_usec", ",", "controls", ",", "mode", ",", "flags", ")", ",", "force_mavlink1", "=", "force_mavlink1", ")" ]
71.166667
51.5
def err(format_msg, *args, **kwargs): '''print format_msg to stderr''' exc_info = kwargs.pop("exc_info", False) stderr.warning(str(format_msg).format(*args, **kwargs), exc_info=exc_info)
[ "def", "err", "(", "format_msg", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "exc_info", "=", "kwargs", ".", "pop", "(", "\"exc_info\"", ",", "False", ")", "stderr", ".", "warning", "(", "str", "(", "format_msg", ")", ".", "format", "(", "*", "args", ",", "*", "*", "kwargs", ")", ",", "exc_info", "=", "exc_info", ")" ]
48.75
12.25
def geom(self): """Geometry information. :class:`_Geometry` instance holding geometry information. It is issued from binary files holding field information. It is set to None if not available for this time step. """ if self._header is UNDETERMINED: binfiles = self.step.sdat.binfiles_set(self.step.isnap) if binfiles: self._header = stagyyparsers.fields(binfiles.pop(), only_header=True) elif self.step.sdat.hdf5: xmf = self.step.sdat.hdf5 / 'Data.xmf' self._header, _ = stagyyparsers.read_geom_h5(xmf, self.step.isnap) else: self._header = None if self._geom is UNDETERMINED: if self._header is None: self._geom = None else: self._geom = _Geometry(self._header, self.step.sdat.par) return self._geom
[ "def", "geom", "(", "self", ")", ":", "if", "self", ".", "_header", "is", "UNDETERMINED", ":", "binfiles", "=", "self", ".", "step", ".", "sdat", ".", "binfiles_set", "(", "self", ".", "step", ".", "isnap", ")", "if", "binfiles", ":", "self", ".", "_header", "=", "stagyyparsers", ".", "fields", "(", "binfiles", ".", "pop", "(", ")", ",", "only_header", "=", "True", ")", "elif", "self", ".", "step", ".", "sdat", ".", "hdf5", ":", "xmf", "=", "self", ".", "step", ".", "sdat", ".", "hdf5", "/", "'Data.xmf'", "self", ".", "_header", ",", "_", "=", "stagyyparsers", ".", "read_geom_h5", "(", "xmf", ",", "self", ".", "step", ".", "isnap", ")", "else", ":", "self", ".", "_header", "=", "None", "if", "self", ".", "_geom", "is", "UNDETERMINED", ":", "if", "self", ".", "_header", "is", "None", ":", "self", ".", "_geom", "=", "None", "else", ":", "self", ".", "_geom", "=", "_Geometry", "(", "self", ".", "_header", ",", "self", ".", "step", ".", "sdat", ".", "par", ")", "return", "self", ".", "_geom" ]
42.625
17.75
def _smooth_epsf(self, epsf_data): """ Smooth the ePSF array by convolving it with a kernel. Parameters ---------- epsf_data : 2D `~numpy.ndarray` A 2D array containing the ePSF image. Returns ------- result : 2D `~numpy.ndarray` The smoothed (convolved) ePSF data. """ from scipy.ndimage import convolve if self.smoothing_kernel is None: return epsf_data elif self.smoothing_kernel == 'quartic': # from Polynomial2D fit with degree=4 to 5x5 array of # zeros with 1. at the center # Polynomial2D(4, c0_0=0.04163265, c1_0=-0.76326531, # c2_0=0.99081633, c3_0=-0.4, c4_0=0.05, # c0_1=-0.76326531, c0_2=0.99081633, c0_3=-0.4, # c0_4=0.05, c1_1=0.32653061, c1_2=-0.08163265, # c1_3=0., c2_1=-0.08163265, c2_2=0.02040816, # c3_1=-0.)> kernel = np.array( [[+0.041632, -0.080816, 0.078368, -0.080816, +0.041632], [-0.080816, -0.019592, 0.200816, -0.019592, -0.080816], [+0.078368, +0.200816, 0.441632, +0.200816, +0.078368], [-0.080816, -0.019592, 0.200816, -0.019592, -0.080816], [+0.041632, -0.080816, 0.078368, -0.080816, +0.041632]]) elif self.smoothing_kernel == 'quadratic': # from Polynomial2D fit with degree=2 to 5x5 array of # zeros with 1. at the center # Polynomial2D(2, c0_0=-0.07428571, c1_0=0.11428571, # c2_0=-0.02857143, c0_1=0.11428571, # c0_2=-0.02857143, c1_1=-0.) kernel = np.array( [[-0.07428311, 0.01142786, 0.03999952, 0.01142786, -0.07428311], [+0.01142786, 0.09714283, 0.12571449, 0.09714283, +0.01142786], [+0.03999952, 0.12571449, 0.15428215, 0.12571449, +0.03999952], [+0.01142786, 0.09714283, 0.12571449, 0.09714283, +0.01142786], [-0.07428311, 0.01142786, 0.03999952, 0.01142786, -0.07428311]]) elif isinstance(self.smoothing_kernel, np.ndarray): kernel = self.kernel else: raise TypeError('Unsupported kernel.') return convolve(epsf_data, kernel)
[ "def", "_smooth_epsf", "(", "self", ",", "epsf_data", ")", ":", "from", "scipy", ".", "ndimage", "import", "convolve", "if", "self", ".", "smoothing_kernel", "is", "None", ":", "return", "epsf_data", "elif", "self", ".", "smoothing_kernel", "==", "'quartic'", ":", "# from Polynomial2D fit with degree=4 to 5x5 array of", "# zeros with 1. at the center", "# Polynomial2D(4, c0_0=0.04163265, c1_0=-0.76326531,", "# c2_0=0.99081633, c3_0=-0.4, c4_0=0.05,", "# c0_1=-0.76326531, c0_2=0.99081633, c0_3=-0.4,", "# c0_4=0.05, c1_1=0.32653061, c1_2=-0.08163265,", "# c1_3=0., c2_1=-0.08163265, c2_2=0.02040816,", "# c3_1=-0.)>", "kernel", "=", "np", ".", "array", "(", "[", "[", "+", "0.041632", ",", "-", "0.080816", ",", "0.078368", ",", "-", "0.080816", ",", "+", "0.041632", "]", ",", "[", "-", "0.080816", ",", "-", "0.019592", ",", "0.200816", ",", "-", "0.019592", ",", "-", "0.080816", "]", ",", "[", "+", "0.078368", ",", "+", "0.200816", ",", "0.441632", ",", "+", "0.200816", ",", "+", "0.078368", "]", ",", "[", "-", "0.080816", ",", "-", "0.019592", ",", "0.200816", ",", "-", "0.019592", ",", "-", "0.080816", "]", ",", "[", "+", "0.041632", ",", "-", "0.080816", ",", "0.078368", ",", "-", "0.080816", ",", "+", "0.041632", "]", "]", ")", "elif", "self", ".", "smoothing_kernel", "==", "'quadratic'", ":", "# from Polynomial2D fit with degree=2 to 5x5 array of", "# zeros with 1. at the center", "# Polynomial2D(2, c0_0=-0.07428571, c1_0=0.11428571,", "# c2_0=-0.02857143, c0_1=0.11428571,", "# c0_2=-0.02857143, c1_1=-0.)", "kernel", "=", "np", ".", "array", "(", "[", "[", "-", "0.07428311", ",", "0.01142786", ",", "0.03999952", ",", "0.01142786", ",", "-", "0.07428311", "]", ",", "[", "+", "0.01142786", ",", "0.09714283", ",", "0.12571449", ",", "0.09714283", ",", "+", "0.01142786", "]", ",", "[", "+", "0.03999952", ",", "0.12571449", ",", "0.15428215", ",", "0.12571449", ",", "+", "0.03999952", "]", ",", "[", "+", "0.01142786", ",", "0.09714283", ",", "0.12571449", ",", "0.09714283", ",", "+", "0.01142786", "]", ",", "[", "-", "0.07428311", ",", "0.01142786", ",", "0.03999952", ",", "0.01142786", ",", "-", "0.07428311", "]", "]", ")", "elif", "isinstance", "(", "self", ".", "smoothing_kernel", ",", "np", ".", "ndarray", ")", ":", "kernel", "=", "self", ".", "kernel", "else", ":", "raise", "TypeError", "(", "'Unsupported kernel.'", ")", "return", "convolve", "(", "epsf_data", ",", "kernel", ")" ]
39.95082
19.885246
def qtrim_back(self, name, size=1): """ Sets the list element at ``index`` to ``value``. An error is returned for out of range indexes. :param string name: the queue name :param int size: the max length of removed elements :return: the length of removed elements :rtype: int """ size = get_positive_integer("size", size) return self.execute_command('qtrim_back', name, size)
[ "def", "qtrim_back", "(", "self", ",", "name", ",", "size", "=", "1", ")", ":", "size", "=", "get_positive_integer", "(", "\"size\"", ",", "size", ")", "return", "self", ".", "execute_command", "(", "'qtrim_back'", ",", "name", ",", "size", ")" ]
35.384615
17.692308
async def query(self, path, method='get', **params): """ Do a query to the System API :param path: url to the API :param method: the kind of query to do :param params: a dict with all the necessary things to query the API :return json data """ if method in ('get', 'post', 'patch', 'delete', 'put'): full_path = self.host + path if method == 'get': resp = await self.aio_sess.get(full_path, params=params) elif method == 'post': resp = await self.aio_sess.post(full_path, data=params) elif method == 'patch': resp = await self.aio_sess.patch(full_path, data=params) elif method == 'delete': resp = await self.aio_sess.delete(full_path, params=params, headers=params) elif method == 'put': resp = await self.aio_sess.put(full_path, data=params) async with resp: # return the content if its a binary one if resp.content_type.startswith('application/pdf') or \ resp.content_type.startswith('application/epub'): return await resp.read() return await self.handle_json_response(resp) else: raise ValueError('method expected: get, post, patch, delete, put')
[ "async", "def", "query", "(", "self", ",", "path", ",", "method", "=", "'get'", ",", "*", "*", "params", ")", ":", "if", "method", "in", "(", "'get'", ",", "'post'", ",", "'patch'", ",", "'delete'", ",", "'put'", ")", ":", "full_path", "=", "self", ".", "host", "+", "path", "if", "method", "==", "'get'", ":", "resp", "=", "await", "self", ".", "aio_sess", ".", "get", "(", "full_path", ",", "params", "=", "params", ")", "elif", "method", "==", "'post'", ":", "resp", "=", "await", "self", ".", "aio_sess", ".", "post", "(", "full_path", ",", "data", "=", "params", ")", "elif", "method", "==", "'patch'", ":", "resp", "=", "await", "self", ".", "aio_sess", ".", "patch", "(", "full_path", ",", "data", "=", "params", ")", "elif", "method", "==", "'delete'", ":", "resp", "=", "await", "self", ".", "aio_sess", ".", "delete", "(", "full_path", ",", "params", "=", "params", ",", "headers", "=", "params", ")", "elif", "method", "==", "'put'", ":", "resp", "=", "await", "self", ".", "aio_sess", ".", "put", "(", "full_path", ",", "data", "=", "params", ")", "async", "with", "resp", ":", "# return the content if its a binary one", "if", "resp", ".", "content_type", ".", "startswith", "(", "'application/pdf'", ")", "or", "resp", ".", "content_type", ".", "startswith", "(", "'application/epub'", ")", ":", "return", "await", "resp", ".", "read", "(", ")", "return", "await", "self", ".", "handle_json_response", "(", "resp", ")", "else", ":", "raise", "ValueError", "(", "'method expected: get, post, patch, delete, put'", ")" ]
42.8125
18
def _populate_from_list_blobs(self, creds, options, dry_run): # type: (SourcePath, StorageCredentials, Any, bool) -> StorageEntity """Internal generator for Azure remote blobs :param SourcePath self: this :param StorageCredentials creds: storage creds :param object options: download or synccopy options :param bool dry_run: dry run :rtype: StorageEntity :return: Azure storage entity object """ is_synccopy = isinstance(options, blobxfer.models.options.SyncCopy) for _path in self._paths: rpath = str(_path) sa = creds.get_storage_account(self.lookup_storage_account(rpath)) # ensure at least read permissions if not sa.can_read_object: raise RuntimeError( 'unable to populate sources for remote path {} as ' 'credential for storage account {} does not permit read ' 'access'.format(rpath, sa.name)) cont, dir = blobxfer.util.explode_azure_path(rpath) if sa.can_list_container_objects: for blob in blobxfer.operations.azure.blob.list_blobs( sa.block_blob_client, cont, dir, options.mode, options.recursive): # check for virtual directory placeholder if not is_synccopy: try: if (blob.metadata[ _METADATA_VIRTUAL_DIRECTORY] == 'true'): continue except KeyError: pass if not self._inclusion_check(blob.name): if dry_run: logger.info( '[DRY RUN] skipping due to filters: ' '{}/{}'.format(cont, blob.name)) continue for ase in self._handle_vectored_io_stripe( creds, options, is_synccopy, sa, blob, False, cont): if ase is None: continue yield ase else: blob = blobxfer.operations.azure.blob.get_blob_properties( sa.block_blob_client, cont, dir, options.mode) if blob is None: logger.error( 'blob {} not found in storage account {}'.format( rpath, sa.name)) return if not self._inclusion_check(blob.name): if dry_run: logger.info( '[DRY RUN] skipping due to filters: {}/{}'.format( cont, blob.name)) return for ase in self._handle_vectored_io_stripe( creds, options, is_synccopy, sa, blob, False, cont): if ase is None: continue yield ase
[ "def", "_populate_from_list_blobs", "(", "self", ",", "creds", ",", "options", ",", "dry_run", ")", ":", "# type: (SourcePath, StorageCredentials, Any, bool) -> StorageEntity", "is_synccopy", "=", "isinstance", "(", "options", ",", "blobxfer", ".", "models", ".", "options", ".", "SyncCopy", ")", "for", "_path", "in", "self", ".", "_paths", ":", "rpath", "=", "str", "(", "_path", ")", "sa", "=", "creds", ".", "get_storage_account", "(", "self", ".", "lookup_storage_account", "(", "rpath", ")", ")", "# ensure at least read permissions", "if", "not", "sa", ".", "can_read_object", ":", "raise", "RuntimeError", "(", "'unable to populate sources for remote path {} as '", "'credential for storage account {} does not permit read '", "'access'", ".", "format", "(", "rpath", ",", "sa", ".", "name", ")", ")", "cont", ",", "dir", "=", "blobxfer", ".", "util", ".", "explode_azure_path", "(", "rpath", ")", "if", "sa", ".", "can_list_container_objects", ":", "for", "blob", "in", "blobxfer", ".", "operations", ".", "azure", ".", "blob", ".", "list_blobs", "(", "sa", ".", "block_blob_client", ",", "cont", ",", "dir", ",", "options", ".", "mode", ",", "options", ".", "recursive", ")", ":", "# check for virtual directory placeholder", "if", "not", "is_synccopy", ":", "try", ":", "if", "(", "blob", ".", "metadata", "[", "_METADATA_VIRTUAL_DIRECTORY", "]", "==", "'true'", ")", ":", "continue", "except", "KeyError", ":", "pass", "if", "not", "self", ".", "_inclusion_check", "(", "blob", ".", "name", ")", ":", "if", "dry_run", ":", "logger", ".", "info", "(", "'[DRY RUN] skipping due to filters: '", "'{}/{}'", ".", "format", "(", "cont", ",", "blob", ".", "name", ")", ")", "continue", "for", "ase", "in", "self", ".", "_handle_vectored_io_stripe", "(", "creds", ",", "options", ",", "is_synccopy", ",", "sa", ",", "blob", ",", "False", ",", "cont", ")", ":", "if", "ase", "is", "None", ":", "continue", "yield", "ase", "else", ":", "blob", "=", "blobxfer", ".", "operations", ".", "azure", ".", "blob", ".", "get_blob_properties", "(", "sa", ".", "block_blob_client", ",", "cont", ",", "dir", ",", "options", ".", "mode", ")", "if", "blob", "is", "None", ":", "logger", ".", "error", "(", "'blob {} not found in storage account {}'", ".", "format", "(", "rpath", ",", "sa", ".", "name", ")", ")", "return", "if", "not", "self", ".", "_inclusion_check", "(", "blob", ".", "name", ")", ":", "if", "dry_run", ":", "logger", ".", "info", "(", "'[DRY RUN] skipping due to filters: {}/{}'", ".", "format", "(", "cont", ",", "blob", ".", "name", ")", ")", "return", "for", "ase", "in", "self", ".", "_handle_vectored_io_stripe", "(", "creds", ",", "options", ",", "is_synccopy", ",", "sa", ",", "blob", ",", "False", ",", "cont", ")", ":", "if", "ase", "is", "None", ":", "continue", "yield", "ase" ]
48.375
14.640625
def get_from_layer(self, name, layer=None): """Get a configuration value from the named layer. Parameters ---------- name : str The name of the value to retrieve layer: str The name of the layer to retrieve the value from. If it is not supplied then the outermost layer in which the key is defined will be used. """ if name not in self._children: if self._frozen: raise KeyError(name) self._children[name] = ConfigTree(layers=self._layers) child = self._children[name] if isinstance(child, ConfigNode): return child.get_value(layer) else: return child
[ "def", "get_from_layer", "(", "self", ",", "name", ",", "layer", "=", "None", ")", ":", "if", "name", "not", "in", "self", ".", "_children", ":", "if", "self", ".", "_frozen", ":", "raise", "KeyError", "(", "name", ")", "self", ".", "_children", "[", "name", "]", "=", "ConfigTree", "(", "layers", "=", "self", ".", "_layers", ")", "child", "=", "self", ".", "_children", "[", "name", "]", "if", "isinstance", "(", "child", ",", "ConfigNode", ")", ":", "return", "child", ".", "get_value", "(", "layer", ")", "else", ":", "return", "child" ]
35.65
15.5
def trt_pmf(matrices): """ Fold full disaggregation matrix to tectonic region type PMF. :param matrices: a matrix with T submatrices :returns: an array of T probabilities one per each tectonic region type """ ntrts, nmags, ndists, nlons, nlats, neps = matrices.shape pmf = numpy.zeros(ntrts) for t in range(ntrts): pmf[t] = 1. - numpy.prod( [1. - matrices[t, i, j, k, l, m] for i in range(nmags) for j in range(ndists) for k in range(nlons) for l in range(nlats) for m in range(neps)]) return pmf
[ "def", "trt_pmf", "(", "matrices", ")", ":", "ntrts", ",", "nmags", ",", "ndists", ",", "nlons", ",", "nlats", ",", "neps", "=", "matrices", ".", "shape", "pmf", "=", "numpy", ".", "zeros", "(", "ntrts", ")", "for", "t", "in", "range", "(", "ntrts", ")", ":", "pmf", "[", "t", "]", "=", "1.", "-", "numpy", ".", "prod", "(", "[", "1.", "-", "matrices", "[", "t", ",", "i", ",", "j", ",", "k", ",", "l", ",", "m", "]", "for", "i", "in", "range", "(", "nmags", ")", "for", "j", "in", "range", "(", "ndists", ")", "for", "k", "in", "range", "(", "nlons", ")", "for", "l", "in", "range", "(", "nlats", ")", "for", "m", "in", "range", "(", "neps", ")", "]", ")", "return", "pmf" ]
30.75
13.75
def call(self, obj, name, method, args, kwargs): """Trigger a method along with its beforebacks and afterbacks. Parameters ---------- name: str The name of the method that will be called args: tuple The arguments that will be passed to the base method kwargs: dict The keyword args that will be passed to the base method """ if name in self._callback_registry: beforebacks, afterbacks = zip(*self._callback_registry.get(name, [])) hold = [] for b in beforebacks: if b is not None: call = Data(name=name, kwargs=kwargs.copy(), args=args) v = b(obj, call) else: v = None hold.append(v) out = method(*args, **kwargs) for a, bval in zip(afterbacks, hold): if a is not None: a(obj, Data(before=bval, name=name, value=out)) elif callable(bval): # the beforeback's return value was an # afterback that expects to be called bval(out) return out else: return method(*args, **kwargs)
[ "def", "call", "(", "self", ",", "obj", ",", "name", ",", "method", ",", "args", ",", "kwargs", ")", ":", "if", "name", "in", "self", ".", "_callback_registry", ":", "beforebacks", ",", "afterbacks", "=", "zip", "(", "*", "self", ".", "_callback_registry", ".", "get", "(", "name", ",", "[", "]", ")", ")", "hold", "=", "[", "]", "for", "b", "in", "beforebacks", ":", "if", "b", "is", "not", "None", ":", "call", "=", "Data", "(", "name", "=", "name", ",", "kwargs", "=", "kwargs", ".", "copy", "(", ")", ",", "args", "=", "args", ")", "v", "=", "b", "(", "obj", ",", "call", ")", "else", ":", "v", "=", "None", "hold", ".", "append", "(", "v", ")", "out", "=", "method", "(", "*", "args", ",", "*", "*", "kwargs", ")", "for", "a", ",", "bval", "in", "zip", "(", "afterbacks", ",", "hold", ")", ":", "if", "a", "is", "not", "None", ":", "a", "(", "obj", ",", "Data", "(", "before", "=", "bval", ",", "name", "=", "name", ",", "value", "=", "out", ")", ")", "elif", "callable", "(", "bval", ")", ":", "# the beforeback's return value was an", "# afterback that expects to be called", "bval", "(", "out", ")", "return", "out", "else", ":", "return", "method", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
34.833333
17.75
def consume_value(self, ctx, opts): """ Retrieve default value and display it when prompt is disabled. """ value = click.Option.consume_value(self, ctx, opts) if not value: # value not found by click on command line # now check using our context helper in order into # local configuration # global configuration gandi = ctx.obj value = gandi.get(self.name) if value is not None: # value found in configuration display it self.display_value(ctx, value) else: if self.default is None and self.required: metavar = '' if self.type.name not in ['integer', 'text']: metavar = self.make_metavar() prompt = '%s %s' % (self.help, metavar) gandi.echo(prompt) return value
[ "def", "consume_value", "(", "self", ",", "ctx", ",", "opts", ")", ":", "value", "=", "click", ".", "Option", ".", "consume_value", "(", "self", ",", "ctx", ",", "opts", ")", "if", "not", "value", ":", "# value not found by click on command line", "# now check using our context helper in order into", "# local configuration", "# global configuration", "gandi", "=", "ctx", ".", "obj", "value", "=", "gandi", ".", "get", "(", "self", ".", "name", ")", "if", "value", "is", "not", "None", ":", "# value found in configuration display it", "self", ".", "display_value", "(", "ctx", ",", "value", ")", "else", ":", "if", "self", ".", "default", "is", "None", "and", "self", ".", "required", ":", "metavar", "=", "''", "if", "self", ".", "type", ".", "name", "not", "in", "[", "'integer'", ",", "'text'", "]", ":", "metavar", "=", "self", ".", "make_metavar", "(", ")", "prompt", "=", "'%s %s'", "%", "(", "self", ".", "help", ",", "metavar", ")", "gandi", ".", "echo", "(", "prompt", ")", "return", "value" ]
43.857143
12.52381
def read_eager(self): """Read readily available data. Raise EOFError if connection closed and no cooked data available. Return '' if no cooked data available otherwise. Don't block unless in the midst of an IAC sequence. """ self.process_rawq() while self.cookedq.tell() == 0 and not self.eof and self.sock_avail(): self.fill_rawq() self.process_rawq() return self.read_very_lazy()
[ "def", "read_eager", "(", "self", ")", ":", "self", ".", "process_rawq", "(", ")", "while", "self", ".", "cookedq", ".", "tell", "(", ")", "==", "0", "and", "not", "self", ".", "eof", "and", "self", ".", "sock_avail", "(", ")", ":", "self", ".", "fill_rawq", "(", ")", "self", ".", "process_rawq", "(", ")", "return", "self", ".", "read_very_lazy", "(", ")" ]
35.384615
18.769231
def getElementById(self, _id, root='root', useIndex=True): ''' getElementById - Searches and returns the first (should only be one) element with the given ID. @param id <str> - A string of the id attribute. @param root <AdvancedTag/'root'> - Search starting at a specific node, if provided. if string 'root', the root of the parsed tree will be used. @param useIndex <bool> If useIndex is True and ids are indexed [see constructor] only the index will be used. Otherwise a full search is performed. ''' (root, isFromRoot) = self._handleRootArg(root) if self.useIndex is True and self.indexIDs is True: element = self._idMap.get(_id, None) if isFromRoot is False and element is not None: if self._hasTagInParentLine(element, root) is False: element = None return element return AdvancedHTMLParser.getElementById(self, _id, root)
[ "def", "getElementById", "(", "self", ",", "_id", ",", "root", "=", "'root'", ",", "useIndex", "=", "True", ")", ":", "(", "root", ",", "isFromRoot", ")", "=", "self", ".", "_handleRootArg", "(", "root", ")", "if", "self", ".", "useIndex", "is", "True", "and", "self", ".", "indexIDs", "is", "True", ":", "element", "=", "self", ".", "_idMap", ".", "get", "(", "_id", ",", "None", ")", "if", "isFromRoot", "is", "False", "and", "element", "is", "not", "None", ":", "if", "self", ".", "_hasTagInParentLine", "(", "element", ",", "root", ")", "is", "False", ":", "element", "=", "None", "return", "element", "return", "AdvancedHTMLParser", ".", "getElementById", "(", "self", ",", "_id", ",", "root", ")" ]
44.347826
35.913043
def encode(self): """ Encodes the value of the field and put it in the element also make the check for nil=true if there is one :return: returns the encoded element :rtype: xml.etree.ElementTree.Element """ element = ElementTree.Element(self.name) element = self._set_nil(element, lambda value: str(value)) return element
[ "def", "encode", "(", "self", ")", ":", "element", "=", "ElementTree", ".", "Element", "(", "self", ".", "name", ")", "element", "=", "self", ".", "_set_nil", "(", "element", ",", "lambda", "value", ":", "str", "(", "value", ")", ")", "return", "element" ]
34.909091
14.909091
def add_item(self, item, field_name=None): """ Add the item to the specified section. Intended for use with items of settings.ARMSTRONG_SECTION_ITEM_MODEL. Behavior on other items is undefined. """ field_name = self._choose_field_name(field_name) related_manager = getattr(item, field_name) related_manager.add(self)
[ "def", "add_item", "(", "self", ",", "item", ",", "field_name", "=", "None", ")", ":", "field_name", "=", "self", ".", "_choose_field_name", "(", "field_name", ")", "related_manager", "=", "getattr", "(", "item", ",", "field_name", ")", "related_manager", ".", "add", "(", "self", ")" ]
37.2
12.4
def status(self): ''' :returns: A dictionary with the following: * 'num': Total number of hosts already probed * 'up': Number of hosts up * 'down': Number of hosts down * 'ratio': Ratio between 'up'/'down' as float Ratio: * ``100%`` up == `1.0` * ``10%`` up == `0.1` * ``0%`` up == `0.0` ''' num = len(self.probe) up = len([h for h in self.probe if self.probe[h]['up']]) ratio = up/num if num != 0 else 0 # over 9000! return dict(num=num, up=up, down=num-up, ratio=ratio)
[ "def", "status", "(", "self", ")", ":", "num", "=", "len", "(", "self", ".", "probe", ")", "up", "=", "len", "(", "[", "h", "for", "h", "in", "self", ".", "probe", "if", "self", ".", "probe", "[", "h", "]", "[", "'up'", "]", "]", ")", "ratio", "=", "up", "/", "num", "if", "num", "!=", "0", "else", "0", "# over 9000!", "return", "dict", "(", "num", "=", "num", ",", "up", "=", "up", ",", "down", "=", "num", "-", "up", ",", "ratio", "=", "ratio", ")" ]
26.727273
21.454545
def get_interfaces(self, socket_connection=None): """Returns the a list of Interface objects the service implements.""" if not socket_connection: socket_connection = self.open_connection() close_socket = True else: close_socket = False # noinspection PyUnresolvedReferences _service = self.handler(self._interfaces["org.varlink.service"], socket_connection) self.info = _service.GetInfo() if close_socket: socket_connection.close() return self.info['interfaces']
[ "def", "get_interfaces", "(", "self", ",", "socket_connection", "=", "None", ")", ":", "if", "not", "socket_connection", ":", "socket_connection", "=", "self", ".", "open_connection", "(", ")", "close_socket", "=", "True", "else", ":", "close_socket", "=", "False", "# noinspection PyUnresolvedReferences", "_service", "=", "self", ".", "handler", "(", "self", ".", "_interfaces", "[", "\"org.varlink.service\"", "]", ",", "socket_connection", ")", "self", ".", "info", "=", "_service", ".", "GetInfo", "(", ")", "if", "close_socket", ":", "socket_connection", ".", "close", "(", ")", "return", "self", ".", "info", "[", "'interfaces'", "]" ]
35.125
17.0625
def cleanup(self): """ Cleanup resources used during execution """ if self.local_port is not None: logger.debug(("Stopping ssh tunnel {0}:{1}:{2} for " "{3}@{4}".format(self.local_port, self.remote_address, self.remote_port, self.username, self.address))) if self.forward is not None: self.forward.stop() self.forward.join() if self.transport is not None: self.transport.close()
[ "def", "cleanup", "(", "self", ")", ":", "if", "self", ".", "local_port", "is", "not", "None", ":", "logger", ".", "debug", "(", "(", "\"Stopping ssh tunnel {0}:{1}:{2} for \"", "\"{3}@{4}\"", ".", "format", "(", "self", ".", "local_port", ",", "self", ".", "remote_address", ",", "self", ".", "remote_port", ",", "self", ".", "username", ",", "self", ".", "address", ")", ")", ")", "if", "self", ".", "forward", "is", "not", "None", ":", "self", ".", "forward", ".", "stop", "(", ")", "self", ".", "forward", ".", "join", "(", ")", "if", "self", ".", "transport", "is", "not", "None", ":", "self", ".", "transport", ".", "close", "(", ")" ]
42.3125
10.3125
def check_include_exclude(attributes): """Check __include__ and __exclude__ attributes. :type attributes: dict """ include = attributes.get('__include__', tuple()) exclude = attributes.get('__exclude__', tuple()) if not isinstance(include, tuple): raise TypeError("Attribute __include__ must be a tuple.") if not isinstance(exclude, tuple): raise TypeError("Attribute __exclude__ must be a tuple.") if all((not include, not exclude)): return None if all((include, exclude)): raise AttributeError("Usage of __include__ and __exclude__ " "at the same time is prohibited.")
[ "def", "check_include_exclude", "(", "attributes", ")", ":", "include", "=", "attributes", ".", "get", "(", "'__include__'", ",", "tuple", "(", ")", ")", "exclude", "=", "attributes", ".", "get", "(", "'__exclude__'", ",", "tuple", "(", ")", ")", "if", "not", "isinstance", "(", "include", ",", "tuple", ")", ":", "raise", "TypeError", "(", "\"Attribute __include__ must be a tuple.\"", ")", "if", "not", "isinstance", "(", "exclude", ",", "tuple", ")", ":", "raise", "TypeError", "(", "\"Attribute __exclude__ must be a tuple.\"", ")", "if", "all", "(", "(", "not", "include", ",", "not", "exclude", ")", ")", ":", "return", "None", "if", "all", "(", "(", "include", ",", "exclude", ")", ")", ":", "raise", "AttributeError", "(", "\"Usage of __include__ and __exclude__ \"", "\"at the same time is prohibited.\"", ")" ]
35.45
19.5
def dprintx(passeditem, special=False): """Print Text if DEBUGALL set, optionally with PrettyPrint. Args: passeditem (str): item to print special (bool): determines if item prints with PrettyPrint or regular print. """ if DEBUGALL: if special: from pprint import pprint pprint(passeditem) else: print("%s%s%s" % (C_TI, passeditem, C_NORM))
[ "def", "dprintx", "(", "passeditem", ",", "special", "=", "False", ")", ":", "if", "DEBUGALL", ":", "if", "special", ":", "from", "pprint", "import", "pprint", "pprint", "(", "passeditem", ")", "else", ":", "print", "(", "\"%s%s%s\"", "%", "(", "C_TI", ",", "passeditem", ",", "C_NORM", ")", ")" ]
29
16.066667
def _set_show_bare_metal_state(self, v, load=False): """ Setter method for show_bare_metal_state, mapped from YANG variable /brocade_preprovision_rpc/show_bare_metal_state (rpc) If this variable is read-only (config: false) in the source YANG file, then _set_show_bare_metal_state is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_show_bare_metal_state() directly. """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=show_bare_metal_state.show_bare_metal_state, is_leaf=True, yang_name="show-bare-metal-state", rest_name="show-bare-metal-state", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, extensions={u'tailf-common': {u'info': u'Retrieve bare-metal state.', u'hidden': u'rpccmd', u'actionpoint': u'get-bare-metal-state'}}, namespace='urn:brocade.com:mgmt:brocade-preprovision', defining_module='brocade-preprovision', yang_type='rpc', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """show_bare_metal_state must be of a type compatible with rpc""", 'defined-type': "rpc", 'generated-type': """YANGDynClass(base=show_bare_metal_state.show_bare_metal_state, is_leaf=True, yang_name="show-bare-metal-state", rest_name="show-bare-metal-state", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, extensions={u'tailf-common': {u'info': u'Retrieve bare-metal state.', u'hidden': u'rpccmd', u'actionpoint': u'get-bare-metal-state'}}, namespace='urn:brocade.com:mgmt:brocade-preprovision', defining_module='brocade-preprovision', yang_type='rpc', is_config=True)""", }) self.__show_bare_metal_state = t if hasattr(self, '_set'): self._set()
[ "def", "_set_show_bare_metal_state", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", "v", ",", "base", "=", "show_bare_metal_state", ".", "show_bare_metal_state", ",", "is_leaf", "=", "True", ",", "yang_name", "=", "\"show-bare-metal-state\"", ",", "rest_name", "=", "\"show-bare-metal-state\"", ",", "parent", "=", "self", ",", "path_helper", "=", "self", ".", "_path_helper", ",", "extmethods", "=", "self", ".", "_extmethods", ",", "register_paths", "=", "False", ",", "extensions", "=", "{", "u'tailf-common'", ":", "{", "u'info'", ":", "u'Retrieve bare-metal state.'", ",", "u'hidden'", ":", "u'rpccmd'", ",", "u'actionpoint'", ":", "u'get-bare-metal-state'", "}", "}", ",", "namespace", "=", "'urn:brocade.com:mgmt:brocade-preprovision'", ",", "defining_module", "=", "'brocade-preprovision'", ",", "yang_type", "=", "'rpc'", ",", "is_config", "=", "True", ")", "except", "(", "TypeError", ",", "ValueError", ")", ":", "raise", "ValueError", "(", "{", "'error-string'", ":", "\"\"\"show_bare_metal_state must be of a type compatible with rpc\"\"\"", ",", "'defined-type'", ":", "\"rpc\"", ",", "'generated-type'", ":", "\"\"\"YANGDynClass(base=show_bare_metal_state.show_bare_metal_state, is_leaf=True, yang_name=\"show-bare-metal-state\", rest_name=\"show-bare-metal-state\", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, extensions={u'tailf-common': {u'info': u'Retrieve bare-metal state.', u'hidden': u'rpccmd', u'actionpoint': u'get-bare-metal-state'}}, namespace='urn:brocade.com:mgmt:brocade-preprovision', defining_module='brocade-preprovision', yang_type='rpc', is_config=True)\"\"\"", ",", "}", ")", "self", ".", "__show_bare_metal_state", "=", "t", "if", "hasattr", "(", "self", ",", "'_set'", ")", ":", "self", ".", "_set", "(", ")" ]
83.727273
39.863636
def message_with_placeholders(message): """ Return an ASGI message, with any body-type content omitted and replaced with a placeholder. """ new_message = message.copy() for attr in PLACEHOLDER_FORMAT.keys(): if message.get(attr) is not None: content = message[attr] placeholder = PLACEHOLDER_FORMAT[attr].format(length=len(content)) new_message[attr] = placeholder return new_message
[ "def", "message_with_placeholders", "(", "message", ")", ":", "new_message", "=", "message", ".", "copy", "(", ")", "for", "attr", "in", "PLACEHOLDER_FORMAT", ".", "keys", "(", ")", ":", "if", "message", ".", "get", "(", "attr", ")", "is", "not", "None", ":", "content", "=", "message", "[", "attr", "]", "placeholder", "=", "PLACEHOLDER_FORMAT", "[", "attr", "]", ".", "format", "(", "length", "=", "len", "(", "content", ")", ")", "new_message", "[", "attr", "]", "=", "placeholder", "return", "new_message" ]
37
10.666667
def _bit_is_one(self, n, hash_bytes): """ Check if the n (index) of hash_bytes is 1 or 0. """ scale = 16 # hexadecimal if not hash_bytes[int(n / (scale / 2))] >> int( (scale / 2) - ((n % (scale / 2)) + 1)) & 1 == 1: return False return True
[ "def", "_bit_is_one", "(", "self", ",", "n", ",", "hash_bytes", ")", ":", "scale", "=", "16", "# hexadecimal", "if", "not", "hash_bytes", "[", "int", "(", "n", "/", "(", "scale", "/", "2", ")", ")", "]", ">>", "int", "(", "(", "scale", "/", "2", ")", "-", "(", "(", "n", "%", "(", "scale", "/", "2", ")", ")", "+", "1", ")", ")", "&", "1", "==", "1", ":", "return", "False", "return", "True" ]
28.090909
16.454545
def set(name, data, **kwargs): ''' Set debconf selections .. code-block:: yaml <state_id>: debconf.set: - name: <name> - data: <question>: {'type': <type>, 'value': <value>} <question>: {'type': <type>, 'value': <value>} <state_id>: debconf.set: - name: <name> - data: <question>: {'type': <type>, 'value': <value>} <question>: {'type': <type>, 'value': <value>} name: The package name to set answers for. data: A set of questions/answers for debconf. Note that everything under this must be indented twice. question: The question the is being pre-answered type: The type of question that is being asked (string, boolean, select, etc.) value: The answer to the question ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''} current = __salt__['debconf.show'](name) for (key, args) in six.iteritems(data): # For debconf data, valid booleans are 'true' and 'false'; # But str()'ing the args['value'] will result in 'True' and 'False' # which will be ignored and overridden by a dpkg-reconfigure. # So we should manually set these values to lowercase ones, # before any str() call is performed. if args['type'] == 'boolean': args['value'] = 'true' if args['value'] else 'false' if current is not None and [key, args['type'], six.text_type(args['value'])] in current: if ret['comment'] is '': ret['comment'] = 'Unchanged answers: ' ret['comment'] += ('{0} ').format(key) else: if __opts__['test']: ret['result'] = None ret['changes'][key] = ('New value: {0}').format(args['value']) else: if __salt__['debconf.set'](name, key, args['type'], args['value']): if args['type'] == 'password': ret['changes'][key] = '(password hidden)' else: ret['changes'][key] = ('{0}').format(args['value']) else: ret['result'] = False ret['comment'] = 'Some settings failed to be applied.' ret['changes'][key] = 'Failed to set!' if not ret['changes']: ret['comment'] = 'All specified answers are already set' return ret
[ "def", "set", "(", "name", ",", "data", ",", "*", "*", "kwargs", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'changes'", ":", "{", "}", ",", "'result'", ":", "True", ",", "'comment'", ":", "''", "}", "current", "=", "__salt__", "[", "'debconf.show'", "]", "(", "name", ")", "for", "(", "key", ",", "args", ")", "in", "six", ".", "iteritems", "(", "data", ")", ":", "# For debconf data, valid booleans are 'true' and 'false';", "# But str()'ing the args['value'] will result in 'True' and 'False'", "# which will be ignored and overridden by a dpkg-reconfigure.", "# So we should manually set these values to lowercase ones,", "# before any str() call is performed.", "if", "args", "[", "'type'", "]", "==", "'boolean'", ":", "args", "[", "'value'", "]", "=", "'true'", "if", "args", "[", "'value'", "]", "else", "'false'", "if", "current", "is", "not", "None", "and", "[", "key", ",", "args", "[", "'type'", "]", ",", "six", ".", "text_type", "(", "args", "[", "'value'", "]", ")", "]", "in", "current", ":", "if", "ret", "[", "'comment'", "]", "is", "''", ":", "ret", "[", "'comment'", "]", "=", "'Unchanged answers: '", "ret", "[", "'comment'", "]", "+=", "(", "'{0} '", ")", ".", "format", "(", "key", ")", "else", ":", "if", "__opts__", "[", "'test'", "]", ":", "ret", "[", "'result'", "]", "=", "None", "ret", "[", "'changes'", "]", "[", "key", "]", "=", "(", "'New value: {0}'", ")", ".", "format", "(", "args", "[", "'value'", "]", ")", "else", ":", "if", "__salt__", "[", "'debconf.set'", "]", "(", "name", ",", "key", ",", "args", "[", "'type'", "]", ",", "args", "[", "'value'", "]", ")", ":", "if", "args", "[", "'type'", "]", "==", "'password'", ":", "ret", "[", "'changes'", "]", "[", "key", "]", "=", "'(password hidden)'", "else", ":", "ret", "[", "'changes'", "]", "[", "key", "]", "=", "(", "'{0}'", ")", ".", "format", "(", "args", "[", "'value'", "]", ")", "else", ":", "ret", "[", "'result'", "]", "=", "False", "ret", "[", "'comment'", "]", "=", "'Some settings failed to be applied.'", "ret", "[", "'changes'", "]", "[", "key", "]", "=", "'Failed to set!'", "if", "not", "ret", "[", "'changes'", "]", ":", "ret", "[", "'comment'", "]", "=", "'All specified answers are already set'", "return", "ret" ]
32.415584
24.025974
def evaluate(self, verbose=True, passes=None): """Summary Returns: TYPE: Description """ if self.is_pivot: index, pivot, columns = LazyOpResult( self.expr, self.weld_type, 0 ).evaluate(verbose=verbose, passes=passes) df_dict = {} for i, column_name in enumerate(columns): df_dict[column_name] = pivot[i] return DataFrameWeld(pd.DataFrame(df_dict, index=index)) else: df = pd.DataFrame(columns=[]) weldvec_type_list = [] for type in self.column_types: weldvec_type_list.append(WeldVec(type)) columns = LazyOpResult( grizzly_impl.unzip_columns( self.expr, self.column_types ), WeldStruct(weldvec_type_list), 0 ).evaluate(verbose=verbose, passes=passes) for i, column_name in enumerate(self.column_names): df[column_name] = columns[i] return DataFrameWeld(df)
[ "def", "evaluate", "(", "self", ",", "verbose", "=", "True", ",", "passes", "=", "None", ")", ":", "if", "self", ".", "is_pivot", ":", "index", ",", "pivot", ",", "columns", "=", "LazyOpResult", "(", "self", ".", "expr", ",", "self", ".", "weld_type", ",", "0", ")", ".", "evaluate", "(", "verbose", "=", "verbose", ",", "passes", "=", "passes", ")", "df_dict", "=", "{", "}", "for", "i", ",", "column_name", "in", "enumerate", "(", "columns", ")", ":", "df_dict", "[", "column_name", "]", "=", "pivot", "[", "i", "]", "return", "DataFrameWeld", "(", "pd", ".", "DataFrame", "(", "df_dict", ",", "index", "=", "index", ")", ")", "else", ":", "df", "=", "pd", ".", "DataFrame", "(", "columns", "=", "[", "]", ")", "weldvec_type_list", "=", "[", "]", "for", "type", "in", "self", ".", "column_types", ":", "weldvec_type_list", ".", "append", "(", "WeldVec", "(", "type", ")", ")", "columns", "=", "LazyOpResult", "(", "grizzly_impl", ".", "unzip_columns", "(", "self", ".", "expr", ",", "self", ".", "column_types", ")", ",", "WeldStruct", "(", "weldvec_type_list", ")", ",", "0", ")", ".", "evaluate", "(", "verbose", "=", "verbose", ",", "passes", "=", "passes", ")", "for", "i", ",", "column_name", "in", "enumerate", "(", "self", ".", "column_names", ")", ":", "df", "[", "column_name", "]", "=", "columns", "[", "i", "]", "return", "DataFrameWeld", "(", "df", ")" ]
32.057143
14.771429
async def async_open(self) -> None: """Opens connection to the LifeSOS ethernet interface.""" await self._loop.create_connection( lambda: self, self._host, self._port)
[ "async", "def", "async_open", "(", "self", ")", "->", "None", ":", "await", "self", ".", "_loop", ".", "create_connection", "(", "lambda", ":", "self", ",", "self", ".", "_host", ",", "self", ".", "_port", ")" ]
30.571429
13.857143
def from_optional_dict(cls, d: Optional[dict], force_snake_case: bool=True,force_cast: bool=False, restrict: bool=True) -> TOption[T]: """From dict to optional instance. :param d: Dict :param force_snake_case: Keys are transformed to snake case in order to compliant PEP8 if True :param force_cast: Cast forcibly if True :param restrict: Prohibit extra parameters if True :return: Instance Usage: >>> from owlmixin.samples import Human >>> Human.from_optional_dict(None).is_none() True >>> Human.from_optional_dict({}).get() # doctest: +NORMALIZE_WHITESPACE Traceback (most recent call last): ... owlmixin.errors.RequiredError: . ∧,,_∧ ,___________________ ⊂ ( ・ω・ )つ- < Required error /// /::/ `------------------- |::|/⊂ヽノ|::|」 / ̄ ̄旦 ̄ ̄ ̄/| ______/ | | |------ー----ー|/ <BLANKLINE> `owlmixin.samples.Human#id: int` is empty!! <BLANKLINE> * If `id` is certainly required, specify anything. * If `id` is optional, change type from `int` to `TOption[int]` <BLANKLINE> """ return TOption(cls.from_dict(d, force_snake_case=force_snake_case, force_cast=force_cast, restrict=restrict) if d is not None else None)
[ "def", "from_optional_dict", "(", "cls", ",", "d", ":", "Optional", "[", "dict", "]", ",", "force_snake_case", ":", "bool", "=", "True", ",", "force_cast", ":", "bool", "=", "False", ",", "restrict", ":", "bool", "=", "True", ")", "->", "TOption", "[", "T", "]", ":", "return", "TOption", "(", "cls", ".", "from_dict", "(", "d", ",", "force_snake_case", "=", "force_snake_case", ",", "force_cast", "=", "force_cast", ",", "restrict", "=", "restrict", ")", "if", "d", "is", "not", "None", "else", "None", ")" ]
42.351351
21.243243
def is_revoked(self, crl_list): """ Given a list of trusted CRL (their signature has already been verified with trusted anchors), this function returns True if the certificate is marked as revoked by one of those CRL. Note that if the Certificate was on hold in a previous CRL and is now valid again in a new CRL and bot are in the list, it will be considered revoked: this is because _all_ CRLs are checked (not only the freshest) and revocation status is not handled. Also note that the check on the issuer is performed on the Authority Key Identifier if available in _both_ the CRL and the Cert. Otherwise, the issuers are simply compared. """ for c in crl_list: if (self.authorityKeyID is not None and c.authorityKeyID is not None and self.authorityKeyID == c.authorityKeyID): return self.serial in map(lambda x: x[0], c.revoked_cert_serials) elif (self.issuer == c.issuer): return self.serial in map(lambda x: x[0], c.revoked_cert_serials) return False
[ "def", "is_revoked", "(", "self", ",", "crl_list", ")", ":", "for", "c", "in", "crl_list", ":", "if", "(", "self", ".", "authorityKeyID", "is", "not", "None", "and", "c", ".", "authorityKeyID", "is", "not", "None", "and", "self", ".", "authorityKeyID", "==", "c", ".", "authorityKeyID", ")", ":", "return", "self", ".", "serial", "in", "map", "(", "lambda", "x", ":", "x", "[", "0", "]", ",", "c", ".", "revoked_cert_serials", ")", "elif", "(", "self", ".", "issuer", "==", "c", ".", "issuer", ")", ":", "return", "self", ".", "serial", "in", "map", "(", "lambda", "x", ":", "x", "[", "0", "]", ",", "c", ".", "revoked_cert_serials", ")", "return", "False" ]
47.75
22.416667
def sqllab(self): """SQL Editor""" d = { 'defaultDbId': config.get('SQLLAB_DEFAULT_DBID'), 'common': self.common_bootsrap_payload(), } return self.render_template( 'superset/basic.html', entry='sqllab', bootstrap_data=json.dumps(d, default=utils.json_iso_dttm_ser), )
[ "def", "sqllab", "(", "self", ")", ":", "d", "=", "{", "'defaultDbId'", ":", "config", ".", "get", "(", "'SQLLAB_DEFAULT_DBID'", ")", ",", "'common'", ":", "self", ".", "common_bootsrap_payload", "(", ")", ",", "}", "return", "self", ".", "render_template", "(", "'superset/basic.html'", ",", "entry", "=", "'sqllab'", ",", "bootstrap_data", "=", "json", ".", "dumps", "(", "d", ",", "default", "=", "utils", ".", "json_iso_dttm_ser", ")", ",", ")" ]
32.454545
18.454545
def _manage_child_object(self, nurest_object, method=HTTP_METHOD_GET, async=False, callback=None, handler=None, response_choice=None, commit=False): """ Low level child management. Send given HTTP method with given nurest_object to given ressource of current object Args: nurest_object: the NURESTObject object to manage method: the HTTP method to use (GET, POST, PUT, DELETE) callback: the callback to call at the end handler: a custom handler to call when complete, before calling the callback commit: True to auto commit changes in the current object Returns: Returns the object and connection (object, connection) """ url = None if method == HTTP_METHOD_POST: url = self.get_resource_url_for_child_type(nurest_object.__class__) else: url = self.get_resource_url() if response_choice is not None: url += '?responseChoice=%s' % response_choice request = NURESTRequest(method=method, url=url, data=nurest_object.to_dict()) user_info = {'nurest_object': nurest_object, 'commit': commit} if not handler: handler = self._did_perform_standard_operation if async: return self.send_request(request=request, async=async, local_callback=handler, remote_callback=callback, user_info=user_info) else: connection = self.send_request(request=request, user_info=user_info) return handler(connection)
[ "def", "_manage_child_object", "(", "self", ",", "nurest_object", ",", "method", "=", "HTTP_METHOD_GET", ",", "async", "=", "False", ",", "callback", "=", "None", ",", "handler", "=", "None", ",", "response_choice", "=", "None", ",", "commit", "=", "False", ")", ":", "url", "=", "None", "if", "method", "==", "HTTP_METHOD_POST", ":", "url", "=", "self", ".", "get_resource_url_for_child_type", "(", "nurest_object", ".", "__class__", ")", "else", ":", "url", "=", "self", ".", "get_resource_url", "(", ")", "if", "response_choice", "is", "not", "None", ":", "url", "+=", "'?responseChoice=%s'", "%", "response_choice", "request", "=", "NURESTRequest", "(", "method", "=", "method", ",", "url", "=", "url", ",", "data", "=", "nurest_object", ".", "to_dict", "(", ")", ")", "user_info", "=", "{", "'nurest_object'", ":", "nurest_object", ",", "'commit'", ":", "commit", "}", "if", "not", "handler", ":", "handler", "=", "self", ".", "_did_perform_standard_operation", "if", "async", ":", "return", "self", ".", "send_request", "(", "request", "=", "request", ",", "async", "=", "async", ",", "local_callback", "=", "handler", ",", "remote_callback", "=", "callback", ",", "user_info", "=", "user_info", ")", "else", ":", "connection", "=", "self", ".", "send_request", "(", "request", "=", "request", ",", "user_info", "=", "user_info", ")", "return", "handler", "(", "connection", ")" ]
44.371429
30.457143
def _add_default_options(self) -> None: """Add default command line options to the parser. """ # Updating the trust stores update_stores_group = OptionGroup(self._parser, 'Trust stores options', '') update_stores_group.add_option( '--update_trust_stores', help='Update the default trust stores used by SSLyze. The latest stores will be downloaded from ' 'https://github.com/nabla-c0d3/trust_stores_observatory. This option is meant to be used separately, ' 'and will silence any other command line option supplied to SSLyze.', dest='update_trust_stores', action='store_true', ) self._parser.add_option_group(update_stores_group) # Client certificate options clientcert_group = OptionGroup(self._parser, 'Client certificate options', '') clientcert_group.add_option( '--cert', help='Client certificate chain filename. The certificates must be in PEM format and must be sorted ' 'starting with the subject\'s client certificate, followed by intermediate CA certificates if ' 'applicable.', dest='cert' ) clientcert_group.add_option( '--key', help='Client private key filename.', dest='key' ) clientcert_group.add_option( '--keyform', help='Client private key format. DER or PEM (default).', dest='keyform', default='PEM' ) clientcert_group.add_option( '--pass', help='Client private key passphrase.', dest='keypass', default='' ) self._parser.add_option_group(clientcert_group) # Input / output output_group = OptionGroup(self._parser, 'Input and output options', '') # XML output output_group.add_option( '--xml_out', help='Write the scan results as an XML document to the file XML_FILE. If XML_FILE is set to "-", the XML ' 'output will instead be printed to stdout. The corresponding XML Schema Definition is available at ' './docs/xml_out.xsd', dest='xml_file', default=None ) # JSON output output_group.add_option( '--json_out', help='Write the scan results as a JSON document to the file JSON_FILE. If JSON_FILE is set to "-", the ' 'JSON output will instead be printed to stdout. The resulting JSON file is a serialized version of ' 'the ScanResult objects described in SSLyze\'s Python API: the nodes and attributes will be the same. ' 'See https://nabla-c0d3.github.io/sslyze/documentation/available-scan-commands.html for more details.', dest='json_file', default=None ) # Read targets from input file output_group.add_option( '--targets_in', help='Read the list of targets to scan from the file TARGETS_IN. It should contain one host:port per ' 'line.', dest='targets_in', default=None ) # No text output output_group.add_option( '--quiet', action='store_true', dest='quiet', help='Do not output anything to stdout; useful when using --xml_out or --json_out.' ) self._parser.add_option_group(output_group) # Connectivity option group connect_group = OptionGroup(self._parser, 'Connectivity options', '') # Connection speed connect_group.add_option( '--slow_connection', help='Greatly reduce the number of concurrent connections initiated by SSLyze. This will make the scans ' 'slower but more reliable if the connection between your host and the server is slow, or if the ' 'server cannot handle many concurrent connections. Enable this option if you are getting a lot of ' 'timeouts or errors.', action='store_true', dest='slow_connection', ) # HTTP CONNECT Proxy connect_group.add_option( '--https_tunnel', help='Tunnel all traffic to the target server(s) through an HTTP CONNECT proxy. HTTP_TUNNEL should be the ' 'proxy\'s URL: \'http://USER:PW@HOST:PORT/\'. For proxies requiring authentication, only Basic ' 'Authentication is supported.', dest='https_tunnel', default=None ) # STARTTLS connect_group.add_option( '--starttls', help='Perform a StartTLS handshake when connecting to the target server(s). ' '{}'.format(self.START_TLS_USAGE), dest='starttls', default=None ) connect_group.add_option( '--xmpp_to', help='Optional setting for STARTTLS XMPP. XMPP_TO should be the hostname to be put in the \'to\' ' 'attribute of the XMPP stream. Default is the server\'s hostname.', dest='xmpp_to', default=None ) # Server Name Indication connect_group.add_option( '--sni', help='Use Server Name Indication to specify the hostname to connect to. Will only affect TLS 1.0+ ' 'connections.', dest='sni', default=None ) self._parser.add_option_group(connect_group)
[ "def", "_add_default_options", "(", "self", ")", "->", "None", ":", "# Updating the trust stores", "update_stores_group", "=", "OptionGroup", "(", "self", ".", "_parser", ",", "'Trust stores options'", ",", "''", ")", "update_stores_group", ".", "add_option", "(", "'--update_trust_stores'", ",", "help", "=", "'Update the default trust stores used by SSLyze. The latest stores will be downloaded from '", "'https://github.com/nabla-c0d3/trust_stores_observatory. This option is meant to be used separately, '", "'and will silence any other command line option supplied to SSLyze.'", ",", "dest", "=", "'update_trust_stores'", ",", "action", "=", "'store_true'", ",", ")", "self", ".", "_parser", ".", "add_option_group", "(", "update_stores_group", ")", "# Client certificate options", "clientcert_group", "=", "OptionGroup", "(", "self", ".", "_parser", ",", "'Client certificate options'", ",", "''", ")", "clientcert_group", ".", "add_option", "(", "'--cert'", ",", "help", "=", "'Client certificate chain filename. The certificates must be in PEM format and must be sorted '", "'starting with the subject\\'s client certificate, followed by intermediate CA certificates if '", "'applicable.'", ",", "dest", "=", "'cert'", ")", "clientcert_group", ".", "add_option", "(", "'--key'", ",", "help", "=", "'Client private key filename.'", ",", "dest", "=", "'key'", ")", "clientcert_group", ".", "add_option", "(", "'--keyform'", ",", "help", "=", "'Client private key format. DER or PEM (default).'", ",", "dest", "=", "'keyform'", ",", "default", "=", "'PEM'", ")", "clientcert_group", ".", "add_option", "(", "'--pass'", ",", "help", "=", "'Client private key passphrase.'", ",", "dest", "=", "'keypass'", ",", "default", "=", "''", ")", "self", ".", "_parser", ".", "add_option_group", "(", "clientcert_group", ")", "# Input / output", "output_group", "=", "OptionGroup", "(", "self", ".", "_parser", ",", "'Input and output options'", ",", "''", ")", "# XML output", "output_group", ".", "add_option", "(", "'--xml_out'", ",", "help", "=", "'Write the scan results as an XML document to the file XML_FILE. If XML_FILE is set to \"-\", the XML '", "'output will instead be printed to stdout. The corresponding XML Schema Definition is available at '", "'./docs/xml_out.xsd'", ",", "dest", "=", "'xml_file'", ",", "default", "=", "None", ")", "# JSON output", "output_group", ".", "add_option", "(", "'--json_out'", ",", "help", "=", "'Write the scan results as a JSON document to the file JSON_FILE. If JSON_FILE is set to \"-\", the '", "'JSON output will instead be printed to stdout. The resulting JSON file is a serialized version of '", "'the ScanResult objects described in SSLyze\\'s Python API: the nodes and attributes will be the same. '", "'See https://nabla-c0d3.github.io/sslyze/documentation/available-scan-commands.html for more details.'", ",", "dest", "=", "'json_file'", ",", "default", "=", "None", ")", "# Read targets from input file", "output_group", ".", "add_option", "(", "'--targets_in'", ",", "help", "=", "'Read the list of targets to scan from the file TARGETS_IN. It should contain one host:port per '", "'line.'", ",", "dest", "=", "'targets_in'", ",", "default", "=", "None", ")", "# No text output", "output_group", ".", "add_option", "(", "'--quiet'", ",", "action", "=", "'store_true'", ",", "dest", "=", "'quiet'", ",", "help", "=", "'Do not output anything to stdout; useful when using --xml_out or --json_out.'", ")", "self", ".", "_parser", ".", "add_option_group", "(", "output_group", ")", "# Connectivity option group", "connect_group", "=", "OptionGroup", "(", "self", ".", "_parser", ",", "'Connectivity options'", ",", "''", ")", "# Connection speed", "connect_group", ".", "add_option", "(", "'--slow_connection'", ",", "help", "=", "'Greatly reduce the number of concurrent connections initiated by SSLyze. This will make the scans '", "'slower but more reliable if the connection between your host and the server is slow, or if the '", "'server cannot handle many concurrent connections. Enable this option if you are getting a lot of '", "'timeouts or errors.'", ",", "action", "=", "'store_true'", ",", "dest", "=", "'slow_connection'", ",", ")", "# HTTP CONNECT Proxy", "connect_group", ".", "add_option", "(", "'--https_tunnel'", ",", "help", "=", "'Tunnel all traffic to the target server(s) through an HTTP CONNECT proxy. HTTP_TUNNEL should be the '", "'proxy\\'s URL: \\'http://USER:PW@HOST:PORT/\\'. For proxies requiring authentication, only Basic '", "'Authentication is supported.'", ",", "dest", "=", "'https_tunnel'", ",", "default", "=", "None", ")", "# STARTTLS", "connect_group", ".", "add_option", "(", "'--starttls'", ",", "help", "=", "'Perform a StartTLS handshake when connecting to the target server(s). '", "'{}'", ".", "format", "(", "self", ".", "START_TLS_USAGE", ")", ",", "dest", "=", "'starttls'", ",", "default", "=", "None", ")", "connect_group", ".", "add_option", "(", "'--xmpp_to'", ",", "help", "=", "'Optional setting for STARTTLS XMPP. XMPP_TO should be the hostname to be put in the \\'to\\' '", "'attribute of the XMPP stream. Default is the server\\'s hostname.'", ",", "dest", "=", "'xmpp_to'", ",", "default", "=", "None", ")", "# Server Name Indication", "connect_group", ".", "add_option", "(", "'--sni'", ",", "help", "=", "'Use Server Name Indication to specify the hostname to connect to. Will only affect TLS 1.0+ '", "'connections.'", ",", "dest", "=", "'sni'", ",", "default", "=", "None", ")", "self", ".", "_parser", ".", "add_option_group", "(", "connect_group", ")" ]
43.68254
25.373016
def optional_else(self, node, last): """ Create op_pos for optional else """ if node.orelse: min_first_max_last(node, node.orelse[-1]) if 'else' in self.operators: position = (node.orelse[0].first_line, node.orelse[0].first_col) _, efirst = self.operators['else'].find_previous(position) if efirst and efirst > last: elast, _ = self.operators[':'].find_previous(position) node.op_pos.append(NodeWithPosition(elast, efirst))
[ "def", "optional_else", "(", "self", ",", "node", ",", "last", ")", ":", "if", "node", ".", "orelse", ":", "min_first_max_last", "(", "node", ",", "node", ".", "orelse", "[", "-", "1", "]", ")", "if", "'else'", "in", "self", ".", "operators", ":", "position", "=", "(", "node", ".", "orelse", "[", "0", "]", ".", "first_line", ",", "node", ".", "orelse", "[", "0", "]", ".", "first_col", ")", "_", ",", "efirst", "=", "self", ".", "operators", "[", "'else'", "]", ".", "find_previous", "(", "position", ")", "if", "efirst", "and", "efirst", ">", "last", ":", "elast", ",", "_", "=", "self", ".", "operators", "[", "':'", "]", ".", "find_previous", "(", "position", ")", "node", ".", "op_pos", ".", "append", "(", "NodeWithPosition", "(", "elast", ",", "efirst", ")", ")" ]
54.2
17.7
def fun_en_complete_func(self, client, findstart_and_base, base=None): """Invokable function from vim and neovim to perform completion.""" if isinstance(findstart_and_base, list): # Invoked by neovim findstart = findstart_and_base[0] base = findstart_and_base[1] else: # Invoked by vim findstart = findstart_and_base return client.complete_func(findstart, base)
[ "def", "fun_en_complete_func", "(", "self", ",", "client", ",", "findstart_and_base", ",", "base", "=", "None", ")", ":", "if", "isinstance", "(", "findstart_and_base", ",", "list", ")", ":", "# Invoked by neovim", "findstart", "=", "findstart_and_base", "[", "0", "]", "base", "=", "findstart_and_base", "[", "1", "]", "else", ":", "# Invoked by vim", "findstart", "=", "findstart_and_base", "return", "client", ".", "complete_func", "(", "findstart", ",", "base", ")" ]
44.4
10.5
def _genprop(converter, *apipaths, **kwargs): """ This internal helper method returns a property (similar to the @property decorator). In additional to a simple Python property, this also adds a type validator (`converter`) and most importantly, specifies the path within a dictionary where the value should be stored. Any object using this property *must* have a dictionary called ``_json`` as a property :param converter: The converter to be used, e.g. `int` or `lambda x: x` for passthrough :param apipaths: Components of a path to store, e.g. `foo, bar, baz` for `foo['bar']['baz']` :return: A property object """ if not apipaths: raise TypeError('Must have at least one API path') def fget(self): d = self._json_ try: for x in apipaths: d = d[x] return d except KeyError: return None def fset(self, value): value = converter(value) d = self._json_ for x in apipaths[:-1]: d = d.setdefault(x, {}) d[apipaths[-1]] = value def fdel(self): d = self._json_ try: for x in apipaths[:-1]: d = d[x] del d[apipaths[-1]] except KeyError: pass doc = kwargs.pop( 'doc', 'Corresponds to the ``{0}`` field'.format('.'.join(apipaths))) return property(fget, fset, fdel, doc)
[ "def", "_genprop", "(", "converter", ",", "*", "apipaths", ",", "*", "*", "kwargs", ")", ":", "if", "not", "apipaths", ":", "raise", "TypeError", "(", "'Must have at least one API path'", ")", "def", "fget", "(", "self", ")", ":", "d", "=", "self", ".", "_json_", "try", ":", "for", "x", "in", "apipaths", ":", "d", "=", "d", "[", "x", "]", "return", "d", "except", "KeyError", ":", "return", "None", "def", "fset", "(", "self", ",", "value", ")", ":", "value", "=", "converter", "(", "value", ")", "d", "=", "self", ".", "_json_", "for", "x", "in", "apipaths", "[", ":", "-", "1", "]", ":", "d", "=", "d", ".", "setdefault", "(", "x", ",", "{", "}", ")", "d", "[", "apipaths", "[", "-", "1", "]", "]", "=", "value", "def", "fdel", "(", "self", ")", ":", "d", "=", "self", ".", "_json_", "try", ":", "for", "x", "in", "apipaths", "[", ":", "-", "1", "]", ":", "d", "=", "d", "[", "x", "]", "del", "d", "[", "apipaths", "[", "-", "1", "]", "]", "except", "KeyError", ":", "pass", "doc", "=", "kwargs", ".", "pop", "(", "'doc'", ",", "'Corresponds to the ``{0}`` field'", ".", "format", "(", "'.'", ".", "join", "(", "apipaths", ")", ")", ")", "return", "property", "(", "fget", ",", "fset", ",", "fdel", ",", "doc", ")" ]
29.244898
20.387755
def as_iso8601(self): """ example: 00:38:05.210Z """ if self.__time is None: return None return "%s:%s:%s0Z" % (self.__time[:2], self.__time[2:4], self.__time[4:])
[ "def", "as_iso8601", "(", "self", ")", ":", "if", "self", ".", "__time", "is", "None", ":", "return", "None", "return", "\"%s:%s:%s0Z\"", "%", "(", "self", ".", "__time", "[", ":", "2", "]", ",", "self", ".", "__time", "[", "2", ":", "4", "]", ",", "self", ".", "__time", "[", "4", ":", "]", ")" ]
26.125
17.125
def control_change(self, channel, control, value): """Send a control change message. See the MIDI specification for more information. """ if control < 0 or control > 128: return False if value < 0 or value > 128: return False self.cc_event(channel, control, value) self.notify_listeners(self.MSG_CC, {'channel': int(channel), 'control': int(control), 'value': int(value)}) return True
[ "def", "control_change", "(", "self", ",", "channel", ",", "control", ",", "value", ")", ":", "if", "control", "<", "0", "or", "control", ">", "128", ":", "return", "False", "if", "value", "<", "0", "or", "value", ">", "128", ":", "return", "False", "self", ".", "cc_event", "(", "channel", ",", "control", ",", "value", ")", "self", ".", "notify_listeners", "(", "self", ".", "MSG_CC", ",", "{", "'channel'", ":", "int", "(", "channel", ")", ",", "'control'", ":", "int", "(", "control", ")", ",", "'value'", ":", "int", "(", "value", ")", "}", ")", "return", "True" ]
36.384615
13.461538
def prepend_elements(self, elements): """ Prepends more elements to the contained internal elements. """ self._elements = list(elements) + self._elements self._on_element_change()
[ "def", "prepend_elements", "(", "self", ",", "elements", ")", ":", "self", ".", "_elements", "=", "list", "(", "elements", ")", "+", "self", ".", "_elements", "self", ".", "_on_element_change", "(", ")" ]
35.666667
8.666667
def DOM_copyTo(self, nodeId, targetNodeId, **kwargs): """ Function path: DOM.copyTo Domain: DOM Method name: copyTo WARNING: This function is marked 'Experimental'! Parameters: Required arguments: 'nodeId' (type: NodeId) -> Id of the node to copy. 'targetNodeId' (type: NodeId) -> Id of the element to drop the copy into. Optional arguments: 'insertBeforeNodeId' (type: NodeId) -> Drop the copy before this node (if absent, the copy becomes the last child of <code>targetNodeId</code>). Returns: 'nodeId' (type: NodeId) -> Id of the node clone. Description: Creates a deep copy of the specified node and places it into the target container before the given anchor. """ expected = ['insertBeforeNodeId'] passed_keys = list(kwargs.keys()) assert all([(key in expected) for key in passed_keys] ), "Allowed kwargs are ['insertBeforeNodeId']. Passed kwargs: %s" % passed_keys subdom_funcs = self.synchronous_command('DOM.copyTo', nodeId=nodeId, targetNodeId=targetNodeId, **kwargs) return subdom_funcs
[ "def", "DOM_copyTo", "(", "self", ",", "nodeId", ",", "targetNodeId", ",", "*", "*", "kwargs", ")", ":", "expected", "=", "[", "'insertBeforeNodeId'", "]", "passed_keys", "=", "list", "(", "kwargs", ".", "keys", "(", ")", ")", "assert", "all", "(", "[", "(", "key", "in", "expected", ")", "for", "key", "in", "passed_keys", "]", ")", ",", "\"Allowed kwargs are ['insertBeforeNodeId']. Passed kwargs: %s\"", "%", "passed_keys", "subdom_funcs", "=", "self", ".", "synchronous_command", "(", "'DOM.copyTo'", ",", "nodeId", "=", "nodeId", ",", "targetNodeId", "=", "targetNodeId", ",", "*", "*", "kwargs", ")", "return", "subdom_funcs" ]
40.5
25.423077
def daemonize(): """ Forks and daemonizes the current process. Does not automatically track the process id; to do this, use :class:`Exscript.util.pidutil`. """ sys.stdout.flush() sys.stderr.flush() # UNIX double-fork magic. We need to fork before any threads are # created. pid = os.fork() if pid > 0: # Exit first parent. sys.exit(0) # Decouple from parent environment. os.chdir('/') os.setsid() os.umask(0) # Now fork again. pid = os.fork() if pid > 0: # Exit second parent. sys.exit(0) _redirect_output(os.devnull)
[ "def", "daemonize", "(", ")", ":", "sys", ".", "stdout", ".", "flush", "(", ")", "sys", ".", "stderr", ".", "flush", "(", ")", "# UNIX double-fork magic. We need to fork before any threads are", "# created.", "pid", "=", "os", ".", "fork", "(", ")", "if", "pid", ">", "0", ":", "# Exit first parent.", "sys", ".", "exit", "(", "0", ")", "# Decouple from parent environment.", "os", ".", "chdir", "(", "'/'", ")", "os", ".", "setsid", "(", ")", "os", ".", "umask", "(", "0", ")", "# Now fork again.", "pid", "=", "os", ".", "fork", "(", ")", "if", "pid", ">", "0", ":", "# Exit second parent.", "sys", ".", "exit", "(", "0", ")", "_redirect_output", "(", "os", ".", "devnull", ")" ]
22.185185
21.962963
def __float(value): '''validate a float''' valid, _value = False, value try: _value = float(value) valid = True except ValueError: pass return (valid, _value, 'float')
[ "def", "__float", "(", "value", ")", ":", "valid", ",", "_value", "=", "False", ",", "value", "try", ":", "_value", "=", "float", "(", "value", ")", "valid", "=", "True", "except", "ValueError", ":", "pass", "return", "(", "valid", ",", "_value", ",", "'float'", ")" ]
22.555556
17.444444