text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def visit_Capture(self, node: parsing.Capture) -> [ast.stmt] or ast.expr: """Generates python code to capture text consumed by a clause. #If all clauses can be inlined self.beginTag('tagname') and clause and self.endTag('tagname') if not self.beginTag('tagname'): return Fal...
[ "def", "visit_Capture", "(", "self", ",", "node", ":", "parsing", ".", "Capture", ")", "->", "[", "ast", ".", "stmt", "]", "or", "ast", ".", "expr", ":", "begintag", "=", "ast", ".", "Attribute", "(", "ast", ".", "Name", "(", "'self'", ",", "ast", ...
38.285714
0.00182
def get_pstats_print2list(fnames, filter_fnames=None, exclude_fnames=None, sort=None, sort_reverse=None, limit=None): """Print stats with a filter or exclude filenames, sort index and limit. :param list fnames: cProfile standard files to process. :param list filter_fnames: Relative...
[ "def", "get_pstats_print2list", "(", "fnames", ",", "filter_fnames", "=", "None", ",", "exclude_fnames", "=", "None", ",", "sort", "=", "None", ",", "sort_reverse", "=", "None", ",", "limit", "=", "None", ")", ":", "if", "isinstance", "(", "fnames", ",", ...
41.432432
0.000319
def mtf_transformer_lm_baseline(): """Small language model to run on 1 TPU. Run this on 2x2 on languagemodel_lm1b32k_packed for 272000 steps (10 epochs) Results: params/10^9 log-ppl(per-token) 0.14 3.202 Returns: a hparams """ hparams = mtf_transformer_paper_lm(-1) hparams...
[ "def", "mtf_transformer_lm_baseline", "(", ")", ":", "hparams", "=", "mtf_transformer_paper_lm", "(", "-", "1", ")", "hparams", ".", "batch_size", "=", "128", "hparams", ".", "learning_rate_decay_steps", "=", "27200", "# one epoch on lm1b", "hparams", ".", "mesh_sha...
27.3125
0.015487
def whois_list(request, format=None): """ Retrieve basic whois information related to a layer2 or layer3 network address. """ results = [] # layer3 results for ip in Ip.objects.select_related().all(): interface = ip.interface user = interface.device.node.user device = int...
[ "def", "whois_list", "(", "request", ",", "format", "=", "None", ")", ":", "results", "=", "[", "]", "# layer3 results", "for", "ip", "in", "Ip", ".", "objects", ".", "select_related", "(", ")", ".", "all", "(", ")", ":", "interface", "=", "ip", ".",...
32.83871
0.001908
def load_modules(self, data=None, proxy=None): ''' Load the modules into the state ''' log.info('Loading fresh modules for state activity') self.utils = salt.loader.utils(self.opts) self.functions = salt.loader.minion_mods(self.opts, self.state_con, ...
[ "def", "load_modules", "(", "self", ",", "data", "=", "None", ",", "proxy", "=", "None", ")", ":", "log", ".", "info", "(", "'Loading fresh modules for state activity'", ")", "self", ".", "utils", "=", "salt", ".", "loader", ".", "utils", "(", "self", "....
49.454545
0.002404
def handle_processing_packets(): """handle_processing_packets Replacement packet processing engine. This is not done. """ host = os.getenv( "LISTEN_ON_HOST", "127.0.0.1").strip().lstrip() port = int(os.getenv( "LISTEN_ON_PORT", "80").strip().lstrip()) backlog =...
[ "def", "handle_processing_packets", "(", ")", ":", "host", "=", "os", ".", "getenv", "(", "\"LISTEN_ON_HOST\"", ",", "\"127.0.0.1\"", ")", ".", "strip", "(", ")", ".", "lstrip", "(", ")", "port", "=", "int", "(", "os", ".", "getenv", "(", "\"LISTEN_ON_PO...
30.322981
0.000198
def price_dataframe(symbols='sp5002012', start=datetime.datetime(2008, 1, 1), end=datetime.datetime(2009, 12, 31), price_type='actual_close', cleaner=clean_dataframe, ): """Retrieve the prices of a list of equities as a DataFrame (columns = symbols) Arguments: symbols (list of str):...
[ "def", "price_dataframe", "(", "symbols", "=", "'sp5002012'", ",", "start", "=", "datetime", ".", "datetime", "(", "2008", ",", "1", ",", "1", ")", ",", "end", "=", "datetime", ".", "datetime", "(", "2009", ",", "12", ",", "31", ")", ",", "price_type...
41.461538
0.00816
def disvec(self, x, y, aq=None): '''Returns array of size (2, nparam, naq)''' if aq is None: aq = self.model.aq.find_aquifer_data(x, y) return np.sum(self.parameters * self.disvecinf(x, y, aq), 1)
[ "def", "disvec", "(", "self", ",", "x", ",", "y", ",", "aq", "=", "None", ")", ":", "if", "aq", "is", "None", ":", "aq", "=", "self", ".", "model", ".", "aq", ".", "find_aquifer_data", "(", "x", ",", "y", ")", "return", "np", ".", "sum", "(",...
54.25
0.013636
def parse_localclasspath(self, tup_tree): """ Parse a LOCALCLASSPATH element and return the class path it represents as a CIMClassName object. :: <!ELEMENT LOCALCLASSPATH (LOCALNAMESPACEPATH, CLASSNAME)> """ self.check_node(tup_tree, 'LOCALCLASSPATH') ...
[ "def", "parse_localclasspath", "(", "self", ",", "tup_tree", ")", ":", "self", ".", "check_node", "(", "tup_tree", ",", "'LOCALCLASSPATH'", ")", "k", "=", "kids", "(", "tup_tree", ")", "if", "len", "(", "k", ")", "!=", "2", ":", "raise", "CIMXMLParseErro...
31.230769
0.002389
def is_highlink_density(self, element): """ checks the density of links within a node, is there not much text and most of it contains linky shit? if so it's no good """ links = self.parser.getElementsByTag(element, tag='a') if not links: return False ...
[ "def", "is_highlink_density", "(", "self", ",", "element", ")", ":", "links", "=", "self", ".", "parser", ".", "getElementsByTag", "(", "element", ",", "tag", "=", "'a'", ")", "if", "not", "links", ":", "return", "False", "text", "=", "self", ".", "par...
34.807692
0.002151
def random_link(self, dataset, state, backward=False): """Get a random link. Parameters ---------- dataset : `object` Dataset from `self.get_dataset()`. state : `object` Link source. backward : `bool`, optional Link direction. ...
[ "def", "random_link", "(", "self", ",", "dataset", ",", "state", ",", "backward", "=", "False", ")", ":", "links", "=", "self", ".", "get_links", "(", "dataset", ",", "state", ",", "backward", ")", "if", "not", "links", ":", "return", "None", ",", "N...
27.78125
0.002174
def copystat(self, target): """Copies the permissions, times and flags from this to the `target`. The owner is not copied. """ shutil.copystat(self.path, self._to_backend(target))
[ "def", "copystat", "(", "self", ",", "target", ")", ":", "shutil", ".", "copystat", "(", "self", ".", "path", ",", "self", ".", "_to_backend", "(", "target", ")", ")" ]
34.5
0.009434
def pb_for_delete(document_path, option): """Make a ``Write`` protobuf for ``delete()`` methods. Args: document_path (str): A fully-qualified document path. option (optional[~.firestore_v1beta1.client.WriteOption]): A write option to make assertions / preconditions on the server ...
[ "def", "pb_for_delete", "(", "document_path", ",", "option", ")", ":", "write_pb", "=", "write_pb2", ".", "Write", "(", "delete", "=", "document_path", ")", "if", "option", "is", "not", "None", ":", "option", ".", "modify_write", "(", "write_pb", ")", "ret...
34.944444
0.001548
def _convert_filetime_to_timestamp(filetime): """ Windows returns times as 64-bit unsigned longs that are the number of hundreds of nanoseconds since Jan 1 1601. This converts it to a datetime object. :param filetime: A FILETIME struct object :return: An integer unix timestamp ...
[ "def", "_convert_filetime_to_timestamp", "(", "filetime", ")", ":", "hundreds_nano_seconds", "=", "struct", ".", "unpack", "(", "b'>Q'", ",", "struct", ".", "pack", "(", "b'>LL'", ",", "filetime", ".", "dwHighDateTime", ",", "filetime", ".", "dwLowDateTime", ")"...
26
0.001613
def modulename(cls, depth=1): """ get caller's __name__ """ depth += cls.extra_depth frame = sys._getframe(depth) return frame.f_globals['__name__']
[ "def", "modulename", "(", "cls", ",", "depth", "=", "1", ")", ":", "depth", "+=", "cls", ".", "extra_depth", "frame", "=", "sys", ".", "_getframe", "(", "depth", ")", "return", "frame", ".", "f_globals", "[", "'__name__'", "]" ]
27.142857
0.010204
def _synthesize_multiple_generic(self, helper_function, text_file, output_file_path, quit_after=None, backwards=False): """ Synthesize multiple fragments, generic function. The ``helper_function`` is a function that takes parameters ``(text, voice_code, output_file_path)`` and r...
[ "def", "_synthesize_multiple_generic", "(", "self", ",", "helper_function", ",", "text_file", ",", "output_file_path", ",", "quit_after", "=", "None", ",", "backwards", "=", "False", ")", ":", "self", ".", "log", "(", "u\"Calling TTS engine using multiple generic func...
44.938776
0.002222
def convertImages(self): """ run this to turn all folder1 TIFs and JPGs into folder2 data. TIFs will be treated as micrographs and converted to JPG with enhanced contrast. JPGs will simply be copied over. """ # copy over JPGs (and such) exts=['.jpg','.png'] ...
[ "def", "convertImages", "(", "self", ")", ":", "# copy over JPGs (and such)", "exts", "=", "[", "'.jpg'", ",", "'.png'", "]", "for", "fname", "in", "[", "x", "for", "x", "in", "self", ".", "files1", "if", "cm", ".", "ext", "(", "x", ")", "in", "exts"...
44.4375
0.01927
def value_counts(self, dropna=True): """ Returns a Series containing counts of unique values. Parameters ---------- dropna : boolean, default True Don't include counts of NaN, even if NaN is in sp_values. Returns ------- counts : Series ...
[ "def", "value_counts", "(", "self", ",", "dropna", "=", "True", ")", ":", "from", "pandas", "import", "Index", ",", "Series", "keys", ",", "counts", "=", "algos", ".", "_value_counts_arraylike", "(", "self", ".", "sp_values", ",", "dropna", "=", "dropna", ...
30.756757
0.001704
def get_last(self): """ Get the last migration batch. :rtype: list """ query = self.table().where('batch', self.get_last_batch_number()) return query.order_by('migration', 'desc').get()
[ "def", "get_last", "(", "self", ")", ":", "query", "=", "self", ".", "table", "(", ")", ".", "where", "(", "'batch'", ",", "self", ".", "get_last_batch_number", "(", ")", ")", "return", "query", ".", "order_by", "(", "'migration'", ",", "'desc'", ")", ...
25.222222
0.008511
def refresh(self, token, timeout=None): """Set new timeout for lock, if existing and valid.""" if timeout is None: timeout = LockManager.LOCK_TIME_OUT_DEFAULT return self.storage.refresh(token, timeout)
[ "def", "refresh", "(", "self", ",", "token", ",", "timeout", "=", "None", ")", ":", "if", "timeout", "is", "None", ":", "timeout", "=", "LockManager", ".", "LOCK_TIME_OUT_DEFAULT", "return", "self", ".", "storage", ".", "refresh", "(", "token", ",", "tim...
46.8
0.008403
def gradev(data, rate=1.0, data_type="phase", taus=None, ci=0.9, noisetype='wp'): """ gap resistant overlapping Allan deviation Parameters ---------- data: np.array Input data. Provide either phase or frequency (fractional, adimensional). Warning : phase data works better (fr...
[ "def", "gradev", "(", "data", ",", "rate", "=", "1.0", ",", "data_type", "=", "\"phase\"", ",", "taus", "=", "None", ",", "ci", "=", "0.9", ",", "noisetype", "=", "'wp'", ")", ":", "if", "(", "data_type", "==", "\"freq\"", ")", ":", "print", "(", ...
36.942857
0.000377
def U(self): "Seconds since the Unix epoch (January 1 1970 00:00:00 GMT)" if getattr(self.data, 'tzinfo', None): return int(calendar.timegm(self.data.utctimetuple())) else: return int(time.mktime(self.data.timetuple()))
[ "def", "U", "(", "self", ")", ":", "if", "getattr", "(", "self", ".", "data", ",", "'tzinfo'", ",", "None", ")", ":", "return", "int", "(", "calendar", ".", "timegm", "(", "self", ".", "data", ".", "utctimetuple", "(", ")", ")", ")", "else", ":",...
39.666667
0.012346
def paga_adjacency( adata, adjacency='connectivities', adjacency_tree='connectivities_tree', as_heatmap=True, color_map=None, show=None, save=None): """Connectivity of paga groups. """ connectivity = adata.uns[adjacency].toarray() connectivity_sele...
[ "def", "paga_adjacency", "(", "adata", ",", "adjacency", "=", "'connectivities'", ",", "adjacency_tree", "=", "'connectivities_tree'", ",", "as_heatmap", "=", "True", ",", "color_map", "=", "None", ",", "show", "=", "None", ",", "save", "=", "None", ")", ":"...
38.821429
0.000898
def _get_filehandler_with_formatter(logname, formatter=None): """ Return a logging FileHandler for given logname using a given logging formatter :param logname: Name of the file where logs will be stored, ".log" extension will be added :param formatter: An instance of logging.Formatter or None if th...
[ "def", "_get_filehandler_with_formatter", "(", "logname", ",", "formatter", "=", "None", ")", ":", "handler", "=", "logging", ".", "FileHandler", "(", "logname", ")", "if", "formatter", "is", "not", "None", ":", "handler", ".", "setFormatter", "(", "formatter"...
37.615385
0.001996
def _validate_frequency(cls, index, freq, **kwargs): """ Validate that a frequency is compatible with the values of a given Datetime Array/Index or Timedelta Array/Index Parameters ---------- index : DatetimeIndex or TimedeltaIndex The index on which to deter...
[ "def", "_validate_frequency", "(", "cls", ",", "index", ",", "freq", ",", "*", "*", "kwargs", ")", ":", "if", "is_period_dtype", "(", "cls", ")", ":", "# Frequency validation is not meaningful for Period Array/Index", "return", "None", "inferred", "=", "index", "....
44.25641
0.001134
def stream_bytes(data, chunk_size=default_chunk_size): """Gets a buffered generator for streaming binary data. Returns a buffered generator which encodes binary data as :mimetype:`multipart/form-data` with the corresponding headers. Parameters ---------- data : bytes The data bytes to ...
[ "def", "stream_bytes", "(", "data", ",", "chunk_size", "=", "default_chunk_size", ")", ":", "stream", "=", "BytesStream", "(", "data", ",", "chunk_size", "=", "chunk_size", ")", "return", "stream", ".", "body", "(", ")", ",", "stream", ".", "headers" ]
26.45
0.001825
def compute_screen_line_counts( feed: "Feed", linestring: LineString, dates: List[str], geo_shapes=None ) -> DataFrame: """ Find all the Feed trips active on the given dates that intersect the given Shapely LineString (with WGS84 longitude-latitude coordinates). Parameters ---------- fe...
[ "def", "compute_screen_line_counts", "(", "feed", ":", "\"Feed\"", ",", "linestring", ":", "LineString", ",", "dates", ":", "List", "[", "str", "]", ",", "geo_shapes", "=", "None", ")", "->", "DataFrame", ":", "dates", "=", "feed", ".", "restrict_dates", "...
37.584795
0.000152
def pposition(hd, details=False): """Parse string into angular position. A string containing 2 or 6 numbers is parsed, and the numbers are converted into decimal numbers. In the former case the numbers are assumed to be floats. In the latter case, the numbers are assumed to be sexagesimal. Par...
[ "def", "pposition", "(", "hd", ",", "details", "=", "False", ")", ":", "# :TODO: split two angles based on user entered separator and process each part separately.", "# Split at any character other than a digit, \".\", \"-\", and \"+\".", "p", "=", "re", ".", "split", "(", "r\"[^...
28.876289
0.00069
def get_command(self, command): """Helper function for osx - return gnu utils rather than default for eg head and md5sum where possible and needed. """ shutit_global.shutit_global_object.yield_to_draw() if command in ('md5sum','sed','head'): if self.get_current_shutit_pexpect_session_environment().distr...
[ "def", "get_command", "(", "self", ",", "command", ")", ":", "shutit_global", ".", "shutit_global_object", ".", "yield_to_draw", "(", ")", "if", "command", "in", "(", "'md5sum'", ",", "'sed'", ",", "'head'", ")", ":", "if", "self", ".", "get_current_shutit_p...
40.555556
0.034853
def _normalizeImpurityMatrix(matrix): """Normalize each row of the matrix that the sum of the row equals 1. :params matrix: a matrix (2d nested list) containing numbers, each isobaric channel must be present as a row. :returns: a matrix containing normalized values """ newMatrix = list() ...
[ "def", "_normalizeImpurityMatrix", "(", "matrix", ")", ":", "newMatrix", "=", "list", "(", ")", "for", "line", "in", "matrix", ":", "total", "=", "sum", "(", "line", ")", "if", "total", "!=", "0", ":", "newMatrix", ".", "append", "(", "[", "i", "/", ...
33.466667
0.001938
def select_right(self): """move cursor right""" r, c = self._index self._select_index(r, c+1)
[ "def", "select_right", "(", "self", ")", ":", "r", ",", "c", "=", "self", ".", "_index", "self", ".", "_select_index", "(", "r", ",", "c", "+", "1", ")" ]
28.5
0.017094
def _get_variable_value(defined_variables, name): """ Call the function provided on the defined_variables object with the given name (raise exception if that doesn't exist) and casts it to the specified type. Returns an instance of operators.BaseType """ def fallback(*args, **kwargs): r...
[ "def", "_get_variable_value", "(", "defined_variables", ",", "name", ")", ":", "def", "fallback", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "raise", "AssertionError", "(", "\"Variable {0} is not defined in class {1}\"", ".", "format", "(", "name", ","...
42.153846
0.001786
def _parse_docstring(fh): """Parse the docstrings of a script to find marked dependencies.""" find_fades = re.compile(r'\b(fades)\b:').search for line in fh: if line.startswith("'"): quote = "'" break if line.startswith('"'): quote = '"' break...
[ "def", "_parse_docstring", "(", "fh", ")", ":", "find_fades", "=", "re", ".", "compile", "(", "r'\\b(fades)\\b:'", ")", ".", "search", "for", "line", "in", "fh", ":", "if", "line", ".", "startswith", "(", "\"'\"", ")", ":", "quote", "=", "\"'\"", "brea...
26
0.000976
def segment_curvature(self, t, use_inf=False): """returns the curvature of the segment at t. Notes ----- If you receive a RuntimeWarning, run command >>> old = np.seterr(invalid='raise') This can be undone with >>> np.seterr(**old) """ dz = self.derivative(t) ddz = self.derivat...
[ "def", "segment_curvature", "(", "self", ",", "t", ",", "use_inf", "=", "False", ")", ":", "dz", "=", "self", ".", "derivative", "(", "t", ")", "ddz", "=", "self", ".", "derivative", "(", "t", ",", "n", "=", "2", ")", "dx", ",", "dy", "=", "dz"...
30.147059
0.000945
def MAFFT(sequences, gap_open=1.53, gap_extension=0.0, retree=2): '''A Coral wrapper for the MAFFT command line multiple sequence aligner. :param sequences: A list of sequences to align. :type sequences: List of homogeneous sequences (all DNA, or all RNA, etc.) :param gap_open: --o...
[ "def", "MAFFT", "(", "sequences", ",", "gap_open", "=", "1.53", ",", "gap_extension", "=", "0.0", ",", "retree", "=", "2", ")", ":", "arguments", "=", "[", "'mafft'", "]", "arguments", "+=", "[", "'--op'", ",", "str", "(", "gap_open", ")", "]", "argu...
36.212766
0.000572
def cmpToDataStore_uri(base, ds1, ds2): '''Bases the comparison of the datastores on URI alone.''' ret = difflib.get_close_matches(base.uri, [ds1.uri, ds2.uri], 1, cutoff=0.5) if len(ret) <= 0: return 0 if ret[0] == ds1.uri: return -1 return 1
[ "def", "cmpToDataStore_uri", "(", "base", ",", "ds1", ",", "ds2", ")", ":", "ret", "=", "difflib", ".", "get_close_matches", "(", "base", ".", "uri", ",", "[", "ds1", ".", "uri", ",", "ds2", ".", "uri", "]", ",", "1", ",", "cutoff", "=", "0.5", "...
31.75
0.022989
def get_pydoc_completions(modulename): """Get possible completions for modulename for pydoc. Returns a list of possible values to be passed to pydoc. """ modulename = compat.ensure_not_unicode(modulename) modulename = modulename.rstrip(".") if modulename == "": return sorted(get_module...
[ "def", "get_pydoc_completions", "(", "modulename", ")", ":", "modulename", "=", "compat", ".", "ensure_not_unicode", "(", "modulename", ")", "modulename", "=", "modulename", ".", "rstrip", "(", "\".\"", ")", "if", "modulename", "==", "\"\"", ":", "return", "so...
33.238095
0.001393
def get_condition(self, service_id, version_number, name): """Gets a specified condition.""" content = self._fetch("/service/%s/version/%d/condition/%s" % (service_id, version_number, name)) return FastlyCondition(self, content)
[ "def", "get_condition", "(", "self", ",", "service_id", ",", "version_number", ",", "name", ")", ":", "content", "=", "self", ".", "_fetch", "(", "\"/service/%s/version/%d/condition/%s\"", "%", "(", "service_id", ",", "version_number", ",", "name", ")", ")", "...
57.75
0.025641
def Rank(a): """ Rank op. """ return np.array([len(a.shape)], dtype=np.int32),
[ "def", "Rank", "(", "a", ")", ":", "return", "np", ".", "array", "(", "[", "len", "(", "a", ".", "shape", ")", "]", ",", "dtype", "=", "np", ".", "int32", ")", "," ]
18
0.010638
def process_connection(connection, my_socket): """Handle I/O and Timers on a single Connection.""" if connection.closed: return False work = False readfd = [] writefd = [] if connection.needs_input > 0: readfd = [my_socket] work = True if connection.has_output > 0: ...
[ "def", "process_connection", "(", "connection", ",", "my_socket", ")", ":", "if", "connection", ".", "closed", ":", "return", "False", "work", "=", "False", "readfd", "=", "[", "]", "writefd", "=", "[", "]", "if", "connection", ".", "needs_input", ">", "...
29.489796
0.00067
def take(list_, index_list): """ Selects a subset of a list based on a list of indices. This is similar to np.take, but pure python. Args: list_ (list): some indexable object index_list (list, slice, int): some indexing object Returns: list or scalar: subset of the list ...
[ "def", "take", "(", "list_", ",", "index_list", ")", ":", "try", ":", "return", "[", "list_", "[", "index", "]", "for", "index", "in", "index_list", "]", "except", "TypeError", ":", "return", "list_", "[", "index_list", "]" ]
24.365385
0.000759
def download_as_file(fn, data=None): """ Download given `data` as file `fn`. This service exists to allow frontend present user with downloadable files. """ if data is None: raise HTTPError(500, "This service require POST `data` parameter.") response.set_header("Content-Type", "applicat...
[ "def", "download_as_file", "(", "fn", ",", "data", "=", "None", ")", ":", "if", "data", "is", "None", ":", "raise", "HTTPError", "(", "500", ",", "\"This service require POST `data` parameter.\"", ")", "response", ".", "set_header", "(", "\"Content-Type\"", ",",...
30.266667
0.002137
def _EncodeUnknownFields(message): """Remap unknown fields in message out of message.source.""" source = _UNRECOGNIZED_FIELD_MAPPINGS.get(type(message)) if source is None: return message # CopyProtoMessage uses _ProtoJsonApiTools, which uses this message. Use # the vanilla protojson-based co...
[ "def", "_EncodeUnknownFields", "(", "message", ")", ":", "source", "=", "_UNRECOGNIZED_FIELD_MAPPINGS", ".", "get", "(", "type", "(", "message", ")", ")", "if", "source", "is", "None", ":", "return", "message", "# CopyProtoMessage uses _ProtoJsonApiTools, which uses t...
46.772727
0.000952
def process_from_file(signor_data_file, signor_complexes_file=None): """Process Signor interaction data from CSV files. Parameters ---------- signor_data_file : str Path to the Signor interaction data file in CSV format. signor_complexes_file : str Path to the Signor complexes data ...
[ "def", "process_from_file", "(", "signor_data_file", ",", "signor_complexes_file", "=", "None", ")", ":", "# Get generator over the CSV file", "data_iter", "=", "read_unicode_csv", "(", "signor_data_file", ",", "delimiter", "=", "';'", ",", "skiprows", "=", "1", ")", ...
41.538462
0.000905
def lowstate_file_refs(chunks, extras=''): ''' Create a list of file ref objects to reconcile ''' refs = {} for chunk in chunks: if not isinstance(chunk, dict): continue saltenv = 'base' crefs = [] for state in chunk: if state == '__env__': ...
[ "def", "lowstate_file_refs", "(", "chunks", ",", "extras", "=", "''", ")", ":", "refs", "=", "{", "}", "for", "chunk", "in", "chunks", ":", "if", "not", "isinstance", "(", "chunk", ",", "dict", ")", ":", "continue", "saltenv", "=", "'base'", "crefs", ...
28.407407
0.001261
def ADDMOD(self, a, b, c): """Modulo addition operation""" try: result = Operators.ITEBV(256, c == 0, 0, (a + b) % c) except ZeroDivisionError: result = 0 return result
[ "def", "ADDMOD", "(", "self", ",", "a", ",", "b", ",", "c", ")", ":", "try", ":", "result", "=", "Operators", ".", "ITEBV", "(", "256", ",", "c", "==", "0", ",", "0", ",", "(", "a", "+", "b", ")", "%", "c", ")", "except", "ZeroDivisionError",...
31.142857
0.008929
def _process_dataset(name, directory, num_shards, labels_file): """Process a complete data set and save it as a TFRecord. Args: name: string, unique identifier specifying the data set. directory: string, root path to the data set. num_shards: integer number of shards for this data set. labels_file:...
[ "def", "_process_dataset", "(", "name", ",", "directory", ",", "num_shards", ",", "labels_file", ")", ":", "filenames", ",", "texts", ",", "labels", "=", "_find_image_files", "(", "directory", ",", "labels_file", ")", "_process_image_files", "(", "name", ",", ...
44.272727
0.008048
def add_provide(self, provide): """ Add a provide object if it does not already exist """ for p in self.provides: if p.value == provide.value: return self.provides.append(provide)
[ "def", "add_provide", "(", "self", ",", "provide", ")", ":", "for", "p", "in", "self", ".", "provides", ":", "if", "p", ".", "value", "==", "provide", ".", "value", ":", "return", "self", ".", "provides", ".", "append", "(", "provide", ")" ]
37.666667
0.008658
def _parseHeader (self, line, lineno, log): """Parses a sequence header line containing 'name: value' pairs.""" if line.startswith('#') and line.find(':') > 0: tokens = [ t.strip().lower() for t in line[1:].split(":", 1) ] name = tokens[0] pos = SeqPos(line, lineno) if name in self...
[ "def", "_parseHeader", "(", "self", ",", "line", ",", "lineno", ",", "log", ")", ":", "if", "line", ".", "startswith", "(", "'#'", ")", "and", "line", ".", "find", "(", "':'", ")", ">", "0", ":", "tokens", "=", "[", "t", ".", "strip", "(", ")",...
39.526316
0.019506
def get_grp2codes(self): """Get dict of group name to namedtuples.""" grp2codes = cx.defaultdict(set) for code, ntd in self.code2nt.items(): grp2codes[ntd.group].add(code) return dict(grp2codes)
[ "def", "get_grp2codes", "(", "self", ")", ":", "grp2codes", "=", "cx", ".", "defaultdict", "(", "set", ")", "for", "code", ",", "ntd", "in", "self", ".", "code2nt", ".", "items", "(", ")", ":", "grp2codes", "[", "ntd", ".", "group", "]", ".", "add"...
38.833333
0.008403
def add_bollinger_bands(self,periods=20,boll_std=2,fill=True,column=None,name='', str='{name}({column},{period})',**kwargs): """ Add Bollinger Bands (BOLL) study to QuantFigure.studies Parameters: periods : int or list(int) Number of periods boll_std : int Number of standard deviations for...
[ "def", "add_bollinger_bands", "(", "self", ",", "periods", "=", "20", ",", "boll_std", "=", "2", ",", "fill", "=", "True", ",", "column", "=", "None", ",", "name", "=", "''", ",", "str", "=", "'{name}({column},{period})'", ",", "*", "*", "kwargs", ")",...
29.304348
0.059584
def from_analysis_period(cls, analysis_period, tau_b, tau_d, daylight_savings_indicator='No'): """"Initialize a RevisedClearSkyCondition from an analysis_period""" _check_analysis_period(analysis_period) return cls(analysis_period.st_month, analysis_period.st_day, ta...
[ "def", "from_analysis_period", "(", "cls", ",", "analysis_period", ",", "tau_b", ",", "tau_d", ",", "daylight_savings_indicator", "=", "'No'", ")", ":", "_check_analysis_period", "(", "analysis_period", ")", "return", "cls", "(", "analysis_period", ".", "st_month", ...
62.166667
0.010582
def init_defaults(self): """Initializes important headers to default values, if not already specified. The WARC-Record-ID header is set to a newly generated UUID. The WARC-Date header is set to the current datetime. The Content-Type is set based on the WARC-Type header. ...
[ "def", "init_defaults", "(", "self", ")", ":", "if", "\"WARC-Record-ID\"", "not", "in", "self", ":", "self", "[", "'WARC-Record-ID'", "]", "=", "\"<urn:uuid:%s>\"", "%", "uuid", ".", "uuid1", "(", ")", "if", "\"WARC-Date\"", "not", "in", "self", ":", "self...
52.5
0.008021
def branches(self): """ #TODO: description """ for branch in self._grid.graph_edges(): if branch['branch'].ring == self: yield branch
[ "def", "branches", "(", "self", ")", ":", "for", "branch", "in", "self", ".", "_grid", ".", "graph_edges", "(", ")", ":", "if", "branch", "[", "'branch'", "]", ".", "ring", "==", "self", ":", "yield", "branch" ]
30
0.010811
def build_job(name=None, parameters=None): ''' Initiate a build for the provided job. :param name: The name of the job is check if it exists. :param parameters: Parameters to send to the job. :return: True is successful, otherwise raise an exception. CLI Example: .. code-block:: bash ...
[ "def", "build_job", "(", "name", "=", "None", ",", "parameters", "=", "None", ")", ":", "if", "not", "name", ":", "raise", "SaltInvocationError", "(", "'Required parameter \\'name\\' is missing'", ")", "server", "=", "_connect", "(", ")", "if", "not", "job_exi...
26.766667
0.001202
def sca_intensity(scatterer, h_pol=True): """Scattering intensity (phase function) for the current setup. Args: scatterer: a Scatterer instance. h_pol: If True (default), use horizontal polarization. If False, use vertical polarization. Returns: The differential scatter...
[ "def", "sca_intensity", "(", "scatterer", ",", "h_pol", "=", "True", ")", ":", "Z", "=", "scatterer", ".", "get_Z", "(", ")", "return", "(", "Z", "[", "0", ",", "0", "]", "-", "Z", "[", "0", ",", "1", "]", ")", "if", "h_pol", "else", "(", "Z"...
32.384615
0.013857
def _instantiate_target(self, target_adaptor): """Given a TargetAdaptor struct previously parsed from a BUILD file, instantiate a Target.""" target_cls = self._target_types[target_adaptor.type_alias] try: # Pop dependencies, which were already consumed during construction. kwargs = target_adapto...
[ "def", "_instantiate_target", "(", "self", ",", "target_adaptor", ")", ":", "target_cls", "=", "self", ".", "_target_types", "[", "target_adaptor", ".", "type_alias", "]", "try", ":", "# Pop dependencies, which were already consumed during construction.", "kwargs", "=", ...
42.2
0.013905
def nnz_obs_names(self): """ wrapper around pyemu.Pst.nnz_obs_names for listing non-zero observation names Returns ------- nnz_obs_names : list pyemu.Pst.nnz_obs_names """ if self.__pst is not None: return self.pst.nnz_obs_names ...
[ "def", "nnz_obs_names", "(", "self", ")", ":", "if", "self", ".", "__pst", "is", "not", "None", ":", "return", "self", ".", "pst", ".", "nnz_obs_names", "else", ":", "return", "self", ".", "jco", ".", "obs_names" ]
25.5
0.008108
def _pre_request(self, url, method = u"get", data = None, headers=None, **kwargs): """ hook for manipulating the _pre request data """ return (url, method, data, headers, kwargs)
[ "def", "_pre_request", "(", "self", ",", "url", ",", "method", "=", "u\"get\"", ",", "data", "=", "None", ",", "headers", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "(", "url", ",", "method", ",", "data", ",", "headers", ",", "kwargs...
41.2
0.033333
def _gpdfit(x): """Estimate the parameters for the Generalized Pareto Distribution (GPD). Empirical Bayes estimate for the parameters of the generalized Pareto distribution given the data. Parameters ---------- x : array sorted 1D data array Returns ------- k : float ...
[ "def", "_gpdfit", "(", "x", ")", ":", "prior_bs", "=", "3", "prior_k", "=", "10", "len_x", "=", "len", "(", "x", ")", "m_est", "=", "30", "+", "int", "(", "len_x", "**", "0.5", ")", "b_ary", "=", "1", "-", "np", ".", "sqrt", "(", "m_est", "/"...
28.958333
0.002088
def get_conn(self): """Returns a Google Cloud Dataproc service object.""" http_authorized = self._authorize() return build( 'dataproc', self.api_version, http=http_authorized, cache_discovery=False)
[ "def", "get_conn", "(", "self", ")", ":", "http_authorized", "=", "self", ".", "_authorize", "(", ")", "return", "build", "(", "'dataproc'", ",", "self", ".", "api_version", ",", "http", "=", "http_authorized", ",", "cache_discovery", "=", "False", ")" ]
40.166667
0.00813
def create_logger(name, formatter=None, handler=None, level=None): """ Returns a new logger for the specified name. """ logger = logging.getLogger(name) #: remove existing handlers logger.handlers = [] #: use a standard out handler if handler is None: handler = logging.StreamHa...
[ "def", "create_logger", "(", "name", ",", "formatter", "=", "None", ",", "handler", "=", "None", ",", "level", "=", "None", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", "name", ")", "#: remove existing handlers", "logger", ".", "handlers", "=...
25.64
0.001504
def get_row_by_fsid(self, fs_id): '''确认在Liststore中是否存在这条任务. 如果存在, 返回TreeModelRow, 否则就返回None''' for row in self.liststore: if row[FSID_COL] == fs_id: return row return None
[ "def", "get_row_by_fsid", "(", "self", ",", "fs_id", ")", ":", "for", "row", "in", "self", ".", "liststore", ":", "if", "row", "[", "FSID_COL", "]", "==", "fs_id", ":", "return", "row", "return", "None" ]
32.142857
0.008658
def register_preprocessed_file(self, infile, pmid, extra_annotations): """Set up already preprocessed text file for reading with ISI reader. This is essentially a mock function to "register" already preprocessed files and get an IsiPreprocessor object that can be passed to the IsiProces...
[ "def", "register_preprocessed_file", "(", "self", ",", "infile", ",", "pmid", ",", "extra_annotations", ")", ":", "infile_base", "=", "os", ".", "path", ".", "basename", "(", "infile", ")", "outfile", "=", "os", ".", "path", ".", "join", "(", "self", "."...
40.444444
0.001789
def serialize_to_xml(root, block): """ Serialize the Peer Instruction XBlock's content to XML. Args: block (PeerInstructionXBlock): The peer instruction block to serialize. root (etree.Element): The XML root node to update. Returns: etree.Element """ root.tag = 'ubcpi'...
[ "def", "serialize_to_xml", "(", "root", ",", "block", ")", ":", "root", ".", "tag", "=", "'ubcpi'", "if", "block", ".", "rationale_size", "is", "not", "None", ":", "if", "block", ".", "rationale_size", ".", "get", "(", "'min'", ")", ":", "root", ".", ...
33.153846
0.002254
def make_name(super_name, default_super_name, sub_name): """Helper which makes a `str` name; useful for tf.compat.v1.name_scope.""" name = super_name if super_name is not None else default_super_name if sub_name is not None: name += '_' + sub_name return name
[ "def", "make_name", "(", "super_name", ",", "default_super_name", ",", "sub_name", ")", ":", "name", "=", "super_name", "if", "super_name", "is", "not", "None", "else", "default_super_name", "if", "sub_name", "is", "not", "None", ":", "name", "+=", "'_'", "+...
44.333333
0.01845
def getCenter(self): """ Return the ``Location`` of the center of this region """ return Location(self.x+(self.w/2), self.y+(self.h/2))
[ "def", "getCenter", "(", "self", ")", ":", "return", "Location", "(", "self", ".", "x", "+", "(", "self", ".", "w", "/", "2", ")", ",", "self", ".", "y", "+", "(", "self", ".", "h", "/", "2", ")", ")" ]
49.666667
0.013245
def decode(token, certs=None, verify=True, audience=None): """Decode and verify a JWT. Args: token (str): The encoded JWT. certs (Union[str, bytes, Mapping[str, Union[str, bytes]]]): The certificate used to validate the JWT signature. If bytes or string, it must the the ...
[ "def", "decode", "(", "token", ",", "certs", "=", "None", ",", "verify", "=", "True", ",", "audience", "=", "None", ")", ":", "header", ",", "payload", ",", "signed_section", ",", "signature", "=", "_unverified_decode", "(", "token", ")", "if", "not", ...
38.896552
0.000432
def logscale(x_min, x_max, n): """ :param x_min: minumum value :param x_max: maximum value :param n: number of steps :returns: an array of n values from x_min to x_max """ if not (isinstance(n, int) and n > 0): raise ValueError('n must be a positive integer, got %s' % n) if x_min...
[ "def", "logscale", "(", "x_min", ",", "x_max", ",", "n", ")", ":", "if", "not", "(", "isinstance", "(", "n", ",", "int", ")", "and", "n", ">", "0", ")", ":", "raise", "ValueError", "(", "'n must be a positive integer, got %s'", "%", "n", ")", "if", "...
38.375
0.00159
def _outer_error_is_decreasing(self): """True if outer iteration error is decreasing.""" is_decreasing, self._last_outer_error = self._error_is_decreasing(self._last_outer_error) return is_decreasing
[ "def", "_outer_error_is_decreasing", "(", "self", ")", ":", "is_decreasing", ",", "self", ".", "_last_outer_error", "=", "self", ".", "_error_is_decreasing", "(", "self", ".", "_last_outer_error", ")", "return", "is_decreasing" ]
55
0.013453
def _getshapes_2d(center, max_radius, shape): """Calculate indices and slices for the bounding box of a disk.""" index_mean = shape * center index_radius = max_radius / 2.0 * np.array(shape) # Avoid negative indices min_idx = np.maximum(np.floor(index_mean - index_radius), 0).astype(int) max_id...
[ "def", "_getshapes_2d", "(", "center", ",", "max_radius", ",", "shape", ")", ":", "index_mean", "=", "shape", "*", "center", "index_radius", "=", "max_radius", "/", "2.0", "*", "np", ".", "array", "(", "shape", ")", "# Avoid negative indices", "min_idx", "="...
45
0.001815
def _get_queue_for_the_action(self, action): """Find action queue for the action depending on the module. The id is found with action modulo on action id :param a: the action that need action queue to be assigned :type action: object :return: worker id and queue. (0, None) if no...
[ "def", "_get_queue_for_the_action", "(", "self", ",", "action", ")", ":", "# get the module name, if not, take fork", "mod", "=", "getattr", "(", "action", ",", "'module_type'", ",", "'fork'", ")", "queues", "=", "list", "(", "self", ".", "q_by_mod", "[", "mod",...
38
0.002139
def dict_from_cookiejar(cj): """Returns a key/value dictionary from a CookieJar. :param cj: CookieJar object to extract cookies from. """ cookie_dict = {} for _, cookies in cj._cookies.items(): for _, cookies in cookies.items(): for cookie in cookies.values(): ...
[ "def", "dict_from_cookiejar", "(", "cj", ")", ":", "cookie_dict", "=", "{", "}", "for", "_", ",", "cookies", "in", "cj", ".", "_cookies", ".", "items", "(", ")", ":", "for", "_", ",", "cookies", "in", "cookies", ".", "items", "(", ")", ":", "for", ...
26.666667
0.002415
def rgb(red, green, blue, content): """ Colors a content using rgb for h :param red: [0-5] :type red: int :param green: [0-5] :type green: int :param blue: [0-5] :type blue: int :param content: Whatever you want to say... :type content: unicode :return: ansi string :rtype: un...
[ "def", "rgb", "(", "red", ",", "green", ",", "blue", ",", "content", ")", ":", "color", "=", "16", "+", "36", "*", "red", "+", "6", "*", "green", "+", "blue", "return", "encode", "(", "'38;5;'", "+", "str", "(", "color", ")", ")", "+", "content...
28.8
0.002242
def get_polygons(self, by_spec=False, depth=None): """ Returns a list of polygons in this cell. Parameters ---------- by_spec : bool If ``True``, the return value is a dictionary with the polygons of each individual pair (layer, datatype). depth :...
[ "def", "get_polygons", "(", "self", ",", "by_spec", "=", "False", ",", "depth", "=", "None", ")", ":", "if", "depth", "is", "not", "None", "and", "depth", "<", "0", ":", "bb", "=", "self", ".", "get_bounding_box", "(", ")", "if", "bb", "is", "None"...
43.625
0.000701
def assemble(self): """Assemble a QasmQobjInstruction""" instruction = super().assemble() if self.label: instruction.label = self.label return instruction
[ "def", "assemble", "(", "self", ")", ":", "instruction", "=", "super", "(", ")", ".", "assemble", "(", ")", "if", "self", ".", "label", ":", "instruction", ".", "label", "=", "self", ".", "label", "return", "instruction" ]
32.166667
0.010101
def longest_monotonic_subseq_length(xs): '''Return the length of the longest monotonic subsequence of xs, second return value is the difference between increasing and decreasing lengths. >>> longest_monotonic_subseq_length((4, 5, 1, 2, 3)) (3, 1) >>> longest_monotonic_subseq_length((1, 2, 3, 5, 4))...
[ "def", "longest_monotonic_subseq_length", "(", "xs", ")", ":", "li", "=", "longest_increasing_subseq_length", "(", "xs", ")", "ld", "=", "longest_decreasing_subseq_length", "(", "xs", ")", "return", "max", "(", "li", ",", "ld", ")", ",", "li", "-", "ld" ]
36.571429
0.001905
def docker_to_uuid(uuid): ''' Get the image uuid from an imported docker image .. versionadded:: 2019.2.0 ''' if _is_uuid(uuid): return uuid if _is_docker_uuid(uuid): images = list_installed(verbose=True) for image_uuid in images: if 'name' not in images[imag...
[ "def", "docker_to_uuid", "(", "uuid", ")", ":", "if", "_is_uuid", "(", "uuid", ")", ":", "return", "uuid", "if", "_is_docker_uuid", "(", "uuid", ")", ":", "images", "=", "list_installed", "(", "verbose", "=", "True", ")", "for", "image_uuid", "in", "imag...
27.4375
0.002203
def tplot_options(option, value): """ This function allows the user to set several global options for the generated plots. Parameters: option : str The name of the option. See section below value : str/int/float/list The value of the option. See section bel...
[ "def", "tplot_options", "(", "option", ",", "value", ")", ":", "option", "=", "option", ".", "lower", "(", ")", "temp", "=", "tplot_utilities", ".", "set_tplot_options", "(", "option", ",", "value", ",", "pytplot", ".", "tplot_opt_glob", ")", "pytplot", "....
40.12
0.015085
def stripe_to_db(self, data): """Convert the raw timestamp value to a DateTime representation.""" val = data.get(self.name) # Note: 0 is a possible return value, which is 'falseish' if val is not None: return convert_tstamp(val)
[ "def", "stripe_to_db", "(", "self", ",", "data", ")", ":", "val", "=", "data", ".", "get", "(", "self", ".", "name", ")", "# Note: 0 is a possible return value, which is 'falseish'", "if", "val", "is", "not", "None", ":", "return", "convert_tstamp", "(", "val"...
33.428571
0.029167
def update_limits(self, change_source_lower_limit=None, change_source_upper_limit=None): """ updates the limits (lower and upper) of the update manager instance :param change_source_lower_limit: [[i_model, ['param_name', ...], [value1, value2, ...]]] :return: updates internal state of l...
[ "def", "update_limits", "(", "self", ",", "change_source_lower_limit", "=", "None", ",", "change_source_upper_limit", "=", "None", ")", ":", "if", "not", "change_source_lower_limit", "is", "None", ":", "self", ".", "_source_lower", "=", "self", ".", "_update_limit...
60.454545
0.013333
def validate_capacity(capacity): """Validate ScalingConfiguration capacity for serverless DBCluster""" if capacity not in VALID_SCALING_CONFIGURATION_CAPACITIES: raise ValueError( "ScalingConfiguration capacity must be one of: {}".format( ", ".join(map( s...
[ "def", "validate_capacity", "(", "capacity", ")", ":", "if", "capacity", "not", "in", "VALID_SCALING_CONFIGURATION_CAPACITIES", ":", "raise", "ValueError", "(", "\"ScalingConfiguration capacity must be one of: {}\"", ".", "format", "(", "\", \"", ".", "join", "(", "map"...
33.307692
0.002247
def project_status(): """...""" r = Response() try: project = cauldron.project.get_internal_project() if project: r.update(project=project.status()) else: r.update(project=None) except Exception as err: r.fail( code='PROJECT_STATUS_ERR...
[ "def", "project_status", "(", ")", ":", "r", "=", "Response", "(", ")", "try", ":", "project", "=", "cauldron", ".", "project", ".", "get_internal_project", "(", ")", "if", "project", ":", "r", ".", "update", "(", "project", "=", "project", ".", "statu...
26.631579
0.001908
def addai(argname, condition=None): r""" Add an "AI" exception in the global exception handler. An "AI" exception is of the type :code:`RuntimeError('Argument \`*[argname]*\` is not valid')` where :code:`*[argname]*` is the value of the **argname** argument :param argname: Argument name :t...
[ "def", "addai", "(", "argname", ",", "condition", "=", "None", ")", ":", "# pylint: disable=C0123", "if", "not", "isinstance", "(", "argname", ",", "str", ")", ":", "raise", "RuntimeError", "(", "\"Argument `argname` is not valid\"", ")", "if", "(", "condition",...
37
0.001756
def spawn(func, *args, **kwargs): """Create a task to run ``func(*args, **kwargs)``. Returns a :class:`Task` objec. Execution control returns immediately to the caller; the created task is merely scheduled to be run at the next available opportunity. Use :func:`spawn_later` to arrange for tasks t...
[ "def", "spawn", "(", "func", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "t", "=", "Task", "(", "target", "=", "func", ",", "args", "=", "args", ",", "kwargs", "=", "kwargs", ")", "t", ".", "start", "(", ")", "return", "t" ]
36.166667
0.002247
def get_overlapping_ranges(self, collection_link, partition_key_ranges): ''' Given a partition key range and a collection, returns the list of overlapping partition key ranges :param str collection_link: The name of the collection. :param list partition_key_...
[ "def", "get_overlapping_ranges", "(", "self", ",", "collection_link", ",", "partition_key_ranges", ")", ":", "cl", "=", "self", ".", "_documentClient", "collection_id", "=", "base", ".", "GetResourceIdOrFullNameFromLink", "(", "collection_link", ")", "collection_routing...
54.321429
0.011628
def list_config_map_for_all_namespaces(self, **kwargs): """ list or watch objects of kind ConfigMap This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.list_config_map_for_all_namespaces(async_...
[ "def", "list_config_map_for_all_namespaces", "(", "self", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async_req'", ")", ":", "return", "self", ".", "list_config_map_for_all_na...
168.777778
0.0024
def protocols(self): """ :rtype: dict[int, list of ProtocolAnalyzer] """ if self.__protocols is None: self.__protocols = self.proto_tree_model.protocols return self.__protocols
[ "def", "protocols", "(", "self", ")", ":", "if", "self", ".", "__protocols", "is", "None", ":", "self", ".", "__protocols", "=", "self", ".", "proto_tree_model", ".", "protocols", "return", "self", ".", "__protocols" ]
31.714286
0.008772
def local_manager_gid(self): """Group id of local manager group of current authenticated member. Currently a user can be assigned only to one local manager group. If more than one local manager group is configured, an error is raised. """ config = self.root['settings']['ugm_loca...
[ "def", "local_manager_gid", "(", "self", ")", ":", "config", "=", "self", ".", "root", "[", "'settings'", "]", "[", "'ugm_localmanager'", "]", ".", "attrs", "user", "=", "security", ".", "authenticated_user", "(", "get_current_request", "(", ")", ")", "if", ...
41.461538
0.001813
def layout(self): """Call to have the view layout itself. Subclasses should invoke this after laying out child views and/or updating its own frame. """ if self.shadowed: shadow_size = theme.current.shadow_size shadowed_frame_size = (self.frame.w + shadow_...
[ "def", "layout", "(", "self", ")", ":", "if", "self", ".", "shadowed", ":", "shadow_size", "=", "theme", ".", "current", ".", "shadow_size", "shadowed_frame_size", "=", "(", "self", ".", "frame", ".", "w", "+", "shadow_size", ",", "self", ".", "frame", ...
44.444444
0.002448
def ui_label(self): """UI string identifying the partition if possible.""" return ': '.join(filter(None, [ self.ui_device_presentation, self.ui_id_label or self.ui_id_uuid or self.drive_label ]))
[ "def", "ui_label", "(", "self", ")", ":", "return", "': '", ".", "join", "(", "filter", "(", "None", ",", "[", "self", ".", "ui_device_presentation", ",", "self", ".", "ui_id_label", "or", "self", ".", "ui_id_uuid", "or", "self", ".", "drive_label", "]",...
39.666667
0.00823
def get_value(self, dictionary): """ Given the *incoming* primitive data, return the value for this field that should be validated and transformed to a native value. """ if html.is_html_input(dictionary): # HTML forms will represent empty fields as '', and cannot ...
[ "def", "get_value", "(", "self", ",", "dictionary", ")", ":", "if", "html", ".", "is_html_input", "(", "dictionary", ")", ":", "# HTML forms will represent empty fields as '', and cannot", "# represent None or False values directly.", "if", "self", ".", "field_name", "not...
50.826087
0.001679
def user(name, id='', user='', priv='', password='', status='active'): ''' Ensures that a user is configured on the device. Due to being unable to verify the user password. This is a forced operation. .. versionadded:: 2019.2.0 name: The name of the module function to execute. id(int): The us...
[ "def", "user", "(", "name", ",", "id", "=", "''", ",", "user", "=", "''", ",", "priv", "=", "''", ",", "password", "=", "''", ",", "status", "=", "'active'", ")", ":", "ret", "=", "_default_ret", "(", "name", ")", "user_conf", "=", "__salt__", "[...
26.149254
0.00165
def get_account_tokens(self, address): """ Get the list of tokens that this address owns """ cur = self.db.cursor() return namedb_get_account_tokens(cur, address)
[ "def", "get_account_tokens", "(", "self", ",", "address", ")", ":", "cur", "=", "self", ".", "db", ".", "cursor", "(", ")", "return", "namedb_get_account_tokens", "(", "cur", ",", "address", ")" ]
32.833333
0.009901
def toJSONFilters(actions): """Generate a JSON-to-JSON filter from stdin to stdout The filter: * reads a JSON-formatted pandoc document from stdin * transforms it by walking the tree and performing the actions * returns a new JSON-formatted pandoc document to stdout The argument `actions` is ...
[ "def", "toJSONFilters", "(", "actions", ")", ":", "try", ":", "input_stream", "=", "io", ".", "TextIOWrapper", "(", "sys", ".", "stdin", ".", "buffer", ",", "encoding", "=", "'utf-8'", ")", "except", "AttributeError", ":", "# Python 2 does not have sys.stdin.buf...
34.21875
0.000888
def getCalculationDependencies(self, flat=False, deps=None): """ Recursively calculates all dependencies of this calculation. The return value is dictionary of dictionaries (of dictionaries...) {service_UID1: {service_UID2: {service_UID3: {}, ...
[ "def", "getCalculationDependencies", "(", "self", ",", "flat", "=", "False", ",", "deps", "=", "None", ")", ":", "if", "deps", "is", "None", ":", "deps", "=", "[", "]", "if", "flat", "is", "True", "else", "{", "}", "for", "service", "in", "self", "...
32.846154
0.002275
def _sub16(ins): ''' Pops last 2 words from the stack and subtract them. Then push the result onto the stack. Top of the stack is subtracted Top -1 Optimizations: * If 2nd op is ZERO, then do NOTHING: A - 0 = A * If any of the operands is < 4, then DEC is used * If a...
[ "def", "_sub16", "(", "ins", ")", ":", "op1", ",", "op2", "=", "tuple", "(", "ins", ".", "quad", "[", "2", ":", "4", "]", ")", "if", "is_int", "(", "op2", ")", ":", "op", "=", "int16", "(", "op2", ")", "output", "=", "_16bit_oper", "(", "op1"...
24.117647
0.000781
def connectivity_map(dset,prefix,x,y,z,radius=2): '''Will perform connectivity analysis on ``dset`` using seed point ``(x,y,z)`` (in RAI order) with a sphere of radius ``radius``. Does not perform any preprocessing of ``dset``. This should be already motion corrected, noise-regressed, residualized, etc.''' ...
[ "def", "connectivity_map", "(", "dset", ",", "prefix", ",", "x", ",", "y", ",", "z", ",", "radius", "=", "2", ")", ":", "seed_series", "=", "nl", ".", "sphere_average", "(", "dset", ",", "x", ",", "y", ",", "z", ",", "radius", ")", "with", "tempf...
45.066667
0.02029
def reset(self): """Resets the iterator to the beginning of the data.""" self.curr_idx = 0 random.shuffle(self.idx) for buck in self.data: np.random.shuffle(buck)
[ "def", "reset", "(", "self", ")", ":", "self", ".", "curr_idx", "=", "0", "random", ".", "shuffle", "(", "self", ".", "idx", ")", "for", "buck", "in", "self", ".", "data", ":", "np", ".", "random", ".", "shuffle", "(", "buck", ")" ]
33.5
0.009709
def set_position(self, x, y, speed=None): ''' Move chuck to absolute position in um''' if speed: self._intf.write('MoveChuckSubsite %1.1f %1.1f R Y %d' % (x, y, speed)) else: self._intf.write('MoveChuckSubsite %1.1f %1.1f R Y' % (x, y))
[ "def", "set_position", "(", "self", ",", "x", ",", "y", ",", "speed", "=", "None", ")", ":", "if", "speed", ":", "self", ".", "_intf", ".", "write", "(", "'MoveChuckSubsite %1.1f %1.1f R Y %d'", "%", "(", "x", ",", "y", ",", "speed", ")", ")", "else"...
46.5
0.010563