text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def key_value(minion_id, pillar, # pylint: disable=W0613 pillar_key='redis_pillar'): ''' Looks for key in redis matching minion_id, returns a structure based on the data type of the redis key. String for string type, dict for hash type and lists for lists, sets and sorted se...
[ "def", "key_value", "(", "minion_id", ",", "pillar", ",", "# pylint: disable=W0613", "pillar_key", "=", "'redis_pillar'", ")", ":", "# Identify key type and process as needed based on that type", "key_type", "=", "__salt__", "[", "'redis.key_type'", "]", "(", "minion_id", ...
40.727273
0.000727
def check_address(cls, *, chat: typing.Union[str, int, None] = None, user: typing.Union[str, int, None] = None) -> (typing.Union[str, int], typing.Union[str, int]): """ In all storage's methods chat or user is always required. If one of them is not pro...
[ "def", "check_address", "(", "cls", ",", "*", ",", "chat", ":", "typing", ".", "Union", "[", "str", ",", "int", ",", "None", "]", "=", "None", ",", "user", ":", "typing", ".", "Union", "[", "str", ",", "int", ",", "None", "]", "=", "None", ")",...
38
0.008557
def breakRankTies(self, oldsym, newsym): """break Ties to form a new list with the same integer ordering from high to low Example old = [ 4, 2, 4, 7, 8] (Two ties, 4 and 4) new = [60, 2 61,90,99] res = [ 4, 0, 3, 1, 2] * * This tie is broken i...
[ "def", "breakRankTies", "(", "self", ",", "oldsym", ",", "newsym", ")", ":", "stableSort", "=", "map", "(", "None", ",", "oldsym", ",", "newsym", ",", "range", "(", "len", "(", "oldsym", ")", ")", ")", "stableSort", ".", "sort", "(", ")", "lastOld", ...
33.615385
0.002225
def _copy(self): """Create and return a new copy of the Bits (always in memory).""" s_copy = self.__class__() s_copy._setbytes_unsafe(self._datastore.getbyteslice(0, self._datastore.bytelength), self.len, self._offset) return s_copy
[ "def", "_copy", "(", "self", ")", ":", "s_copy", "=", "self", ".", "__class__", "(", ")", "s_copy", ".", "_setbytes_unsafe", "(", "self", ".", "_datastore", ".", "getbyteslice", "(", "0", ",", "self", ".", "_datastore", ".", "bytelength", ")", ",", "se...
48.5
0.010135
def as_dict(self): """ Serializes the object necessary data in a dictionary. :returns: Serialized data in a dictionary. :rtype: dict """ result_dict = super(Benchmark, self).as_dict() statuses = list() titles = list() descriptions = list() ...
[ "def", "as_dict", "(", "self", ")", ":", "result_dict", "=", "super", "(", "Benchmark", ",", "self", ")", ".", "as_dict", "(", ")", "statuses", "=", "list", "(", ")", "titles", "=", "list", "(", ")", "descriptions", "=", "list", "(", ")", "front_matt...
34.316667
0.000944
def build_base_image_cmd(self, force): """ Build the glusterbase image """ check_permissions() basetag = self.conf.basetag basedir = self.conf.basedir verbose = self.conf.verbose if self.image_exists(tag=basetag): if not force: ...
[ "def", "build_base_image_cmd", "(", "self", ",", "force", ")", ":", "check_permissions", "(", ")", "basetag", "=", "self", ".", "conf", ".", "basetag", "basedir", "=", "self", ".", "conf", ".", "basedir", "verbose", "=", "self", ".", "conf", ".", "verbos...
33.185185
0.002169
def eval_unx(self, exp): "unary expressions" inner=self.eval(exp.val) if exp.op.op=='+': return inner elif exp.op.op=='-': return -inner elif exp.op.op=='not': return threevl.ThreeVL.nein(inner) else: raise NotImplementedError('unk_op',exp.op)
[ "def", "eval_unx", "(", "self", ",", "exp", ")", ":", "inner", "=", "self", ".", "eval", "(", "exp", ".", "val", ")", "if", "exp", ".", "op", ".", "op", "==", "'+'", ":", "return", "inner", "elif", "exp", ".", "op", ".", "op", "==", "'-'", ":...
37.285714
0.037453
def record_trace(self, selectors=None): """Record a trace of readings produced by this simulator. This causes the property `self.trace` to be populated with a SimulationTrace object that contains all of the readings that are produced during the course of the simulation. Only readings ...
[ "def", "record_trace", "(", "self", ",", "selectors", "=", "None", ")", ":", "if", "selectors", "is", "None", ":", "selectors", "=", "[", "x", ".", "selector", "for", "x", "in", "self", ".", "sensor_graph", ".", "streamers", "]", "self", ".", "trace", ...
46.542857
0.001203
def node_number(self, *, count_pnode=True) -> int: """Return the number of node""" return (sum(1 for n in self.nodes()) + (sum(1 for n in self.powernodes()) if count_pnode else 0))
[ "def", "node_number", "(", "self", ",", "*", ",", "count_pnode", "=", "True", ")", "->", "int", ":", "return", "(", "sum", "(", "1", "for", "n", "in", "self", ".", "nodes", "(", ")", ")", "+", "(", "sum", "(", "1", "for", "n", "in", "self", "...
52.25
0.009434
def _inet6_ntop(addr): """Convert an IPv6 address from binary form into text representation, used when socket.inet_pton is not available. """ # IPv6 addresses have 128bits (16 bytes) if len(addr) != 16: raise ValueError("invalid length of packed IP address string") # Decode to hex represen...
[ "def", "_inet6_ntop", "(", "addr", ")", ":", "# IPv6 addresses have 128bits (16 bytes)", "if", "len", "(", "addr", ")", "!=", "16", ":", "raise", "ValueError", "(", "\"invalid length of packed IP address string\"", ")", "# Decode to hex representation", "address", "=", ...
41.166667
0.000989
def genericCameraMatrix(shape, angularField=60): ''' Return a generic camera matrix [[fx, 0, cx], [ 0, fy, cy], [ 0, 0, 1]] for a given image shape ''' # http://nghiaho.com/?page_id=576 # assume that the optical centre is in the middle: cy = int(shape[0] / 2) cx ...
[ "def", "genericCameraMatrix", "(", "shape", ",", "angularField", "=", "60", ")", ":", "# http://nghiaho.com/?page_id=576\r", "# assume that the optical centre is in the middle:\r", "cy", "=", "int", "(", "shape", "[", "0", "]", "/", "2", ")", "cx", "=", "int", "("...
33
0.001339
def _choi_to_kraus(data, input_dim, output_dim, atol=ATOL_DEFAULT): """Transform Choi representation to Kraus representation.""" # Check if hermitian matrix if is_hermitian_matrix(data, atol=atol): # Get eigen-decomposition of Choi-matrix w, v = la.eigh(data) # Check eigenvaleus are ...
[ "def", "_choi_to_kraus", "(", "data", ",", "input_dim", ",", "output_dim", ",", "atol", "=", "ATOL_DEFAULT", ")", ":", "# Check if hermitian matrix", "if", "is_hermitian_matrix", "(", "data", ",", "atol", "=", "atol", ")", ":", "# Get eigen-decomposition of Choi-mat...
44.1
0.00074
def _contiguous_groups( length: int, comparator: Callable[[int, int], bool] ) -> List[Tuple[int, int]]: """Splits range(length) into approximate equivalence classes. Args: length: The length of the range to split. comparator: Determines if two indices have approximately equal it...
[ "def", "_contiguous_groups", "(", "length", ":", "int", ",", "comparator", ":", "Callable", "[", "[", "int", ",", "int", "]", ",", "bool", "]", ")", "->", "List", "[", "Tuple", "[", "int", ",", "int", "]", "]", ":", "result", "=", "[", "]", "star...
30.304348
0.001391
def centers(self): """The centers for the KMeans model.""" o = self._model_json["output"] cvals = o["centers"].cell_values centers = [list(cval[1:]) for cval in cvals] return centers
[ "def", "centers", "(", "self", ")", ":", "o", "=", "self", ".", "_model_json", "[", "\"output\"", "]", "cvals", "=", "o", "[", "\"centers\"", "]", ".", "cell_values", "centers", "=", "[", "list", "(", "cval", "[", "1", ":", "]", ")", "for", "cval",...
36.166667
0.009009
def rotate(matrix, angle): r"""Rotate This method rotates an input matrix about the input angle. Parameters ---------- matrix : np.ndarray Input matrix array angle : float Rotation angle in radians Returns ------- np.ndarray rotated matrix Raises ------ ...
[ "def", "rotate", "(", "matrix", ",", "angle", ")", ":", "shape", "=", "np", ".", "array", "(", "matrix", ".", "shape", ")", "if", "shape", "[", "0", "]", "!=", "shape", "[", "1", "]", ":", "raise", "ValueError", "(", "'Input matrix must be square.'", ...
21.586957
0.000963
def confusion_matrix(self, data): """ Returns a confusion matrix based of H2O's default prediction threshold for a dataset. :param data: metric for which the confusion matrix will be calculated. """ return {model.model_id: model.confusion_matrix(data) for model in self.models}
[ "def", "confusion_matrix", "(", "self", ",", "data", ")", ":", "return", "{", "model", ".", "model_id", ":", "model", ".", "confusion_matrix", "(", "data", ")", "for", "model", "in", "self", ".", "models", "}" ]
44.571429
0.012579
def curl_remote_name(cls, file_url): """Download file_url, and save as a file name of the URL. It behaves like "curl -O or --remote-name". It raises HTTPError if the file_url not found. """ tar_gz_file_name = file_url.split('/')[-1] if sys.version_info >= (3, 2): ...
[ "def", "curl_remote_name", "(", "cls", ",", "file_url", ")", ":", "tar_gz_file_name", "=", "file_url", ".", "split", "(", "'/'", ")", "[", "-", "1", "]", "if", "sys", ".", "version_info", ">=", "(", "3", ",", "2", ")", ":", "from", "urllib", ".", "...
34.566667
0.001876
def upgrade(**kwargs): ''' Upgrade all software. Currently not implemented Kwargs: saltenv (str): The salt environment to use. Default ``base``. refresh (bool): Refresh package metadata. Default ``True``. .. note:: This feature is not yet implemented for Windows. Returns: ...
[ "def", "upgrade", "(", "*", "*", "kwargs", ")", ":", "log", ".", "warning", "(", "'pkg.upgrade not implemented on Windows yet'", ")", "refresh", "=", "salt", ".", "utils", ".", "data", ".", "is_true", "(", "kwargs", ".", "get", "(", "'refresh'", ",", "True...
28.827586
0.002315
def create_bayesian_tear_sheet(returns, benchmark_rets=None, live_start_date=None, samples=2000, return_fig=False, stoch_vol=False, progressbar=True): """ Generate a number of Bayesian distributions and a Bayesian c...
[ "def", "create_bayesian_tear_sheet", "(", "returns", ",", "benchmark_rets", "=", "None", ",", "live_start_date", "=", "None", ",", "samples", "=", "2000", ",", "return_fig", "=", "False", ",", "stoch_vol", "=", "False", ",", "progressbar", "=", "True", ")", ...
37.559783
0.000141
def _extract_response_xml(self, domain, response): """Extract XML content of an HTTP response into dictionary format. Args: response: HTML Response objects Returns: A dictionary: {alexa-ranking key : alexa-ranking value}. """ attributes = {} alexa...
[ "def", "_extract_response_xml", "(", "self", ",", "domain", ",", "response", ")", ":", "attributes", "=", "{", "}", "alexa_keys", "=", "{", "'POPULARITY'", ":", "'TEXT'", ",", "'REACH'", ":", "'RANK'", ",", "'RANK'", ":", "'DELTA'", "}", "try", ":", "xml...
42
0.002116
def get_pip_requirement_set(self, arguments, use_remote_index, use_wheels=False): """ Get the unpacked requirement(s) specified by the caller by running pip. :param arguments: The command line arguments to ``pip install ...`` (a list of strings). :param use_rem...
[ "def", "get_pip_requirement_set", "(", "self", ",", "arguments", ",", "use_remote_index", ",", "use_wheels", "=", "False", ")", ":", "# Compose the pip command line arguments. This is where a lot of the", "# core logic of pip-accel is hidden and it uses some esoteric features", "# of...
61.537634
0.001376
def get_object(self, request, object_id, from_field=None): """ our implementation of get_object allows for cloning when updating an object, not cloning when the button 'save but not clone' is pushed and at no other time will clone be called """ # from_field breaks in 1.7....
[ "def", "get_object", "(", "self", ",", "request", ",", "object_id", ",", "from_field", "=", "None", ")", ":", "# from_field breaks in 1.7.8", "obj", "=", "super", "(", "VersionedAdmin", ",", "self", ")", ".", "get_object", "(", "request", ",", "object_id", "...
42.7
0.002291
def create_tables(self): """ create tables in database (if they don't already exist) """ cdir = os.path.dirname( os.path.realpath(__file__) ) # table schemas ------------------------------------- schema = os.path.join(cdir,"data","partsmaster.sql") if sel...
[ "def", "create_tables", "(", "self", ")", ":", "cdir", "=", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "realpath", "(", "__file__", ")", ")", "# table schemas -------------------------------------", "schema", "=", "os", ".", "path", ".",...
30.96875
0.027397
def initialize_shade(self, shade_name, shade_color, alpha): """This method will create semi-transparent surfaces with a specified color. The surface can be toggled on and off. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Inputs: Shade_name - String...
[ "def", "initialize_shade", "(", "self", ",", "shade_name", ",", "shade_color", ",", "alpha", ")", ":", "# Create the pygame surface", "self", ".", "shades", "[", "shade_name", "]", "=", "[", "0", ",", "pygame", ".", "Surface", "(", "self", ".", "image", "....
42.84375
0.001427
def _fromJSON(cls, jsonobject): """Generates a new instance of :class:`maspy.core.Ci` from a decoded JSON object (as generated by :func:`maspy.core.Ci._reprJSON()`). :param jsonobject: decoded JSON object :returns: a new instance of :class:`Ci` """ newInstance = cls(jso...
[ "def", "_fromJSON", "(", "cls", ",", "jsonobject", ")", ":", "newInstance", "=", "cls", "(", "jsonobject", "[", "0", "]", ",", "jsonobject", "[", "1", "]", ")", "attribDict", "=", "{", "}", "attribDict", "[", "'dataProcessingRef'", "]", "=", "jsonobject"...
45.083333
0.00181
def glob_compile(pat): """Translate a shell glob PATTERN to a regular expression. This is almost entirely based on `fnmatch.translate` source-code from the python 3.5 standard-library. """ i, n = 0, len(pat) res = '' while i < n: c = pat[i] i = i + 1 if c == '/' and...
[ "def", "glob_compile", "(", "pat", ")", ":", "i", ",", "n", "=", "0", ",", "len", "(", "pat", ")", "res", "=", "''", "while", "i", "<", "n", ":", "c", "=", "pat", "[", "i", "]", "i", "=", "i", "+", "1", "if", "c", "==", "'/'", "and", "l...
33.291667
0.001216
def parse_conll(self, texts: List[str], retry_count: int = 0) -> List[str]: ''' Processes the texts using TweeboParse and returns them in CoNLL format. :param texts: The List of Strings to be processed by TweeboParse. :param retry_count: The number of times it has retried for. Default ...
[ "def", "parse_conll", "(", "self", ",", "texts", ":", "List", "[", "str", "]", ",", "retry_count", ":", "int", "=", "0", ")", "->", "List", "[", "str", "]", ":", "post_data", "=", "{", "'texts'", ":", "texts", ",", "'output_type'", ":", "'conll'", ...
48.923077
0.001028
def copy_path_to_clipboard(self): """ Copies the file path to the clipboard """ path = self.get_current_path() QtWidgets.QApplication.clipboard().setText(path) debug('path copied: %s' % path)
[ "def", "copy_path_to_clipboard", "(", "self", ")", ":", "path", "=", "self", ".", "get_current_path", "(", ")", "QtWidgets", ".", "QApplication", ".", "clipboard", "(", ")", ".", "setText", "(", "path", ")", "debug", "(", "'path copied: %s'", "%", "path", ...
33.285714
0.008368
def create_new_page (self, section_id, new_page_style=0): """ NewPageStyle 0 - Create a Page that has Default Page Style 1 - Create a blank page with no title 2 - Createa blank page that has no title """ try: self.process.CreateNewPage(section_...
[ "def", "create_new_page", "(", "self", ",", "section_id", ",", "new_page_style", "=", "0", ")", ":", "try", ":", "self", ".", "process", ".", "CreateNewPage", "(", "section_id", ",", "\"\"", ",", "new_page_style", ")", "except", "Exception", "as", "e", ":"...
36
0.009029
def p_statement_expr(self, t): '''statement : node_expression PLUS node_expression | node_expression MINUS node_expression''' if len(t)<3 : self.accu.add(Term('input', [t[1]])) print('input', t[1]) else : #print(t[1], t[2], t[3] self.accu.add(Term('edge', ...
[ "def", "p_statement_expr", "(", "self", ",", "t", ")", ":", "if", "len", "(", "t", ")", "<", "3", ":", "self", ".", "accu", ".", "add", "(", "Term", "(", "'input'", ",", "[", "t", "[", "1", "]", "]", ")", ")", "print", "(", "'input'", ",", ...
44.2
0.031042
def foldl1(f: Callable[[T, T], T], xs: Iterable[T]) -> T: """ Returns the accumulated result of a binary function applied to elements of an iterable. .. math:: foldl1(f, [x_0, x_1, x_2, x_3]) = f(f(f(f(x_0, x_1), x_2), x_3) Examples -------- >>> from delphi.utils.fp import foldl1 ...
[ "def", "foldl1", "(", "f", ":", "Callable", "[", "[", "T", ",", "T", "]", ",", "T", "]", ",", "xs", ":", "Iterable", "[", "T", "]", ")", "->", "T", ":", "return", "reduce", "(", "f", ",", "xs", ")" ]
24.125
0.002494
def _build_block_context(template, context): """Populate the block context with BlockNodes from parent templates.""" # Ensure there's a BlockContext before rendering. This allows blocks in # ExtendsNodes to be found by sub-templates (allowing {{ block.super }} and # overriding sub-blocks to work). ...
[ "def", "_build_block_context", "(", "template", ",", "context", ")", ":", "# Ensure there's a BlockContext before rendering. This allows blocks in", "# ExtendsNodes to be found by sub-templates (allowing {{ block.super }} and", "# overriding sub-blocks to work).", "if", "BLOCK_CONTEXT_KEY", ...
45.538462
0.001654
def workflow_move_stage(object_id, input_params={}, always_retry=True, **kwargs): """ Invokes the /workflow-xxxx/moveStage API method. For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Workflows-and-Analyses#API-method%3A-%2Fworkflow-xxxx%2FmoveStage """ return DXHTTPRequest('/...
[ "def", "workflow_move_stage", "(", "object_id", ",", "input_params", "=", "{", "}", ",", "always_retry", "=", "True", ",", "*", "*", "kwargs", ")", ":", "return", "DXHTTPRequest", "(", "'/%s/moveStage'", "%", "object_id", ",", "input_params", ",", "always_retr...
55.857143
0.010076
def run(self, max_pressure=None): r""" Perform the algorithm Parameters ---------- max_pressure : float The maximum pressure applied to the invading cluster. Any pores and throats with entry pressure above this value will not be invaded. """ ...
[ "def", "run", "(", "self", ",", "max_pressure", "=", "None", ")", ":", "if", "'throat.entry_pressure'", "not", "in", "self", ".", "keys", "(", ")", ":", "logger", ".", "error", "(", "\"Setup method must be run first\"", ")", "if", "max_pressure", "is", "None...
42.472727
0.001255
def get_layer_nr(inp, depth): r"""Get number of layer in which inp resides. Note: If zinp is on a layer interface, the layer above the interface is chosen. This check-function is called from one of the modelling routines in :mod:`model`. Consult these modelling routines for a detailed description...
[ "def", "get_layer_nr", "(", "inp", ",", "depth", ")", ":", "zinp", "=", "inp", "[", "2", "]", "# depth = [-infty : last interface]; create additional depth-array", "# pdepth = [fist interface : +infty]", "pdepth", "=", "np", ".", "concatenate", "(", "(", "depth", "["...
26.119048
0.000879
def decompress(compressed_data): """Decompress data that has been compressed by the filepack algorithm. :param compressed_data: an array of compressed data bytes to decompress :rtype: an array of decompressed bytes""" raw_data = [] index = 0 while index < len(compressed_data): curren...
[ "def", "decompress", "(", "compressed_data", ")", ":", "raw_data", "=", "[", "]", "index", "=", "0", "while", "index", "<", "len", "(", "compressed_data", ")", ":", "current", "=", "compressed_data", "[", "index", "]", "index", "+=", "1", "if", "current"...
31.117647
0.000611
def render_as_json(func): """ Decorator to render as JSON :param func: :return: """ if inspect.isclass(func): setattr(func, "_renderer", json_renderer) return func else: @functools.wraps(func) def decorated_view(*args, **kwargs): data = func(*args,...
[ "def", "render_as_json", "(", "func", ")", ":", "if", "inspect", ".", "isclass", "(", "func", ")", ":", "setattr", "(", "func", ",", "\"_renderer\"", ",", "json_renderer", ")", "return", "func", "else", ":", "@", "functools", ".", "wraps", "(", "func", ...
26.4
0.002439
def byLexer( lexer ): """ Looks up the language plugin by the lexer class of the inputed lexer. :param lexer | <QsciLexer> :return <XLanguage> || None """ XLanguage.load() lexerType = type(lexer) for lang in XLanguage._p...
[ "def", "byLexer", "(", "lexer", ")", ":", "XLanguage", ".", "load", "(", ")", "lexerType", "=", "type", "(", "lexer", ")", "for", "lang", "in", "XLanguage", ".", "_plugins", ".", "values", "(", ")", ":", "if", "(", "lang", ".", "lexerType", "(", ")...
28
0.020737
def setPotential(self, columnIndex, potential): """ Sets the potential mapping for a given column. ``potential`` size must match the number of inputs, and must be greater than ``stimulusThreshold``. :param columnIndex: (int) column index to set potential for. :param potential: (list) value to ...
[ "def", "setPotential", "(", "self", ",", "columnIndex", ",", "potential", ")", ":", "assert", "(", "columnIndex", "<", "self", ".", "_numColumns", ")", "potentialSparse", "=", "numpy", ".", "where", "(", "potential", ">", "0", ")", "[", "0", "]", "if", ...
39.705882
0.01013
def plot_inputseries( self, names: Optional[Iterable[str]] = None, average: bool = False, **kwargs: Any) \ -> None: """Plot (the selected) |InputSequence| |IOSequence.series| values. We demonstrate the functionalities of method |Element.plot_inputseries| base...
[ "def", "plot_inputseries", "(", "self", ",", "names", ":", "Optional", "[", "Iterable", "[", "str", "]", "]", "=", "None", ",", "average", ":", "bool", "=", "False", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "None", ":", "self", ".", "__plot"...
40.118421
0.00064
def clear_java_home(): """Clear JAVA_HOME environment or reset to BCBIO_JAVA_HOME. Avoids accidental java injection but respects custom BCBIO_JAVA_HOME command. """ if os.environ.get("BCBIO_JAVA_HOME"): test_cmd = os.path.join(os.environ["BCBIO_JAVA_HOME"], "bin", "java") if os.path...
[ "def", "clear_java_home", "(", ")", ":", "if", "os", ".", "environ", ".", "get", "(", "\"BCBIO_JAVA_HOME\"", ")", ":", "test_cmd", "=", "os", ".", "path", ".", "join", "(", "os", ".", "environ", "[", "\"BCBIO_JAVA_HOME\"", "]", ",", "\"bin\"", ",", "\"...
39.090909
0.002273
def append_logs_to_result_object(result_obj, result): """ Append log files to cloud result object from Result. :param result_obj: Target result object :param result: Result :return: Nothing, modifies result_obj in place. """ logs = result.has_logs() result_obj["exec"]["logs"] = [] i...
[ "def", "append_logs_to_result_object", "(", "result_obj", ",", "result", ")", ":", "logs", "=", "result", ".", "has_logs", "(", ")", "result_obj", "[", "\"exec\"", "]", "[", "\"logs\"", "]", "=", "[", "]", "if", "logs", "and", "result", ".", "logfiles", ...
33.1
0.000978
def main(): """ Main entry point, expects doctopt arg dict as argd. """ global DEBUG argd = docopt(USAGESTR, version=VERSIONSTR, script=SCRIPT) DEBUG = argd['--debug'] width = parse_int(argd['--width'] or DEFAULT_WIDTH) or 1 indent = parse_int(argd['--indent'] or (argd['--INDENT'] or 0)) pr...
[ "def", "main", "(", ")", ":", "global", "DEBUG", "argd", "=", "docopt", "(", "USAGESTR", ",", "version", "=", "VERSIONSTR", ",", "script", "=", "SCRIPT", ")", "DEBUG", "=", "argd", "[", "'--debug'", "]", "width", "=", "parse_int", "(", "argd", "[", "...
33.111111
0.000543
def show(self, commits=None, encoding='utf-8'): """Show the data of a set of commits. The method returns the output of Git show command for a set of commits using the following options: git show --raw --numstat --pretty=fuller --decorate=full --parents -M -C -c [<co...
[ "def", "show", "(", "self", ",", "commits", "=", "None", ",", "encoding", "=", "'utf-8'", ")", ":", "if", "self", ".", "is_empty", "(", ")", ":", "logger", ".", "warning", "(", "\"Git %s repository is empty; unable to run show\"", ",", "self", ".", "uri", ...
37.051282
0.001349
def to_python(self,value): """ Validates that the value is in self.choices and can be coerced to the right type. """ if value==self.emptyValue or value in EMPTY_VALUES: return self.emptyValue try: value=self.coerce(value) except(ValueErro...
[ "def", "to_python", "(", "self", ",", "value", ")", ":", "if", "value", "==", "self", ".", "emptyValue", "or", "value", "in", "EMPTY_VALUES", ":", "return", "self", ".", "emptyValue", "try", ":", "value", "=", "self", ".", "coerce", "(", "value", ")", ...
34.692308
0.023758
def parse(svg, cached=False, _copy=True): """ Returns cached copies unless otherwise specified. """ if not cached: dom = parser.parseString(svg) paths = parse_node(dom, []) else: id = _cache.id(svg) if not _cache.has_key(id): dom = parser.parseString...
[ "def", "parse", "(", "svg", ",", "cached", "=", "False", ",", "_copy", "=", "True", ")", ":", "if", "not", "cached", ":", "dom", "=", "parser", ".", "parseString", "(", "svg", ")", "paths", "=", "parse_node", "(", "dom", ",", "[", "]", ")", "else...
26.1875
0.011521
def flat_list_to_polymer(atom_list, atom_group_s=4): """Takes a flat list of atomic coordinates and converts it to a `Polymer`. Parameters ---------- atom_list : [Atom] Flat list of coordinates. atom_group_s : int, optional Size of atom groups. Returns ------- polymer :...
[ "def", "flat_list_to_polymer", "(", "atom_list", ",", "atom_group_s", "=", "4", ")", ":", "atom_labels", "=", "[", "'N'", ",", "'CA'", ",", "'C'", ",", "'O'", ",", "'CB'", "]", "atom_elements", "=", "[", "'N'", ",", "'C'", ",", "'C'", ",", "'O'", ","...
32.891892
0.001596
def clean_zipfile(self): '''remove existing zipfile''' if os.path.isfile(self.zip_file): os.remove(self.zip_file)
[ "def", "clean_zipfile", "(", "self", ")", ":", "if", "os", ".", "path", ".", "isfile", "(", "self", ".", "zip_file", ")", ":", "os", ".", "remove", "(", "self", ".", "zip_file", ")" ]
34.5
0.014184
def get_default_ENV(env): """ A fiddlin' little function that has an 'import SCons.Environment' which can't be moved to the top level without creating an import loop. Since this import creates a local variable named 'SCons', it blocks access to the global variable, so we move it here to prevent com...
[ "def", "get_default_ENV", "(", "env", ")", ":", "global", "default_ENV", "try", ":", "return", "env", "[", "'ENV'", "]", "except", "KeyError", ":", "if", "not", "default_ENV", ":", "import", "SCons", ".", "Environment", "# This is a hideously expensive way to get ...
45.380952
0.001028
def process_axes(self, obj, columns=None): """ process axes filters """ # make a copy to avoid side effects if columns is not None: columns = list(columns) # make sure to include levels if we have them if columns is not None and self.is_multi_index: for ...
[ "def", "process_axes", "(", "self", ",", "obj", ",", "columns", "=", "None", ")", ":", "# make a copy to avoid side effects", "if", "columns", "is", "not", "None", ":", "columns", "=", "list", "(", "columns", ")", "# make sure to include levels if we have them", "...
41.474576
0.000798
def encode_dict(data, encoding=None, errors='strict', keep=False, preserve_dict_class=False, preserve_tuples=False): ''' Encode all string values to bytes ''' rv = data.__class__() if preserve_dict_class else {} for key, value in six.iteritems(data): if isinstance(key, tuple)...
[ "def", "encode_dict", "(", "data", ",", "encoding", "=", "None", ",", "errors", "=", "'strict'", ",", "keep", "=", "False", ",", "preserve_dict_class", "=", "False", ",", "preserve_tuples", "=", "False", ")", ":", "rv", "=", "data", ".", "__class__", "("...
43.367347
0.001841
def getOffsetFromRva(self, rva): """ Converts an offset to an RVA. @type rva: int @param rva: The RVA to be converted. @rtype: int @return: An integer value representing an offset in the PE file. """ offset = -1 s = self.getSectio...
[ "def", "getOffsetFromRva", "(", "self", ",", "rva", ")", ":", "offset", "=", "-", "1", "s", "=", "self", ".", "getSectionByRva", "(", "rva", ")", "if", "s", "!=", "offset", ":", "offset", "=", "(", "rva", "-", "self", ".", "sectionHeaders", "[", "s...
28.263158
0.012613
def solve(self): """ Run the solver and assign the solution's :class:`CoordSystem` instances as the corresponding part's world coordinates. """ if self.world_coords is None: log.warning("solving for Assembly without world coordinates set: %r", self) for (comp...
[ "def", "solve", "(", "self", ")", ":", "if", "self", ".", "world_coords", "is", "None", ":", "log", ".", "warning", "(", "\"solving for Assembly without world coordinates set: %r\"", ",", "self", ")", "for", "(", "component", ",", "world_coords", ")", "in", "s...
42.9
0.009132
def url_for(endpoint, default="senaite.jsonapi.get", **values): """Looks up the API URL for the given endpoint :param endpoint: The name of the registered route (aka endpoint) :type endpoint: string :returns: External URL for this endpoint :rtype: string/None """ try: return router...
[ "def", "url_for", "(", "endpoint", ",", "default", "=", "\"senaite.jsonapi.get\"", ",", "*", "*", "values", ")", ":", "try", ":", "return", "router", ".", "url_for", "(", "endpoint", ",", "force_external", "=", "True", ",", "values", "=", "values", ")", ...
39.789474
0.001292
def is_program(self): """ A property which can be used to check if StatusObject uses program features or not. """ from automate.callables import Empty return not (isinstance(self.on_activate, Empty) and isinstance(self.on_deactivate, Empty) ...
[ "def", "is_program", "(", "self", ")", ":", "from", "automate", ".", "callables", "import", "Empty", "return", "not", "(", "isinstance", "(", "self", ".", "on_activate", ",", "Empty", ")", "and", "isinstance", "(", "self", ".", "on_deactivate", ",", "Empty...
44.5
0.008264
def __get_host(node, vm_): ''' Return public IP, private IP, or hostname for the libcloud 'node' object ''' if __get_ssh_interface(vm_) == 'private_ips' or vm_['external_ip'] is None: ip_address = node.private_ips[0] log.info('Salt node data. Private_ip: %s', ip_address) else: ...
[ "def", "__get_host", "(", "node", ",", "vm_", ")", ":", "if", "__get_ssh_interface", "(", "vm_", ")", "==", "'private_ips'", "or", "vm_", "[", "'external_ip'", "]", "is", "None", ":", "ip_address", "=", "node", ".", "private_ips", "[", "0", "]", "log", ...
31.266667
0.00207
def register_persistent_rest_pair(self, persistent_model_class, rest_model_class): """ :param persistent_model_class: :param rest_model_class: """ self.register_adapter(ModelAdapter( rest_model_class=rest_model_class, persistent_model_class=persistent_mode...
[ "def", "register_persistent_rest_pair", "(", "self", ",", "persistent_model_class", ",", "rest_model_class", ")", ":", "self", ".", "register_adapter", "(", "ModelAdapter", "(", "rest_model_class", "=", "rest_model_class", ",", "persistent_model_class", "=", "persistent_m...
36.666667
0.008876
def get_between_times(self, t1, t2, target=None): """ Query for OPUS data between times t1 and t2. Parameters ---------- t1, t2 : datetime.datetime, strings Start and end time for the query. If type is datetime, will be converted to isoformat string. If t...
[ "def", "get_between_times", "(", "self", ",", "t1", ",", "t2", ",", "target", "=", "None", ")", ":", "try", ":", "# checking if times have isoformat() method (datetimes have)", "t1", "=", "t1", ".", "isoformat", "(", ")", "t2", "=", "t2", ".", "isoformat", "...
37.677419
0.001669
def commit(): """ Commit changes and release the write lock """ session_token = request.headers['session_token'] repository = request.headers['repository'] #=== current_user = have_authenticated_user(request.environ['REMOTE_ADDR'], repository, session_token) if current_user is False: return...
[ "def", "commit", "(", ")", ":", "session_token", "=", "request", ".", "headers", "[", "'session_token'", "]", "repository", "=", "request", ".", "headers", "[", "'repository'", "]", "#===", "current_user", "=", "have_authenticated_user", "(", "request", ".", "...
35.451613
0.011515
def add_geo(self, geo_location): """ Saves a <geo-location> Element, to be incoporated into the Open511 geometry field. """ if not geo_location.xpath('latitude') and geo_location.xpath('longitude'): raise Exception("Invalid geo-location %s" % etree.tostring(geo_locati...
[ "def", "add_geo", "(", "self", ",", "geo_location", ")", ":", "if", "not", "geo_location", ".", "xpath", "(", "'latitude'", ")", "and", "geo_location", ".", "xpath", "(", "'longitude'", ")", ":", "raise", "Exception", "(", "\"Invalid geo-location %s\"", "%", ...
48.733333
0.008054
def flexifunction_directory_ack_encode(self, target_system, target_component, directory_type, start_index, count, result): ''' Acknowldge sucess or failure of a flexifunction command target_system : System ID (uint8_t) target_component ...
[ "def", "flexifunction_directory_ack_encode", "(", "self", ",", "target_system", ",", "target_component", ",", "directory_type", ",", "start_index", ",", "count", ",", "result", ")", ":", "return", "MAVLink_flexifunction_directory_ack_message", "(", "target_system", ",", ...
65.384615
0.008121
def check_error(res, error_enum): """Raise if the result has an error, otherwise return the result.""" if res.HasField("error"): enum_name = error_enum.DESCRIPTOR.full_name error_name = error_enum.Name(res.error) details = getattr(res, "error_details", "<none>") raise RequestError("%s.%s: '%s'" % (e...
[ "def", "check_error", "(", "res", ",", "error_enum", ")", ":", "if", "res", ".", "HasField", "(", "\"error\"", ")", ":", "enum_name", "=", "error_enum", ".", "DESCRIPTOR", ".", "full_name", "error_name", "=", "error_enum", ".", "Name", "(", "res", ".", "...
45.25
0.01084
def reindex_similar(self, other, n_sphere=4): """Reindex ``other`` to be similarly indexed as ``self``. Returns a reindexed copy of ``other`` that minimizes the distance for each atom to itself in the same chemical environemt from ``self`` to ``other``. Read more about the defin...
[ "def", "reindex_similar", "(", "self", ",", "other", ",", "n_sphere", "=", "4", ")", ":", "def", "make_subset_similar", "(", "m1", ",", "subset1", ",", "m2", ",", "subset2", ",", "index_dct", ")", ":", "\"\"\"Changes index_dct INPLACE\"\"\"", "coords", "=", ...
43
0.00065
def query(cls, *criteria, **filters): """Wrap sqlalchemy query methods. A wrapper for the filter and filter_by functions of sqlalchemy. Define a dict with which columns should be filtered by which values. .. codeblock:: python WorkflowObject.query(id=123) Workf...
[ "def", "query", "(", "cls", ",", "*", "criteria", ",", "*", "*", "filters", ")", ":", "query", "=", "cls", ".", "dbmodel", ".", "query", ".", "filter", "(", "*", "criteria", ")", ".", "filter_by", "(", "*", "*", "filters", ")", "return", "[", "cl...
32.730769
0.002283
def parse_abstract(xml_dict): """ Parse PubMed XML dictionary to retrieve abstract. """ key_path = ['PubmedArticleSet', 'PubmedArticle', 'MedlineCitation', 'Article', 'Abstract', 'AbstractText'] abstract_xml = reduce(dict.get, key_path, xml_dict) abst...
[ "def", "parse_abstract", "(", "xml_dict", ")", ":", "key_path", "=", "[", "'PubmedArticleSet'", ",", "'PubmedArticle'", ",", "'MedlineCitation'", ",", "'Article'", ",", "'Abstract'", ",", "'AbstractText'", "]", "abstract_xml", "=", "reduce", "(", "dict", ".", "g...
35.595238
0.001302
def parse(filename_or_url, parser=None, base_url=None, **kw): """ Parse a filename, URL, or file-like object into an HTML document tree. Note: this returns a tree, not an element. Use ``parse(...).getroot()`` to get the document root. You can override the base URL with the ``base_url`` keyword. ...
[ "def", "parse", "(", "filename_or_url", ",", "parser", "=", "None", ",", "base_url", "=", "None", ",", "*", "*", "kw", ")", ":", "if", "parser", "is", "None", ":", "parser", "=", "html_parser", "return", "etree", ".", "parse", "(", "filename_or_url", "...
41.916667
0.001946
def get_conn(self): """ Retrieves connection to Cloud Text to Speech. :return: Google Cloud Text to Speech client object. :rtype: google.cloud.texttospeech_v1.TextToSpeechClient """ if not self._client: self._client = TextToSpeechClient(credentials=self._get_...
[ "def", "get_conn", "(", "self", ")", ":", "if", "not", "self", ".", "_client", ":", "self", ".", "_client", "=", "TextToSpeechClient", "(", "credentials", "=", "self", ".", "_get_credentials", "(", ")", ")", "return", "self", ".", "_client" ]
35.3
0.008287
def extract_text_log_artifacts(job_log): """Generate a set of artifacts by parsing from the raw text log.""" # parse a log given its url artifact_bc = ArtifactBuilderCollection(job_log.url) artifact_bc.parse() artifact_list = [] for name, artifact in artifact_bc.artifacts.items(): arti...
[ "def", "extract_text_log_artifacts", "(", "job_log", ")", ":", "# parse a log given its url", "artifact_bc", "=", "ArtifactBuilderCollection", "(", "job_log", ".", "url", ")", "artifact_bc", ".", "parse", "(", ")", "artifact_list", "=", "[", "]", "for", "name", ",...
29.176471
0.001953
def _add_goterms(self, go2obj_user, goid): """Add alt GO IDs to go2obj subset, if requested and relevant.""" goterm = self.go2obj_orig[goid] if goid != goterm.id and goterm.id in go2obj_user and goid not in go2obj_user: go2obj_user[goid] = goterm
[ "def", "_add_goterms", "(", "self", ",", "go2obj_user", ",", "goid", ")", ":", "goterm", "=", "self", ".", "go2obj_orig", "[", "goid", "]", "if", "goid", "!=", "goterm", ".", "id", "and", "goterm", ".", "id", "in", "go2obj_user", "and", "goid", "not", ...
55.6
0.010638
def make_muc_admin_quey(self): """ Create <query xmlns="...muc#admin"/> element in the stanza. :return: the element created. :returntype: `MucAdminQuery` """ self.clear_muc_child() self.muc_child=MucAdminQuery(parent=self.xmlnode) return self.muc_child
[ "def", "make_muc_admin_quey", "(", "self", ")", ":", "self", ".", "clear_muc_child", "(", ")", "self", ".", "muc_child", "=", "MucAdminQuery", "(", "parent", "=", "self", ".", "xmlnode", ")", "return", "self", ".", "muc_child" ]
30.8
0.009464
def configure_host_cache(host_ref, datastore_ref, swap_size_MiB, host_cache_manager=None): ''' Configures the host cahe of the specified host host_ref The vim.HostSystem object representing the host that contains the requested disks. datastore_ref The v...
[ "def", "configure_host_cache", "(", "host_ref", ",", "datastore_ref", ",", "swap_size_MiB", ",", "host_cache_manager", "=", "None", ")", ":", "hostname", "=", "get_managed_object_name", "(", "host_ref", ")", "if", "not", "host_cache_manager", ":", "props", "=", "g...
40.576923
0.000463
def set_dtype(self, opt, dtype): """Set the `dtype` attribute. If opt['DataType'] has a value other than None, it overrides the `dtype` parameter of this method. No changes are made if the `dtype` attribute already exists and has a value other than 'None'. Parameters ---...
[ "def", "set_dtype", "(", "self", ",", "opt", ",", "dtype", ")", ":", "# Take no action of self.dtype exists and is not None", "if", "not", "hasattr", "(", "self", ",", "'dtype'", ")", "or", "self", ".", "dtype", "is", "None", ":", "# DataType option overrides expl...
40.190476
0.002315
def expandScopes(self, *args, **kwargs): """ Expand Scopes Return an expanded copy of the given scopeset, with scopes implied by any roles included. This method takes input: ``v1/scopeset.json#`` This method gives output: ``v1/scopeset.json#`` This method is `...
[ "def", "expandScopes", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_makeApiCall", "(", "self", ".", "funcinfo", "[", "\"expandScopes\"", "]", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
27.266667
0.009456
def generate_molecule_object_dict(source, format, values): """Generate a dictionary that represents a Squonk MoleculeObject when written as JSON :param source: Molecules in molfile or smiles format :param format: The format of the molecule. Either 'mol' or 'smiles' :param values: Optional dict of v...
[ "def", "generate_molecule_object_dict", "(", "source", ",", "format", ",", "values", ")", ":", "m", "=", "{", "\"uuid\"", ":", "str", "(", "uuid", ".", "uuid4", "(", ")", ")", ",", "\"source\"", ":", "source", ",", "\"format\"", ":", "format", "}", "if...
40.583333
0.002008
def get_resourcegroupitems(group_id, scenario_id, **kwargs): """ Get all the items in a group, in a scenario. If group_id is None, return all items across all groups in the scenario. """ rgi_qry = db.DBSession.query(ResourceGroupItem).\ filter(ResourceGroupItem.scenario_id=...
[ "def", "get_resourcegroupitems", "(", "group_id", ",", "scenario_id", ",", "*", "*", "kwargs", ")", ":", "rgi_qry", "=", "db", ".", "DBSession", ".", "query", "(", "ResourceGroupItem", ")", ".", "filter", "(", "ResourceGroupItem", ".", "scenario_id", "==", "...
28.75
0.010526
def contains_point( self, x, y ): """Is the point (x,y) on this curve?""" return ( y * y - ( x * x * x + self.__a * x + self.__b ) ) % self.__p == 0
[ "def", "contains_point", "(", "self", ",", "x", ",", "y", ")", ":", "return", "(", "y", "*", "y", "-", "(", "x", "*", "x", "*", "x", "+", "self", ".", "__a", "*", "x", "+", "self", ".", "__b", ")", ")", "%", "self", ".", "__p", "==", "0" ...
51.333333
0.044872
def reversed(self): ''' Return a new FSM such that for every string that self accepts (e.g. "beer", the new FSM accepts the reversed string ("reeb"). ''' alphabet = self.alphabet # Start from a composite "state-set" consisting of all final states. # If there are no final states, this set is empty and w...
[ "def", "reversed", "(", "self", ")", ":", "alphabet", "=", "self", ".", "alphabet", "# Start from a composite \"state-set\" consisting of all final states.", "# If there are no final states, this set is empty and we'll find that", "# no other states get generated.", "initial", "=", "...
28.806452
0.030336
def move(self, drow, dcol=0): """Move the token by `drow` rows and `dcol` columns.""" self._start_row += drow self._start_col += dcol self._end_row += drow self._end_col += dcol
[ "def", "move", "(", "self", ",", "drow", ",", "dcol", "=", "0", ")", ":", "self", ".", "_start_row", "+=", "drow", "self", ".", "_start_col", "+=", "dcol", "self", ".", "_end_row", "+=", "drow", "self", ".", "_end_col", "+=", "dcol" ]
35.333333
0.009217
def copy(self, newtablename, deep=False, valuecopy=False, dminfo={}, endian='aipsrc', memorytable=False, copynorows=False): """Copy the table and return a table object for the copy. It copies all data in the columns and keywords. Besides the table, all its subtables are copied too....
[ "def", "copy", "(", "self", ",", "newtablename", ",", "deep", "=", "False", ",", "valuecopy", "=", "False", ",", "dminfo", "=", "{", "}", ",", "endian", "=", "'aipsrc'", ",", "memorytable", "=", "False", ",", "copynorows", "=", "False", ")", ":", "t"...
46.333333
0.00151
def write(context): """Starts a new article""" config = context.obj title = click.prompt('Title') author = click.prompt('Author', default=config.get('DEFAULT_AUTHOR')) slug = slugify(title) creation_date = datetime.now() basename = '{:%Y-%m-%d}_{}.md'.format(creation_date, slug) meta ...
[ "def", "write", "(", "context", ")", ":", "config", "=", "context", ".", "obj", "title", "=", "click", ".", "prompt", "(", "'Title'", ")", "author", "=", "click", ".", "prompt", "(", "'Author'", ",", "default", "=", "config", ".", "get", "(", "'DEFAU...
30.030303
0.000978
def assemble_oligos(dna_list, reference=None): '''Given a list of DNA sequences, assemble into a single construct. :param dna_list: List of DNA sequences - they must be single-stranded. :type dna_list: coral.DNA list :param reference: Expected sequence - once assembly completed, this will be used to...
[ "def", "assemble_oligos", "(", "dna_list", ",", "reference", "=", "None", ")", ":", "# FIXME: this protocol currently only supports 5' ends on the assembly", "# Find all matches for every oligo. If more than 2 per side, error.", "# Self-oligo is included in case the 3' end is self-complement...
44.82716
0.000269
def time_bins(header): ''' Returns the time-axis lower bin edge values for the spectrogram. ''' return np.arange(header['number_of_half_frames'], dtype=np.float64)*constants.bins_per_half_frame\ *(1.0 - header['over_sampling']) / header['subband_spacing_hz']
[ "def", "time_bins", "(", "header", ")", ":", "return", "np", ".", "arange", "(", "header", "[", "'number_of_half_frames'", "]", ",", "dtype", "=", "np", ".", "float64", ")", "*", "constants", ".", "bins_per_half_frame", "*", "(", "1.0", "-", "header", "[...
43.833333
0.022388
def get_parent_mode_constraints(self): """Return the category and subcategory keys to be set in the subordinate mode. :returns: (the category definition, the hazard/exposure definition) :rtype: (dict, dict) """ h, e, _hc, _ec = self.selected_impact_function_constraints()...
[ "def", "get_parent_mode_constraints", "(", "self", ")", ":", "h", ",", "e", ",", "_hc", ",", "_ec", "=", "self", ".", "selected_impact_function_constraints", "(", ")", "if", "self", ".", "parent_step", "in", "[", "self", ".", "step_fc_hazlayer_from_canvas", ",...
40.913043
0.002077
def install(application, io_loop=None, **kwargs): """Call this to install AMQP for the Tornado application. Additional keyword arguments are passed through to the constructor of the AMQP object. :param tornado.web.Application application: The tornado application :param tornado.ioloop.IOLoop io_loop...
[ "def", "install", "(", "application", ",", "io_loop", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "getattr", "(", "application", ",", "'amqp'", ",", "None", ")", "is", "not", "None", ":", "LOGGER", ".", "warning", "(", "'AMQP is already install...
38.842105
0.000441
def create(backbone: ModelFactory, input_block: typing.Optional[ModelFactory]=None): """ Vel factory function """ if input_block is None: input_block = IdentityFactory() return PolicyGradientRnnModelFactory( input_block=input_block, backbone=backbone )
[ "def", "create", "(", "backbone", ":", "ModelFactory", ",", "input_block", ":", "typing", ".", "Optional", "[", "ModelFactory", "]", "=", "None", ")", ":", "if", "input_block", "is", "None", ":", "input_block", "=", "IdentityFactory", "(", ")", "return", "...
31.666667
0.013652
def shutdown(opts): ''' Closes connection with the device. ''' try: if not NETWORK_DEVICE.get('UP', False): raise Exception('not connected!') NETWORK_DEVICE.get('DRIVER').close() except Exception as error: port = NETWORK_DEVICE.get('OPTIONAL_ARGS', {}).get('port')...
[ "def", "shutdown", "(", "opts", ")", ":", "try", ":", "if", "not", "NETWORK_DEVICE", ".", "get", "(", "'UP'", ",", "False", ")", ":", "raise", "Exception", "(", "'not connected!'", ")", "NETWORK_DEVICE", ".", "get", "(", "'DRIVER'", ")", ".", "close", ...
30.833333
0.001748
def clear(self): """Remove all queue entries.""" self.mutex.acquire() self.queue.clear() self.mutex.release()
[ "def", "clear", "(", "self", ")", ":", "self", ".", "mutex", ".", "acquire", "(", ")", "self", ".", "queue", ".", "clear", "(", ")", "self", ".", "mutex", ".", "release", "(", ")" ]
27.4
0.014184
def make_default(spec): """Create an empty document that follows spec. Any field with a default will take that value, required or not. Required fields with no default will get a value of None. If your default value does not match your type or otherwise customized Field class, this can create a spec t...
[ "def", "make_default", "(", "spec", ")", ":", "doc", "=", "{", "}", "for", "key", ",", "field", "in", "spec", ".", "iteritems", "(", ")", ":", "if", "field", ".", "default", "is", "not", "no_default", ":", "doc", "[", "key", "]", "=", "field", "....
44.272727
0.002012
def _nest(self): """nests the roles (creates roles hierarchy)""" self._flatten() parent_roles = {} for roleid in self.flatten: role = copy.deepcopy(self.flatten[roleid]) # Display name is mandatory if 'display_name' not in role: raise ...
[ "def", "_nest", "(", "self", ")", ":", "self", ".", "_flatten", "(", ")", "parent_roles", "=", "{", "}", "for", "roleid", "in", "self", ".", "flatten", ":", "role", "=", "copy", ".", "deepcopy", "(", "self", ".", "flatten", "[", "roleid", "]", ")",...
36.866667
0.000704
def process_column(self, idx, value): "Process a single column." if value is not None: value = str(value).decode(self.encoding) return value
[ "def", "process_column", "(", "self", ",", "idx", ",", "value", ")", ":", "if", "value", "is", "not", "None", ":", "value", "=", "str", "(", "value", ")", ".", "decode", "(", "self", ".", "encoding", ")", "return", "value" ]
34.4
0.011364
def mtf_resnet_base(): """Set of hyperparameters.""" hparams = common_hparams.basic_params1() hparams.no_data_parallelism = True hparams.use_fixed_batch_size = True hparams.batch_size = 32 hparams.max_length = 3072 hparams.hidden_size = 256 hparams.label_smoothing = 0.0 # 8-way model-parallelism hpa...
[ "def", "mtf_resnet_base", "(", ")", ":", "hparams", "=", "common_hparams", ".", "basic_params1", "(", ")", "hparams", ".", "no_data_parallelism", "=", "True", "hparams", ".", "use_fixed_batch_size", "=", "True", "hparams", ".", "batch_size", "=", "32", "hparams"...
31.272727
0.026779
def get_time(self, idx=0): """Time of the data Returns nan if the time is not defined """ thetime = super(SingleData, self).get_time(idx=0) return thetime
[ "def", "get_time", "(", "self", ",", "idx", "=", "0", ")", ":", "thetime", "=", "super", "(", "SingleData", ",", "self", ")", ".", "get_time", "(", "idx", "=", "0", ")", "return", "thetime" ]
27
0.010256
def main(): """Upgrades the firmware of the J-Links connected to a Windows device. Returns: None. Raises: OSError: if there are no J-Link software packages. """ windows_libraries = list(pylink.Library.find_library_windows()) latest_library = None for lib in windows_libraries: ...
[ "def", "main", "(", ")", ":", "windows_libraries", "=", "list", "(", "pylink", ".", "Library", ".", "find_library_windows", "(", ")", ")", "latest_library", "=", "None", "for", "lib", "in", "windows_libraries", ":", "if", "os", ".", "path", ".", "dirname",...
30.5
0.000883
def request_version(req_headers): ''' Determines the bakery protocol version from a client request. If the protocol cannot be determined, or is invalid, the original version of the protocol is used. If a later version is found, the latest known version is used, which is OK because versions are backwardl...
[ "def", "request_version", "(", "req_headers", ")", ":", "vs", "=", "req_headers", ".", "get", "(", "BAKERY_PROTOCOL_HEADER", ")", "if", "vs", "is", "None", ":", "# No header - use backward compatibility mode.", "return", "bakery", ".", "VERSION_1", "try", ":", "x"...
40.434783
0.00105
def _process_delivery(self, pn_delivery): """Check if the delivery can be processed.""" if pn_delivery.tag in self._send_requests: if pn_delivery.settled or pn_delivery.remote_state: # remote has reached a 'terminal state' outcome = pn_delivery.remote_state ...
[ "def", "_process_delivery", "(", "self", ",", "pn_delivery", ")", ":", "if", "pn_delivery", ".", "tag", "in", "self", ".", "_send_requests", ":", "if", "pn_delivery", ".", "settled", "or", "pn_delivery", ".", "remote_state", ":", "# remote has reached a 'terminal ...
52.1875
0.001176
def lines_of_content(content, width): """ 计算内容在特定输出宽度下实际显示的行数 calculate the actual rows with specific terminal width """ result = 0 if isinstance(content, list): for line in content: _line = preprocess(line) result += ceil(line_width(_line) / width) elif isins...
[ "def", "lines_of_content", "(", "content", ",", "width", ")", ":", "result", "=", "0", "if", "isinstance", "(", "content", ",", "list", ")", ":", "for", "line", "in", "content", ":", "_line", "=", "preprocess", "(", "line", ")", "result", "+=", "ceil",...
34.941176
0.001639
def check_repo_ok(self): """ Make sure that the ns-3 repository's HEAD commit is the same as the one saved in the campaign database, and that the ns-3 repository is clean (i.e., no untracked or modified files exist). """ from git import Repo, exc # Check that git ...
[ "def", "check_repo_ok", "(", "self", ")", ":", "from", "git", "import", "Repo", ",", "exc", "# Check that git is at the expected commit and that the repo is not", "# dirty", "if", "self", ".", "runner", "is", "not", "None", ":", "path", "=", "self", ".", "runner",...
46.444444
0.001563
def suites(self, request, pk=None): """ List of test suite names available in this project """ suites_names = self.get_object().suites.values_list('slug') suites_metadata = SuiteMetadata.objects.filter(kind='suite', suite__in=suites_names) page = self.paginate_queryset(su...
[ "def", "suites", "(", "self", ",", "request", ",", "pk", "=", "None", ")", ":", "suites_names", "=", "self", ".", "get_object", "(", ")", ".", "suites", ".", "values_list", "(", "'slug'", ")", "suites_metadata", "=", "SuiteMetadata", ".", "objects", ".",...
53.111111
0.00823
def register(): """Plugin registration.""" if not plim: logger.warning('`slim` failed to load dependency `plim`. ' '`slim` plugin not loaded.') return if not mako: logger.warning('`slim` failed to load dependency `mako`. ' '`slim` plugin ...
[ "def", "register", "(", ")", ":", "if", "not", "plim", ":", "logger", ".", "warning", "(", "'`slim` failed to load dependency `plim`. '", "'`slim` plugin not loaded.'", ")", "return", "if", "not", "mako", ":", "logger", ".", "warning", "(", "'`slim` failed to load d...
34.4
0.001414
def ticket_forms_reorder(self, data, **kwargs): "https://developer.zendesk.com/rest_api/docs/core/ticket_forms#reorder-ticket-forms" api_path = "/api/v2/ticket_forms/reorder.json" return self.call(api_path, method="PUT", data=data, **kwargs)
[ "def", "ticket_forms_reorder", "(", "self", ",", "data", ",", "*", "*", "kwargs", ")", ":", "api_path", "=", "\"/api/v2/ticket_forms/reorder.json\"", "return", "self", ".", "call", "(", "api_path", ",", "method", "=", "\"PUT\"", ",", "data", "=", "data", ","...
65.5
0.011321