text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def effectiveTagSet(self): """Return a :class:`~pyasn1.type.tag.TagSet` object of the currently initialized component or self (if |ASN.1| is tagged).""" if self.tagSet: return self.tagSet else: component = self.getComponent() return component.effectiveTagSet
[ "def", "effectiveTagSet", "(", "self", ")", ":", "if", "self", ".", "tagSet", ":", "return", "self", ".", "tagSet", "else", ":", "component", "=", "self", ".", "getComponent", "(", ")", "return", "component", ".", "effectiveTagSet" ]
44.571429
0.009434
def get_file_contents_text( filename: str = None, blob: bytes = None, config: TextProcessingConfig = _DEFAULT_CONFIG) -> str: """ Returns the string contents of a file, or of a BLOB. """ binary_contents = get_file_contents(filename=filename, blob=blob) # 1. Try the encoding the user ...
[ "def", "get_file_contents_text", "(", "filename", ":", "str", "=", "None", ",", "blob", ":", "bytes", "=", "None", ",", "config", ":", "TextProcessingConfig", "=", "_DEFAULT_CONFIG", ")", "->", "str", ":", "binary_contents", "=", "get_file_contents", "(", "fil...
39.482759
0.000853
def _ConvertAnyMessage(self, value, message): """Convert a JSON representation into Any message.""" if isinstance(value, dict) and not value: return try: type_url = value['@type'] except KeyError: raise ParseError('@type is missing when parsing any message.') sub_message = _Create...
[ "def", "_ConvertAnyMessage", "(", "self", ",", "value", ",", "message", ")", ":", "if", "isinstance", "(", "value", ",", "dict", ")", "and", "not", "value", ":", "return", "try", ":", "type_url", "=", "value", "[", "'@type'", "]", "except", "KeyError", ...
37.347826
0.009081
def parse_JSON(self, JSON_string): """ Parses a list of *UVIndex* instances out of raw JSON data. Only certain properties of the data are used: if these properties are not found or cannot be parsed, an error is issued. :param JSON_string: a raw JSON string :type JSON_str...
[ "def", "parse_JSON", "(", "self", ",", "JSON_string", ")", ":", "if", "JSON_string", "is", "None", ":", "raise", "parse_response_error", ".", "ParseResponseError", "(", "'JSON data is None'", ")", "d", "=", "json", ".", "loads", "(", "JSON_string", ")", "uvind...
44.4
0.002205
def getUrlFromFilename(self, filename): """Construct URL from filename.""" components = util.splitpath(util.getRelativePath(self.basepath, filename)) url = '/'.join([url_quote(component, '') for component in components]) return self.baseurl + url
[ "def", "getUrlFromFilename", "(", "self", ",", "filename", ")", ":", "components", "=", "util", ".", "splitpath", "(", "util", ".", "getRelativePath", "(", "self", ".", "basepath", ",", "filename", ")", ")", "url", "=", "'/'", ".", "join", "(", "[", "u...
54.8
0.010791
def _wrap(text, wrap_max=80, indent=4): """Wrap text at given width using textwrap module. text (unicode): Text to wrap. If it's a Path, it's converted to string. wrap_max (int): Maximum line length (indent is deducted). indent (int): Number of spaces for indentation. RETURNS (unicode): Wrapped tex...
[ "def", "_wrap", "(", "text", ",", "wrap_max", "=", "80", ",", "indent", "=", "4", ")", ":", "indent", "=", "indent", "*", "' '", "wrap_width", "=", "wrap_max", "-", "len", "(", "indent", ")", "if", "isinstance", "(", "text", ",", "Path", ")", ":", ...
42.6
0.001531
def fetch(self, failures=True, wait=0): """ get the task result objects from the chain when it finishes. blocks until timeout. :param failures: include failed tasks :param int wait: how many milliseconds to wait for a result :return: an unsorted list of task objects """ ...
[ "def", "fetch", "(", "self", ",", "failures", "=", "True", ",", "wait", "=", "0", ")", ":", "if", "self", ".", "started", ":", "return", "fetch_group", "(", "self", ".", "group", ",", "failures", "=", "failures", ",", "wait", "=", "wait", ",", "cou...
49.888889
0.008753
def __PrintMessageDocstringLines(self, message_type): """Print the docstring for this message.""" description = message_type.description or '%s message type.' % ( message_type.name) short_description = ( _EmptyMessage(message_type) and len(description) < (self...
[ "def", "__PrintMessageDocstringLines", "(", "self", ",", "message_type", ")", ":", "description", "=", "message_type", ".", "description", "or", "'%s message type.'", "%", "(", "message_type", ".", "name", ")", "short_description", "=", "(", "_EmptyMessage", "(", ...
47.36
0.001656
def some(arr): """Return True iff there is an element, a, of arr such that a is not None""" return functools.reduce(lambda x, y: x or (y is not None), arr, False)
[ "def", "some", "(", "arr", ")", ":", "return", "functools", ".", "reduce", "(", "lambda", "x", ",", "y", ":", "x", "or", "(", "y", "is", "not", "None", ")", ",", "arr", ",", "False", ")" ]
56
0.011765
def mobilized(normal_fn): """ Replace a view function with a normal and mobile view. For example:: def view(): ... @mobilized(view) def view(): ... The second function is the mobile version of view. The original function is overwritten, and the de...
[ "def", "mobilized", "(", "normal_fn", ")", ":", "def", "decorator", "(", "mobile_fn", ")", ":", "@", "functools", ".", "wraps", "(", "mobile_fn", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "ctx", "=", "stack", ".", ...
26.2
0.001227
def get_param_bounds_from_config(cp, section, tag, param): """Gets bounds for the given parameter from a section in a config file. Minimum and maximum values for bounds are specified by adding `min-{param}` and `max-{param}` options, where `{param}` is the name of the parameter. The types of boundary (...
[ "def", "get_param_bounds_from_config", "(", "cp", ",", "section", ",", "tag", ",", "param", ")", ":", "try", ":", "minbnd", "=", "float", "(", "cp", ".", "get_opt_tag", "(", "section", ",", "'min-'", "+", "param", ",", "tag", ")", ")", "except", "Error...
34.604651
0.00098
def restore(self, value, context=None, inflated=True): """ Restores the value from a table cache for usage. :param value | <variant> context | <orb.Context> || None """ context = context or orb.Context() # check to see if this column is transl...
[ "def", "restore", "(", "self", ",", "value", ",", "context", "=", "None", ",", "inflated", "=", "True", ")", ":", "context", "=", "context", "or", "orb", ".", "Context", "(", ")", "# check to see if this column is translatable before restoring", "if", "self", ...
33.392857
0.002079
def ser_iuwt_decomposition(in1, scale_count, scale_adjust, store_smoothed): """ This function calls the a trous algorithm code to decompose the input into its wavelet coefficients. This is the isotropic undecimated wavelet transform implemented for a single CPU core. INPUTS: in1 (no...
[ "def", "ser_iuwt_decomposition", "(", "in1", ",", "scale_count", ",", "scale_adjust", ",", "store_smoothed", ")", ":", "wavelet_filter", "=", "(", "1.", "/", "16", ")", "*", "np", ".", "array", "(", "[", "1", ",", "4", ",", "6", ",", "4", ",", "1", ...
48.913043
0.010893
def validate_term(usr, pwd, hpo_term): """ Validate if the HPO term exists. Check if there are any result when querying phenomizer. Arguments: usr (str): A username for phenomizer pwd (str): A password for phenomizer hpo_term (string): Represents the hpo term Re...
[ "def", "validate_term", "(", "usr", ",", "pwd", ",", "hpo_term", ")", ":", "result", "=", "True", "try", ":", "for", "line", "in", "query", "(", "usr", ",", "pwd", ",", "hpo_term", ")", ":", "pass", "except", "RuntimeError", "as", "err", ":", "raise"...
22.833333
0.012259
def create_closure_model(cls): """Creates a <Model>Closure model in the same module as the model.""" meta_vals = { 'unique_together': (("parent", "child"),) } if getattr(cls._meta, 'db_table', None): meta_vals['db_table'] = '%sclosure' % getattr(cls._meta, 'db_table') model = type('...
[ "def", "create_closure_model", "(", "cls", ")", ":", "meta_vals", "=", "{", "'unique_together'", ":", "(", "(", "\"parent\"", ",", "\"child\"", ")", ",", ")", "}", "if", "getattr", "(", "cls", ".", "_meta", ",", "'db_table'", ",", "None", ")", ":", "me...
36.173913
0.001171
def _group_by_area(self, datasets): """Group datasets by their area.""" def _area_id(area_def): return area_def.name + str(area_def.area_extent) + str(area_def.shape) # get all of the datasets stored by area area_datasets = {} for x in datasets: area_id =...
[ "def", "_group_by_area", "(", "self", ",", "datasets", ")", ":", "def", "_area_id", "(", "area_def", ")", ":", "return", "area_def", ".", "name", "+", "str", "(", "area_def", ".", "area_extent", ")", "+", "str", "(", "area_def", ".", "shape", ")", "# g...
39.916667
0.008163
def embedManifestDllCheck(target, source, env): """Function run by embedManifestDllCheckAction to check for existence of manifest and other conditions, and embed the manifest by calling embedManifestDllAction if so.""" if env.get('WINDOWS_EMBED_MANIFEST', 0): manifestSrc = target[0].get_abspath() + ...
[ "def", "embedManifestDllCheck", "(", "target", ",", "source", ",", "env", ")", ":", "if", "env", ".", "get", "(", "'WINDOWS_EMBED_MANIFEST'", ",", "0", ")", ":", "manifestSrc", "=", "target", "[", "0", "]", ".", "get_abspath", "(", ")", "+", "'.manifest'...
52.307692
0.014451
def get_assessment_parts_by_item(self, item_id): """Gets the assessment parts containing the given item. In plenary mode, the returned list contains all known assessment parts or an error results. Otherwise, the returned list may contain only those assessment parts that are accessible t...
[ "def", "get_assessment_parts_by_item", "(", "self", ",", "item_id", ")", ":", "# Implemented from template for", "# osid.repository.AssetCompositionSession.get_compositions_by_asset", "collection", "=", "JSONClientValidated", "(", "'assessment_authoring'", ",", "collection", "=", ...
50
0.001453
def list_available_tools(self): """ Lists all the Benchmarks configuration files found in the configuration folders :return: """ benchmarks = [] if self.alternative_config_dir: for n in glob.glob(os.path.join(self.alternative_config_dir, self.BENCHMARKS_DIR,...
[ "def", "list_available_tools", "(", "self", ")", ":", "benchmarks", "=", "[", "]", "if", "self", ".", "alternative_config_dir", ":", "for", "n", "in", "glob", ".", "glob", "(", "os", ".", "path", ".", "join", "(", "self", ".", "alternative_config_dir", "...
38
0.010274
def configure(self, options, conf): """ Get the options. """ super(S3Logging, self).configure(options, conf) self.options = options
[ "def", "configure", "(", "self", ",", "options", ",", "conf", ")", ":", "super", "(", "S3Logging", ",", "self", ")", ".", "configure", "(", "options", ",", "conf", ")", "self", ".", "options", "=", "options" ]
38
0.012903
def on_data(self, data): """ This is the function called by the handler object upon receipt of incoming client data. The data is passed to the responder's parser class (via the :method:`consume` method), which digests and stores the HTTP data. Upon completion of ...
[ "def", "on_data", "(", "self", ",", "data", ")", ":", "# Headers have not been read in yet", "if", "len", "(", "self", ".", "headers", ")", "==", "0", ":", "# forward data to the parser", "data", "=", "self", ".", "parser", ".", "consume", "(", "data", ")", ...
40.038462
0.000938
def groupByNodes(requestContext, seriesList, callback, *nodes): """ Takes a serieslist and maps a callback to subgroups within as defined by multiple nodes. Example:: &target=groupByNodes(ganglia.server*.*.cpu.load*,"sumSeries",1,4) Would return multiple series which are each the result o...
[ "def", "groupByNodes", "(", "requestContext", ",", "seriesList", ",", "callback", ",", "*", "nodes", ")", ":", "from", ".", "app", "import", "app", "metaSeries", "=", "{", "}", "keys", "=", "[", "]", "if", "isinstance", "(", "nodes", ",", "int", ")", ...
34.973684
0.000732
def get_default_database(self): """DEPRECATED - Get the database named in the MongoDB connection URI. >>> uri = 'mongodb://host/my_database' >>> client = MongoClient(uri) >>> db = client.get_default_database() >>> assert db.name == 'my_database' >>> db = client.get_datab...
[ "def", "get_default_database", "(", "self", ")", ":", "warnings", ".", "warn", "(", "\"get_default_database is deprecated. Use get_database \"", "\"instead.\"", ",", "DeprecationWarning", ",", "stacklevel", "=", "2", ")", "if", "self", ".", "__default_database_name", "i...
40.590909
0.002188
def is_tRNA(clus_obj, out_dir, args): """ Iterates through cluster precursors to predict sRNA types """ ref = os.path.abspath(args.reference) utils.safe_dirs(out_dir) for nc in clus_obj[0]: c = clus_obj[0][nc] loci = c['loci'] out_fa = "cluster_" + nc if loci[0][3...
[ "def", "is_tRNA", "(", "clus_obj", ",", "out_dir", ",", "args", ")", ":", "ref", "=", "os", ".", "path", ".", "abspath", "(", "args", ".", "reference", ")", "utils", ".", "safe_dirs", "(", "out_dir", ")", "for", "nc", "in", "clus_obj", "[", "0", "]...
38.407407
0.000941
def obo(self): """str: the synonym serialized in obo format. """ return 'synonym: "{}" {} [{}]'.format( self.desc, ' '.join([self.scope, self.syn_type.name])\ if self.syn_type else self.scope, ', '.join(self.xref) )
[ "def", "obo", "(", "self", ")", ":", "return", "'synonym: \"{}\" {} [{}]'", ".", "format", "(", "self", ".", "desc", ",", "' '", ".", "join", "(", "[", "self", ".", "scope", ",", "self", ".", "syn_type", ".", "name", "]", ")", "if", "self", ".", "s...
32.333333
0.013378
def load_from_environ(): """ Load the SMC URL, API KEY and optional SSL certificate from the environment. Fields are:: SMC_ADDRESS=http://1.1.1.1:8082 SMC_API_KEY=123abc SMC_CLIENT_CERT=path/to/cert SMC_TIMEOUT = 30 (seconds) SMC_API_VERSION = 6.1 (optio...
[ "def", "load_from_environ", "(", ")", ":", "try", ":", "from", "urllib", ".", "parse", "import", "urlparse", "except", "ImportError", ":", "from", "urlparse", "import", "urlparse", "smc_address", "=", "os", ".", "environ", ".", "get", "(", "'SMC_ADDRESS'", "...
30.638889
0.008344
def add_time_stamp(self, db_id, name): """Add a timestamp to the database.""" with self.lock: self.cur.execute( 'insert into "timestamps" ("job", "what")' 'values (?, ?);', (db_id, name))
[ "def", "add_time_stamp", "(", "self", ",", "db_id", ",", "name", ")", ":", "with", "self", ".", "lock", ":", "self", ".", "cur", ".", "execute", "(", "'insert into \"timestamps\" (\"job\", \"what\")'", "'values (?, ?);'", ",", "(", "db_id", ",", "name", ")", ...
40.333333
0.008097
def _title_similarity_score(full_text, title): """Similarity scores for sentences with title in descending order""" sentences = sentence_tokenizer(full_text) norm = _normalize([title]+sentences) similarity_matrix = pairwise_kernels(norm, metric='cosine') return sorted(zip( ...
[ "def", "_title_similarity_score", "(", "full_text", ",", "title", ")", ":", "sentences", "=", "sentence_tokenizer", "(", "full_text", ")", "norm", "=", "_normalize", "(", "[", "title", "]", "+", "sentences", ")", "similarity_matrix", "=", "pairwise_kernels", "("...
35.466667
0.012821
def views(self, install, comp_sum): """Views packages """ pkg_sum = uni_sum = upg_sum = 0 # fix repositories align repo = self.repo + (" " * (6 - (len(self.repo)))) for pkg, comp in zip(install, comp_sum): pkg_repo = split_package(pkg[:-4]) if find...
[ "def", "views", "(", "self", ",", "install", ",", "comp_sum", ")", ":", "pkg_sum", "=", "uni_sum", "=", "upg_sum", "=", "0", "# fix repositories align", "repo", "=", "self", ".", "repo", "+", "(", "\" \"", "*", "(", "6", "-", "(", "len", "(", "self",...
44.961538
0.001675
def _format(self, object, stream, indent, allowance, context, level): """ Recursive part of the formatting """ try: PrettyPrinter._format(self, object, stream, indent, allowance, context, level) except Exception as e: stream.write(_format_exception(e))
[ "def", "_format", "(", "self", ",", "object", ",", "stream", ",", "indent", ",", "allowance", ",", "context", ",", "level", ")", ":", "try", ":", "PrettyPrinter", ".", "_format", "(", "self", ",", "object", ",", "stream", ",", "indent", ",", "allowance...
38.625
0.009494
def _get_sorter(subpath='', **defaults): """Return function to generate specific subreddit Submission listings.""" @restrict_access(scope='read') def _sorted(self, *args, **kwargs): """Return a get_content generator for some RedditContentObject type. The additional parameters are passed dir...
[ "def", "_get_sorter", "(", "subpath", "=", "''", ",", "*", "*", "defaults", ")", ":", "@", "restrict_access", "(", "scope", "=", "'read'", ")", "def", "_sorted", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "\"\"\"Return a get_cont...
43
0.001339
def _getOccurs(self, e): '''return a 3 item tuple ''' minOccurs = maxOccurs = '1' nillable = True return minOccurs,maxOccurs,nillable
[ "def", "_getOccurs", "(", "self", ",", "e", ")", ":", "minOccurs", "=", "maxOccurs", "=", "'1'", "nillable", "=", "True", "return", "minOccurs", ",", "maxOccurs", ",", "nillable" ]
28.166667
0.028736
def multivariate_normal(random, mean, cov): """ Draw random samples from a multivariate normal distribution. Parameters ---------- random : np.random.RandomState instance Random state. mean : array_like Mean of the n-dimensional distribution. cov : array_like Covaria...
[ "def", "multivariate_normal", "(", "random", ",", "mean", ",", "cov", ")", ":", "from", "numpy", ".", "linalg", "import", "cholesky", "L", "=", "cholesky", "(", "cov", ")", "return", "L", "@", "random", ".", "randn", "(", "L", ".", "shape", "[", "0",...
25.478261
0.001645
def dirty(field,ttl=None): "decorator to cache the result of a function until a field changes" if ttl is not None: raise NotImplementedError('pg.dirty ttl feature') def decorator(f): @functools.wraps(f) def wrapper(self,*args,**kwargs): # warning: not reentrant d=self.dirty_cache[field]...
[ "def", "dirty", "(", "field", ",", "ttl", "=", "None", ")", ":", "if", "ttl", "is", "not", "None", ":", "raise", "NotImplementedError", "(", "'pg.dirty ttl feature'", ")", "def", "decorator", "(", "f", ")", ":", "@", "functools", ".", "wraps", "(", "f"...
47.454545
0.037594
def _GetValueAsObject(self, property_value): """Retrieves the property value as a Python object. Args: property_value (pyolecf.property_value): OLECF property value. Returns: object: property value as a Python object. """ if property_value.type == pyolecf.value_types.BOOLEAN: ret...
[ "def", "_GetValueAsObject", "(", "self", ",", "property_value", ")", ":", "if", "property_value", ".", "type", "==", "pyolecf", ".", "value_types", ".", "BOOLEAN", ":", "return", "property_value", ".", "data_as_boolean", "if", "property_value", ".", "type", "in"...
25.791667
0.009346
def multi_component_layout( data, graph, n_components, component_labels, dim, random_state, metric="euclidean", metric_kwds={}, ): """Specialised layout algorithm for dealing with graphs with many connected components. This will first fid relative positions for the components by ...
[ "def", "multi_component_layout", "(", "data", ",", "graph", ",", "n_components", ",", "component_labels", ",", "dim", ",", "random_state", ",", "metric", "=", "\"euclidean\"", ",", "metric_kwds", "=", "{", "}", ",", ")", ":", "result", "=", "np", ".", "emp...
34.537879
0.002345
def handle_action(self, channel, nick, msg): "Core message parser and dispatcher" messages = () for handler in Handler.find_matching(msg, channel): exception_handler = functools.partial( self._handle_exception, handler=handler, ) rest = handler.process(msg) client = connection = event = None ...
[ "def", "handle_action", "(", "self", ",", "channel", ",", "nick", ",", "msg", ")", ":", "messages", "=", "(", ")", "for", "handler", "in", "Handler", ".", "find_matching", "(", "msg", ",", "channel", ")", ":", "exception_handler", "=", "functools", ".", ...
32
0.030349
def get_active_stats(self): """ Returns all of the active statistics for the gadgets currently registered. """ stats = [] for gadget in self._registry.values(): for s in gadget.stats: if s not in stats: stats.append(s) retur...
[ "def", "get_active_stats", "(", "self", ")", ":", "stats", "=", "[", "]", "for", "gadget", "in", "self", ".", "_registry", ".", "values", "(", ")", ":", "for", "s", "in", "gadget", ".", "stats", ":", "if", "s", "not", "in", "stats", ":", "stats", ...
31.8
0.009174
def subscribe_list(self, list_id): """ Subscribe to a list :param list_id: list ID number :return: :class:`~responsebot.models.List` object """ return List(tweepy_list_to_json(self._client.subscribe_list(list_id=list_id)))
[ "def", "subscribe_list", "(", "self", ",", "list_id", ")", ":", "return", "List", "(", "tweepy_list_to_json", "(", "self", ".", "_client", ".", "subscribe_list", "(", "list_id", "=", "list_id", ")", ")", ")" ]
33
0.01107
def stop(self): """Shutdown pyro naming server.""" args = self.getShutdownArgs() + ['shutdown'] Pyro.nsc.main(args) self.join()
[ "def", "stop", "(", "self", ")", ":", "args", "=", "self", ".", "getShutdownArgs", "(", ")", "+", "[", "'shutdown'", "]", "Pyro", ".", "nsc", ".", "main", "(", "args", ")", "self", ".", "join", "(", ")" ]
31
0.012579
def bias_correct(params, data, acf=None): """ Calculate and apply a bias correction to the given fit parameters Parameters ---------- params : lmfit.Parameters The model parameters. These will be modified. data : 2d-array The data which was used in the fitting acf : 2d-ar...
[ "def", "bias_correct", "(", "params", ",", "data", ",", "acf", "=", "None", ")", ":", "bias", "=", "RB_bias", "(", "data", ",", "params", ",", "acf", "=", "acf", ")", "i", "=", "0", "for", "p", "in", "params", ":", "if", "'theta'", "in", "p", "...
19.878788
0.001453
def xstep(self): r"""Minimise Augmented Lagrangian with respect to :math:`\mathbf{x}`.""" self.YU[:] = self.Y - self.U YUf = sl.rfftn(self.YU, None, self.cri.axisN) YUf0 = self.block_sep0(YUf) YUf1 = self.block_sep1(YUf) b = self.rho * np.sum(np.conj(self.GDf) *...
[ "def", "xstep", "(", "self", ")", ":", "self", ".", "YU", "[", ":", "]", "=", "self", ".", "Y", "-", "self", ".", "U", "YUf", "=", "sl", ".", "rfftn", "(", "self", ".", "YU", ",", "None", ",", "self", ".", "cri", ".", "axisN", ")", "YUf0", ...
51.070423
0.002165
def _similar_names(owner, attrname, distance_threshold, max_choices): """Given an owner and a name, try to find similar names The similar names are searched given a distance metric and only a given number of choices will be returned. """ possible_names = [] names = _node_names(owner) for n...
[ "def", "_similar_names", "(", "owner", ",", "attrname", ",", "distance_threshold", ",", "max_choices", ")", ":", "possible_names", "=", "[", "]", "names", "=", "_node_names", "(", "owner", ")", "for", "name", "in", "names", ":", "if", "name", "==", "attrna...
29.730769
0.001253
def tile_images(data, padsize=1, padval=0): """ Convert an array with shape of (B, C, H, W) into a tiled image. Args: data (~numpy.ndarray): An array with shape of (B, C, H, W). padsize (int): Each tile has padding with this size. padval (float): Padding pixels are filled with this ...
[ "def", "tile_images", "(", "data", ",", "padsize", "=", "1", ",", "padval", "=", "0", ")", ":", "assert", "(", "data", ".", "ndim", "==", "4", ")", "data", "=", "data", ".", "transpose", "(", "0", ",", "2", ",", "3", ",", "1", ")", "# force the...
30.885714
0.000897
def deprecate_entity( self, ilx_id: str, note = None, ) -> None: """ Tagged term in interlex to warn this term is no longer used There isn't an proper way to delete a term and so we have to mark it so I can extrapolate that in mysql/ttl loads. Args: ...
[ "def", "deprecate_entity", "(", "self", ",", "ilx_id", ":", "str", ",", "note", "=", "None", ",", ")", "->", "None", ":", "term_id", ",", "term_version", "=", "[", "(", "d", "[", "'id'", "]", ",", "d", "[", "'version'", "]", ")", "for", "d", "in"...
36.605263
0.009104
def fxy( z="sin(3*x)*log(x-y)/3", x=(0, 3), y=(0, 3), zlimits=(None, None), showNan=True, zlevels=10, wire=False, c="b", bc="aqua", alpha=1, texture="paper", res=100, ): """ Build a surface representing the function :math:`f(x,y)` specified as a string or as a...
[ "def", "fxy", "(", "z", "=", "\"sin(3*x)*log(x-y)/3\"", ",", "x", "=", "(", "0", ",", "3", ")", ",", "y", "=", "(", "0", ",", "3", ")", ",", "zlimits", "=", "(", "None", ",", "None", ")", ",", "showNan", "=", "True", ",", "zlevels", "=", "10"...
29.015152
0.002272
def getInstance(cls, *args): ''' Returns a singleton instance of the class ''' if not cls.__singleton: cls.__singleton = DriverManager(*args) return cls.__singleton
[ "def", "getInstance", "(", "cls", ",", "*", "args", ")", ":", "if", "not", "cls", ".", "__singleton", ":", "cls", ".", "__singleton", "=", "DriverManager", "(", "*", "args", ")", "return", "cls", ".", "__singleton" ]
30
0.009259
def list_(package='', cyg_arch='x86_64'): ''' List locally installed packages. package : '' package name to check. else all cyg_arch : Cygwin architecture to use Options are x86 and x86_64 CLI Example: .. code-block:: bash salt '*' cyg.list ''' pkgs =...
[ "def", "list_", "(", "package", "=", "''", ",", "cyg_arch", "=", "'x86_64'", ")", ":", "pkgs", "=", "{", "}", "args", "=", "' '", ".", "join", "(", "[", "'-c'", ",", "'-d'", ",", "package", "]", ")", "stdout", "=", "_cygcheck", "(", "args", ",", ...
24.266667
0.001321
def send_command_ack(self, device_id, action): """Send command, wait for gateway to repond with acknowledgment.""" # serialize commands yield from self._ready_to_send.acquire() acknowledgement = None try: self._command_ack.clear() self.send_command(device_...
[ "def", "send_command_ack", "(", "self", ",", "device_id", ",", "action", ")", ":", "# serialize commands", "yield", "from", "self", ".", "_ready_to_send", ".", "acquire", "(", ")", "acknowledgement", "=", "None", "try", ":", "self", ".", "_command_ack", ".", ...
40.083333
0.00203
async def workerTypeStats(self, *args, **kwargs): """ Look up the resource stats for a workerType Return an object which has a generic state description. This only contains counts of instances This method gives output: ``v1/worker-type-resources.json#`` This method is ``experi...
[ "async", "def", "workerTypeStats", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "await", "self", ".", "_makeApiCall", "(", "self", ".", "funcinfo", "[", "\"workerTypeStats\"", "]", ",", "*", "args", ",", "*", "*", "kwargs...
35
0.009281
def validate_config(config, required_keys, optional_keys=None): """ Validate a config dictionary to make sure it includes all required keys and does not include any unexpected keys. Args: config: the config to validate. required_keys: the names of the keys that the config must have. optional_keys...
[ "def", "validate_config", "(", "config", ",", "required_keys", ",", "optional_keys", "=", "None", ")", ":", "if", "optional_keys", "is", "None", ":", "optional_keys", "=", "[", "]", "if", "not", "isinstance", "(", "config", ",", "dict", ")", ":", "raise", ...
41.454545
0.010718
def spectrogram2(self, fftlength, overlap=None, window='hann', **kwargs): """Calculate the non-averaged power `Spectrogram` of this `TimeSeries` Parameters ---------- fftlength : `float` number of seconds in single FFT. overlap : `float`, optional number...
[ "def", "spectrogram2", "(", "self", ",", "fftlength", ",", "overlap", "=", "None", ",", "window", "=", "'hann'", ",", "*", "*", "kwargs", ")", ":", "# set kwargs for periodogram()", "kwargs", ".", "setdefault", "(", "'fs'", ",", "self", ".", "sample_rate", ...
41.320755
0.000892
def turn_on(self) -> "Signal": """ Turns on the signal. If processes are waiting, they are all resumed. This may be invoked from any code. Remark that while processes are simultaneously resumed in simulated time, they are effectively resumed in the sequence corresponding to the queue di...
[ "def", "turn_on", "(", "self", ")", "->", "\"Signal\"", ":", "if", "_logger", "is", "not", "None", ":", "self", ".", "_log", "(", "INFO", ",", "\"turn-on\"", ")", "self", ".", "_is_on", "=", "True", "while", "not", "self", ".", "_queue", ".", "is_emp...
53.4
0.008589
def create_rflink_connection(port=None, host=None, baud=57600, protocol=RflinkProtocol, packet_callback=None, event_callback=None, disconnect_callback=None, ignore=None, loop=None): """Create Rflink manager class, returns transport coroutine.""" # use de...
[ "def", "create_rflink_connection", "(", "port", "=", "None", ",", "host", "=", "None", ",", "baud", "=", "57600", ",", "protocol", "=", "RflinkProtocol", ",", "packet_callback", "=", "None", ",", "event_callback", "=", "None", ",", "disconnect_callback", "=", ...
38.636364
0.002296
def get_structure_from_name(self, structure_name): """ Return a structure from a name Args: structure_name (str): name of the structure Returns: Structure """ return next((st for st in self.structures if st.name == structure_name), None)
[ "def", "get_structure_from_name", "(", "self", ",", "structure_name", ")", ":", "return", "next", "(", "(", "st", "for", "st", "in", "self", ".", "structures", "if", "st", ".", "name", "==", "structure_name", ")", ",", "None", ")" ]
33.888889
0.009585
def create(vm_): ''' Create a single VM from a data dict. ''' try: if vm_['profile'] and config.is_profile_configured( __opts__, __active_provider_name__ or 'azurearm', vm_['profile'], vm_=vm_ ) is False: return False except...
[ "def", "create", "(", "vm_", ")", ":", "try", ":", "if", "vm_", "[", "'profile'", "]", "and", "config", ".", "is_profile_configured", "(", "__opts__", ",", "__active_provider_name__", "or", "'azurearm'", ",", "vm_", "[", "'profile'", "]", ",", "vm_", "=", ...
30.486726
0.000562
def post_event_access_codes(self, id, **data): """ POST /events/:id/access_codes/ Creates a new access code; returns the result as a :format:`access_code` as the key ``access_code``. """ return self.post("/events/{0}/access_codes/".format(id), data=data)
[ "def", "post_event_access_codes", "(", "self", ",", "id", ",", "*", "*", "data", ")", ":", "return", "self", ".", "post", "(", "\"/events/{0}/access_codes/\"", ".", "format", "(", "id", ")", ",", "data", "=", "data", ")" ]
42.428571
0.013201
def dump(config): """Dumps a stacker Config object as yaml. Args: config (:class:`Config`): the stacker Config object. stream (stream): an optional stream object to write to. Returns: str: the yaml formatted stacker Config. """ return yaml.safe_dump( config.to_pri...
[ "def", "dump", "(", "config", ")", ":", "return", "yaml", ".", "safe_dump", "(", "config", ".", "to_primitive", "(", ")", ",", "default_flow_style", "=", "False", ",", "encoding", "=", "'utf-8'", ",", "allow_unicode", "=", "True", ")" ]
23.588235
0.002398
def _can_use_fast_algorithm(x, y, exponent=1): """ Check if the fast algorithm for distance stats can be used. The fast algorithm has complexity :math:`O(NlogN)`, better than the complexity of the naive algorithm (:math:`O(N^2)`). The algorithm can only be used for random variables (not vectors) w...
[ "def", "_can_use_fast_algorithm", "(", "x", ",", "y", ",", "exponent", "=", "1", ")", ":", "return", "(", "_is_random_variable", "(", "x", ")", "and", "_is_random_variable", "(", "y", ")", "and", "x", ".", "shape", "[", "0", "]", ">", "3", "and", "y"...
40.692308
0.001848
def cleanOptions(options): """ Takes an options dict and returns a tuple containing the daemonize boolean, the reload boolean, and the parsed list of cleaned options as would be expected to be passed to hx """ _reload = options.pop('reload') dev = options.pop('dev') opts = [] store_t...
[ "def", "cleanOptions", "(", "options", ")", ":", "_reload", "=", "options", ".", "pop", "(", "'reload'", ")", "dev", "=", "options", ".", "pop", "(", "'dev'", ")", "opts", "=", "[", "]", "store_true", "=", "[", "'--nocache'", ",", "'--global_cache'", "...
32.45
0.001497
def filter_any_above_threshold( self, multi_key_fn, value_dict, threshold, default_value=0.0): """Like filter_above_threshold but `multi_key_fn` returns multiple keys and the element is kept if any of them have a value above the given t...
[ "def", "filter_any_above_threshold", "(", "self", ",", "multi_key_fn", ",", "value_dict", ",", "threshold", ",", "default_value", "=", "0.0", ")", ":", "def", "filter_fn", "(", "x", ")", ":", "for", "key", "in", "multi_key_fn", "(", "x", ")", ":", "value",...
32.212121
0.001826
def _update_process_stats(self): """Updates the process stats with the information from the processes This method is called at the end of each static parsing of the nextflow trace file. It re-populates the :attr:`process_stats` dictionary with the new stat metrics. """ ...
[ "def", "_update_process_stats", "(", "self", ")", ":", "good_status", "=", "[", "\"COMPLETED\"", ",", "\"CACHED\"", "]", "for", "process", ",", "vals", "in", "self", ".", "trace_info", ".", "items", "(", ")", ":", "# Update submission status of tags for each proce...
37.678161
0.000595
def enter(self): """Send a StartRequest.""" self._communication.send(StartRequest, self._communication.left_end_needle, self._communication.right_end_needle)
[ "def", "enter", "(", "self", ")", ":", "self", ".", "_communication", ".", "send", "(", "StartRequest", ",", "self", ".", "_communication", ".", "left_end_needle", ",", "self", ".", "_communication", ".", "right_end_needle", ")" ]
47
0.008368
def make_level_set(level): '''make level set will convert one level into a set''' new_level = dict() for key,value in level.items(): if isinstance(value,list): new_level[key] = set(value) else: new_level[key] = value return new_level
[ "def", "make_level_set", "(", "level", ")", ":", "new_level", "=", "dict", "(", ")", "for", "key", ",", "value", "in", "level", ".", "items", "(", ")", ":", "if", "isinstance", "(", "value", ",", "list", ")", ":", "new_level", "[", "key", "]", "=",...
28.4
0.010239
def __insert_frond_LF(d_w, d_u, dfs_data): """Encapsulates the process of inserting a frond uw into the left side frond group.""" # --Add the frond to the left side dfs_data['LF'].append( (d_w, d_u) ) dfs_data['FG']['l'] += 1 dfs_data['last_inserted_side'] = 'LF'
[ "def", "__insert_frond_LF", "(", "d_w", ",", "d_u", ",", "dfs_data", ")", ":", "# --Add the frond to the left side", "dfs_data", "[", "'LF'", "]", ".", "append", "(", "(", "d_w", ",", "d_u", ")", ")", "dfs_data", "[", "'FG'", "]", "[", "'l'", "]", "+=", ...
39.714286
0.014085
def dump(node, config): """ Convert a node tree to a simple nested dict All steps in this conversion are configurable using DumpConfig dump dictionary node: {"type": str, "data": dict} """ if config.is_node(node): fields = OrderedDict() for name in config.fields_iter(node): ...
[ "def", "dump", "(", "node", ",", "config", ")", ":", "if", "config", ".", "is_node", "(", "node", ")", ":", "fields", "=", "OrderedDict", "(", ")", "for", "name", "in", "config", ".", "fields_iter", "(", "node", ")", ":", "attr", "=", "config", "."...
33.473684
0.001529
def open_upload_stream(self, filename, chunk_size_bytes=None, metadata=None): """Opens a Stream that the application can write the contents of the file to. The user must specify the filename, and can choose to add any additional information in the metadata fie...
[ "def", "open_upload_stream", "(", "self", ",", "filename", ",", "chunk_size_bytes", "=", "None", ",", "metadata", "=", "None", ")", ":", "validate_string", "(", "\"filename\"", ",", "filename", ")", "opts", "=", "{", "\"filename\"", ":", "filename", ",", "\"...
41.95122
0.001705
def GetNames(cls): """Retrieves the names of the registered artifact definitions. Returns: list[str]: registered artifact definitions names. """ names = [] for plugin_class in cls._plugins.values(): name = getattr(plugin_class, 'ARTIFACT_DEFINITION_NAME', None) if name: na...
[ "def", "GetNames", "(", "cls", ")", ":", "names", "=", "[", "]", "for", "plugin_class", "in", "cls", ".", "_plugins", ".", "values", "(", ")", ":", "name", "=", "getattr", "(", "plugin_class", ",", "'ARTIFACT_DEFINITION_NAME'", ",", "None", ")", "if", ...
26.307692
0.008475
def clone(source, destination, dbs = None, verbose = False): """Clone Clone is used to clone one or many DBs/Tables from one host to another Args: source (dict): Data specifying the source instance A dictionary with the following possible elements: host, port, user, password, timeout, ssl (see rethinkdb py...
[ "def", "clone", "(", "source", ",", "destination", ",", "dbs", "=", "None", ",", "verbose", "=", "False", ")", ":", "# If the source is not a valid dict", "if", "not", "isinstance", "(", "source", ",", "dict", ")", ":", "raise", "ValueError", "(", "'source m...
26.609375
0.032642
def match_all_in(self, matches, item): """Matches all matches to elements of item.""" for i, match in enumerate(matches): self.match(match, item + "[" + str(i) + "]")
[ "def", "match_all_in", "(", "self", ",", "matches", ",", "item", ")", ":", "for", "i", ",", "match", "in", "enumerate", "(", "matches", ")", ":", "self", ".", "match", "(", "match", ",", "item", "+", "\"[\"", "+", "str", "(", "i", ")", "+", "\"]\...
47.75
0.010309
def _gradient_penalty(self, real_samples, fake_samples, kwargs): """ Compute the norm of the gradients for each sample in a batch, and penalize anything on either side of unit norm """ import torch from torch.autograd import Variable, grad real_samples = real_sam...
[ "def", "_gradient_penalty", "(", "self", ",", "real_samples", ",", "fake_samples", ",", "kwargs", ")", ":", "import", "torch", "from", "torch", ".", "autograd", "import", "Variable", ",", "grad", "real_samples", "=", "real_samples", ".", "view", "(", "fake_sam...
33.538462
0.001486
def serialize(self): """Serialize action.""" commands = [] for cmd in self.commands: commands.append(cmd.serialize()) out = {'commands': commands, 'deviceURL': self.__device_url} return out
[ "def", "serialize", "(", "self", ")", ":", "commands", "=", "[", "]", "for", "cmd", "in", "self", ".", "commands", ":", "commands", ".", "append", "(", "cmd", ".", "serialize", "(", ")", ")", "out", "=", "{", "'commands'", ":", "commands", ",", "'d...
23.5
0.008197
def _match_version_string(version): """Sort a binary version string into major, minor, and micro integers. :param str version: A version string in the form x.x.x :raises GnuPGVersionError: if the **version** string couldn't be parsed. :rtype: tuple :returns: A 3-tuple of integers, representing the...
[ "def", "_match_version_string", "(", "version", ")", ":", "matched", "=", "_VERSION_STRING_REGEX", ".", "match", "(", "version", ")", "g", "=", "matched", ".", "groups", "(", ")", "major", ",", "minor", ",", "micro", "=", "g", "[", "0", "]", ",", "g", ...
35.964286
0.000967
def package_path(cls, root, path): """Returns a normalized package path constructed from the given path and its root. A remote package path is the portion of the remote Go package's import path after the remote root path. For example, the remote import path 'https://github.com/bitly/go-simplejson' has...
[ "def", "package_path", "(", "cls", ",", "root", ",", "path", ")", ":", "package_path", "=", "os", ".", "path", ".", "relpath", "(", "path", ",", "root", ")", "return", "cls", ".", "normalize_package_path", "(", "package_path", ")" ]
54.958333
0.008197
def _subscribe_all(self): """ Subscribes all streams to their input. Subscribes all plugins to all their inputs. Subscribes all plugin outputs to the plugin. """ for stream in (self.inbound_streams + self.outbound_streams): for input_ in stream.inputs: ...
[ "def", "_subscribe_all", "(", "self", ")", ":", "for", "stream", "in", "(", "self", ".", "inbound_streams", "+", "self", ".", "outbound_streams", ")", ":", "for", "input_", "in", "stream", ".", "inputs", ":", "if", "not", "type", "(", "input_", ")", "i...
42.72
0.001832
def blink(self, status): """Turn blink cursor visibility on/off""" self._display_control = ByteUtil.apply_flag(self._display_control, Command.BLINKING_ON, status) self.command(self._display_control)
[ "def", "blink", "(", "self", ",", "status", ")", ":", "self", ".", "_display_control", "=", "ByteUtil", ".", "apply_flag", "(", "self", ".", "_display_control", ",", "Command", ".", "BLINKING_ON", ",", "status", ")", "self", ".", "command", "(", "self", ...
54.75
0.013514
def get_node(self, role: str, default=None) -> BioCNode: """ Get the first node with role Args: role: role default: node returned instead of raising StopIteration Returns: the first node with role """ return next((node for node in sel...
[ "def", "get_node", "(", "self", ",", "role", ":", "str", ",", "default", "=", "None", ")", "->", "BioCNode", ":", "return", "next", "(", "(", "node", "for", "node", "in", "self", ".", "nodes", "if", "node", ".", "role", "==", "role", ")", ",", "d...
29
0.008357
def _ufunc_wrapper(ufunc, name=None): """ A function to generate the top level biggus ufunc wrappers. """ if not isinstance(ufunc, np.ufunc): raise TypeError('{} is not a ufunc'.format(ufunc)) ufunc_name = ufunc.__name__ # Get hold of the masked array equivalent, if it exists. ma_u...
[ "def", "_ufunc_wrapper", "(", "ufunc", ",", "name", "=", "None", ")", ":", "if", "not", "isinstance", "(", "ufunc", ",", "np", ".", "ufunc", ")", ":", "raise", "TypeError", "(", "'{} is not a ufunc'", ".", "format", "(", "ufunc", ")", ")", "ufunc_name", ...
41.227273
0.001078
def readme_verify(): """Populate the template and compare to ``README``. Raises: ValueError: If the current README doesn't agree with the expected value computed from the template. """ expected = populate_readme(REVISION, RTD_VERSION) # Actually get the stored contents. with...
[ "def", "readme_verify", "(", ")", ":", "expected", "=", "populate_readme", "(", "REVISION", ",", "RTD_VERSION", ")", "# Actually get the stored contents.", "with", "open", "(", "README_FILE", ",", "\"r\"", ")", "as", "file_obj", ":", "contents", "=", "file_obj", ...
32.473684
0.001575
def as_bookmark_class(xso_class): """ Decorator to register `xso_class` as a custom bookmark class. This is necessary to store and retrieve such bookmarks. The registered class must be a subclass of the abstract base class :class:`Bookmark`. :raises TypeError: if `xso_class` is not a subclass ...
[ "def", "as_bookmark_class", "(", "xso_class", ")", ":", "if", "not", "issubclass", "(", "xso_class", ",", "Bookmark", ")", ":", "raise", "TypeError", "(", "\"Classes registered as bookmark types must be Bookmark subclasses\"", ")", "Storage", ".", "register_child", "(",...
26.772727
0.001639
def _parse10(self): """Messages are delimited by MSG_DELIM. The buffer could have grown by a maximum of BUF_SIZE bytes everytime this method is called. Retains state across method calls and if a chunk has been read it will not be considered again.""" self.logger.debug("parsing ...
[ "def", "_parse10", "(", "self", ")", ":", "self", ".", "logger", ".", "debug", "(", "\"parsing netconf v1.0\"", ")", "buf", "=", "self", ".", "_buffer", "buf", ".", "seek", "(", "self", ".", "_parsing_pos10", ")", "if", "MSG_DELIM", "in", "buf", ".", "...
43.875
0.002091
def SAS(self): """ Set-up for the rectangularly-gridded superposition of analytical solutions method for solving flexure """ if self.x is None: self.x = np.arange(self.dx/2., self.dx * self.qs.shape[0], self.dx) if self.filename: # Define the (scalar) elastic thickness self.Te...
[ "def", "SAS", "(", "self", ")", ":", "if", "self", ".", "x", "is", "None", ":", "self", ".", "x", "=", "np", ".", "arange", "(", "self", ".", "dx", "/", "2.", ",", "self", ".", "dx", "*", "self", ".", "qs", ".", "shape", "[", "0", "]", ",...
38.758621
0.015625
def _message_address_generate(self, beacon_config): """ Generate address for request/response message. :param beacon_config: server or client configuration. Client configuration is used for request and \ server configuration for response :return: bytes """ address = None if beacon_config['wasp-general:...
[ "def", "_message_address_generate", "(", "self", ",", "beacon_config", ")", ":", "address", "=", "None", "if", "beacon_config", "[", "'wasp-general::network::beacon'", "]", "[", "'public_address'", "]", "!=", "''", ":", "address", "=", "str", "(", "WIPV4SocketInfo...
38.043478
0.022297
def no_loop_in_parents(self, attr1, attr2): # pylint: disable=too-many-branches """ Find loop in dependencies. For now, used with the following attributes : :(self, parents): host dependencies from host object :(host_name, dependent_host_name):\ ho...
[ "def", "no_loop_in_parents", "(", "self", ",", "attr1", ",", "attr2", ")", ":", "# pylint: disable=too-many-branches", "# Ok, we say \"from now, no loop :) \"", "# in_loop = []", "# Create parent graph", "parents", "=", "Graph", "(", ")", "# Start with all items as nodes", "f...
35.079365
0.001761
def pounce(self, file, show=False): """writes a pounce command to the Purr pipe""" file = os.path.abspath(os.path.normpath(os.path.realpath(file))) self._write("pounce:%d:%s\n" % (int(show), file)) return self
[ "def", "pounce", "(", "self", ",", "file", ",", "show", "=", "False", ")", ":", "file", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "normpath", "(", "os", ".", "path", ".", "realpath", "(", "file", ")", ")", ")", "self"...
47.4
0.008299
def lu_solve_ATAI(A, rho, b, lu, piv, check_finite=True): r""" Solve the linear system :math:`(A^T A + \rho I)\mathbf{x} = \mathbf{b}` or :math:`(A^T A + \rho I)X = B` using :func:`scipy.linalg.lu_solve`. Parameters ---------- A : array_like Matrix :math:`A` rho : float Scalar :...
[ "def", "lu_solve_ATAI", "(", "A", ",", "rho", ",", "b", ",", "lu", ",", "piv", ",", "check_finite", "=", "True", ")", ":", "N", ",", "M", "=", "A", ".", "shape", "if", "N", ">=", "M", ":", "x", "=", "linalg", ".", "lu_solve", "(", "(", "lu", ...
31.805556
0.000847
def highpass(cutoff): """ This strategy uses an exponential approximation for cut-off frequency calculation, found by matching the one-pole Laplace lowpass filter and mirroring the resulting filter to get a highpass. """ R = thub(exp(cutoff - pi), 2) return (1 - R) / (1 + R * z ** -1)
[ "def", "highpass", "(", "cutoff", ")", ":", "R", "=", "thub", "(", "exp", "(", "cutoff", "-", "pi", ")", ",", "2", ")", "return", "(", "1", "-", "R", ")", "/", "(", "1", "+", "R", "*", "z", "**", "-", "1", ")" ]
36.5
0.013378
def move_page(request, page_id, extra_context=None): """Move the page to the requested target, at the given position.""" page = Page.objects.get(pk=page_id) target = request.POST.get('target', None) position = request.POST.get('position', None) if target is not None and position is not None: ...
[ "def", "move_page", "(", "request", ",", "page_id", ",", "extra_context", "=", "None", ")", ":", "page", "=", "Page", ".", "objects", ".", "get", "(", "pk", "=", "page_id", ")", "target", "=", "request", ".", "POST", ".", "get", "(", "'target'", ",",...
36.115385
0.001037
def get_inventory(self, keys=None): """ Create an Ansible inventory based on python dicts and lists. The returned value is a dict in which every key represents a group and every value is a list of entries for that group. Args: keys (list of str): Path to the keys tha...
[ "def", "get_inventory", "(", "self", ",", "keys", "=", "None", ")", ":", "inventory", "=", "defaultdict", "(", "list", ")", "keys", "=", "keys", "or", "[", "'vm-type'", ",", "'groups'", ",", "'vm-provider'", "]", "vms", "=", "self", ".", "prefix", ".",...
36.789474
0.001394
async def middleware(request, handler): """ Main middleware function, deals with all the X-Ray segment logic """ # Create X-Ray headers xray_header = construct_xray_header(request.headers) # Get name of service or generate a dynamic one from host name = calculate_segment_name(request.headers...
[ "async", "def", "middleware", "(", "request", ",", "handler", ")", ":", "# Create X-Ray headers", "xray_header", "=", "construct_xray_header", "(", "request", ".", "headers", ")", "# Get name of service or generate a dynamic one from host", "name", "=", "calculate_segment_n...
34.849315
0.001147
def gen_df_site( list_csv_in=list_table, url_base=url_repo_input_site)->pd.DataFrame: '''Generate description info of supy output results as a dataframe Parameters ---------- path_csv_out : str, optional path to the output csv file (the default is 'df_output.csv') list_csv_i...
[ "def", "gen_df_site", "(", "list_csv_in", "=", "list_table", ",", "url_base", "=", "url_repo_input_site", ")", "->", "pd", ".", "DataFrame", ":", "# list of URLs", "list_url_table", "=", "[", "url_base", "/", "table", "for", "table", "in", "list_csv_in", "]", ...
33.108108
0.001982
def pix_to_sub(self): """Compute the mappings between a pixelization's pixels and the unmasked sub-grid pixels. These mappings \ are determined after the regular-grid is used to determine the pixelization. The pixelization's pixels map to different number of sub-grid pixels, thus a list of list...
[ "def", "pix_to_sub", "(", "self", ")", ":", "pix_to_sub", "=", "[", "[", "]", "for", "_", "in", "range", "(", "self", ".", "pixels", ")", "]", "for", "regular_pixel", ",", "pix_pixel", "in", "enumerate", "(", "self", ".", "sub_to_pix", ")", ":", "pix...
47.083333
0.008681
def unorm(data, ord=None, axis=None, keepdims=False): """Matrix or vector norm that preserves units This is a wrapper around np.linalg.norm that preserves units. See the documentation for that function for descriptions of the keyword arguments. Examples -------- >>> from unyt import km ...
[ "def", "unorm", "(", "data", ",", "ord", "=", "None", ",", "axis", "=", "None", ",", "keepdims", "=", "False", ")", ":", "norm", "=", "np", ".", "linalg", ".", "norm", "(", "data", ",", "ord", "=", "ord", ",", "axis", "=", "axis", ",", "keepdim...
31.722222
0.001701
def refresh_menu(self): """Refresh context menu""" index = self.currentIndex() condition = index.isValid() self.edit_action.setEnabled( condition ) self.remove_action.setEnabled( condition ) self.refresh_plot_entries(index)
[ "def", "refresh_menu", "(", "self", ")", ":", "index", "=", "self", ".", "currentIndex", "(", ")", "condition", "=", "index", ".", "isValid", "(", ")", "self", ".", "edit_action", ".", "setEnabled", "(", "condition", ")", "self", ".", "remove_action", "....
38.714286
0.021661
def encrypt(public_key, message, label=b'', hash_class=hashlib.sha1, mgf=mgf.mgf1, seed=None, rnd=default_crypto_random): '''Encrypt a byte message using a RSA public key and the OAEP wrapping algorithm, Parameters: public_key - an RSA public key message - a byte string ...
[ "def", "encrypt", "(", "public_key", ",", "message", ",", "label", "=", "b''", ",", "hash_class", "=", "hashlib", ".", "sha1", ",", "mgf", "=", "mgf", ".", "mgf1", ",", "seed", "=", "None", ",", "rnd", "=", "default_crypto_random", ")", ":", "hash", ...
39.452381
0.000589
def upload(cookie, source_path, path, upload_mode): '''上传一个文件. 这个是使用的网页中的上传接口. upload_mode - const.UploadMode, 如果文件已在服务器上存在: * overwrite, 直接将其重写. * newcopy, 保留原先的文件, 并在新上传的文件名尾部加上当前时间戳. ''' ondup = const.UPLOAD_ONDUP[upload_mode] dir_name, file_name = os.path.split(path) url = '...
[ "def", "upload", "(", "cookie", ",", "source_path", ",", "path", ",", "upload_mode", ")", ":", "ondup", "=", "const", ".", "UPLOAD_ONDUP", "[", "upload_mode", "]", "dir_name", ",", "file_name", "=", "os", ".", "path", ".", "split", "(", "path", ")", "u...
32.107143
0.00108
def _generate_examples(self, images_dir_path, labels_path, setid_path, split_name): """Yields examples.""" with tf.io.gfile.GFile(labels_path, "rb") as f: labels = tfds.core.lazy_imports.scipy.io.loadmat(f)["labels"][0] with tf.io.gfile.GFile(setid_path, "rb") as f: exam...
[ "def", "_generate_examples", "(", "self", ",", "images_dir_path", ",", "labels_path", ",", "setid_path", ",", "split_name", ")", ":", "with", "tf", ".", "io", ".", "gfile", ".", "GFile", "(", "labels_path", ",", "\"rb\"", ")", "as", "f", ":", "labels", "...
40.6
0.009631
def info(self, message, payload=None): """DEPRECATED""" if payload: self.log(event=message, payload=payload) else: self.log(event=message) return self
[ "def", "info", "(", "self", ",", "message", ",", "payload", "=", "None", ")", ":", "if", "payload", ":", "self", ".", "log", "(", "event", "=", "message", ",", "payload", "=", "payload", ")", "else", ":", "self", ".", "log", "(", "event", "=", "m...
28.571429
0.009709
def slugify(string): """ Removes non-alpha characters, and converts spaces to hyphens. Useful for making file names. Source: http://stackoverflow.com/questions/5574042/string-slugification-in-python """ string = re.sub('[^\w .-]', '', string) string = string.replace(" ", "-") retu...
[ "def", "slugify", "(", "string", ")", ":", "string", "=", "re", ".", "sub", "(", "'[^\\w .-]'", ",", "''", ",", "string", ")", "string", "=", "string", ".", "replace", "(", "\" \"", ",", "\"-\"", ")", "return", "string" ]
32
0.012158
def close_connection(self): "Request a connection close from the SMTP session handling instance." if self._is_connected: self._is_connected = False self._command_parser.close_when_done()
[ "def", "close_connection", "(", "self", ")", ":", "if", "self", ".", "_is_connected", ":", "self", ".", "_is_connected", "=", "False", "self", ".", "_command_parser", ".", "close_when_done", "(", ")" ]
44.4
0.00885