text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def _margtime_loglr(self, mf_snr, opt_snr): """Returns the log likelihood ratio marginalized over time. """ return special.logsumexp(mf_snr, b=self._deltat) - 0.5*opt_snr
[ "def", "_margtime_loglr", "(", "self", ",", "mf_snr", ",", "opt_snr", ")", ":", "return", "special", ".", "logsumexp", "(", "mf_snr", ",", "b", "=", "self", ".", "_deltat", ")", "-", "0.5", "*", "opt_snr" ]
47.75
8.25
def get_columns_diff(changes): """Add the changed columns as a diff attribute. - changes: a list of changes (get_model_changes query.all()) Return: the same list, to which elements we added a "diff" attribute containing the changed columns. Diff defaults to []. """ for change in changes: ...
[ "def", "get_columns_diff", "(", "changes", ")", ":", "for", "change", "in", "changes", ":", "change", ".", "diff", "=", "[", "]", "elt_changes", "=", "change", ".", "get_changes", "(", ")", "if", "elt_changes", ":", "change", ".", "diff", "=", "elt_chang...
30.533333
18.533333
def _commit(self, session, errorMessage): """ Custom commit function for file objects """ try: session.commit() except IntegrityError: # Raise special error if the commit fails due to empty files log.error('Commit to database failed. %s' % erro...
[ "def", "_commit", "(", "self", ",", "session", ",", "errorMessage", ")", ":", "try", ":", "session", ".", "commit", "(", ")", "except", "IntegrityError", ":", "# Raise special error if the commit fails due to empty files", "log", ".", "error", "(", "'Commit to datab...
32.916667
14.083333
def sort_seeds(uhandle, usort): """ sort seeds from cluster results""" cmd = ["sort", "-k", "2", uhandle, "-o", usort] proc = sps.Popen(cmd, close_fds=True) proc.communicate()
[ "def", "sort_seeds", "(", "uhandle", ",", "usort", ")", ":", "cmd", "=", "[", "\"sort\"", ",", "\"-k\"", ",", "\"2\"", ",", "uhandle", ",", "\"-o\"", ",", "usort", "]", "proc", "=", "sps", ".", "Popen", "(", "cmd", ",", "close_fds", "=", "True", ")...
37.4
7.8
def decrypt(data, _key): """ ACCEPT BYTES -> UTF8 -> JSON -> {"salt":s, "length":l, "data":d} """ # Key and iv have not been generated or provided, bail out if _key is None: Log.error("Expecting a key") _input = get_module("mo_json").json2value(data.decode('utf8'), leaves=False, flexibl...
[ "def", "decrypt", "(", "data", ",", "_key", ")", ":", "# Key and iv have not been generated or provided, bail out", "if", "_key", "is", "None", ":", "Log", ".", "error", "(", "\"Expecting a key\"", ")", "_input", "=", "get_module", "(", "\"mo_json\"", ")", ".", ...
36.076923
19.461538
def create_external_link(self, **kwargs): # noqa: E501 """Create a specific external link # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.create_external_link...
[ "def", "create_external_link", "(", "self", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async_req'", ")", ":", "return", "self", ".", "create_external_link_w...
49.619048
25.952381
def _set_enablePoMode(self, v, load=False): """ Setter method for enablePoMode, mapped from YANG variable /interface/port_channel/openflowPo/enablePoMode (container) If this variable is read-only (config: false) in the source YANG file, then _set_enablePoMode is considered as a private method. Backe...
[ "def", "_set_enablePoMode", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", "v", ",", "b...
81.454545
38.318182
def check_sparsity(x, fraction=0.6): ''' check_sparsity(x) yields either x or an array equivalent to x with a different sparsity based on a heuristic: if x is a sparse array with more than 60% of its elements specified, it is made dense; otherwise, it is left alone. The optional argument fracti...
[ "def", "check_sparsity", "(", "x", ",", "fraction", "=", "0.6", ")", ":", "if", "not", "sps", ".", "issparse", "(", "x", ")", ":", "return", "x", "n", "=", "numel", "(", "x", ")", "if", "n", "==", "0", ":", "return", "x", "if", "len", "(", "x...
41.928571
27.214286
def nvmlDeviceGetBoardId(handle): r""" /** * Retrieves the device boardId from 0-N. * Devices with the same boardId indicate GPUs connected to the same PLX. Use in conjunction with * \ref nvmlDeviceGetMultiGpuBoard() to decide if they are on the same board as well. * The boardId returned ...
[ "def", "nvmlDeviceGetBoardId", "(", "handle", ")", ":", "c_id", "=", "c_uint", "(", ")", "fn", "=", "_nvmlGetFunctionPointer", "(", "\"nvmlDeviceGetBoardId\"", ")", "ret", "=", "fn", "(", "handle", ",", "byref", "(", "c_id", ")", ")", "_nvmlCheckReturn", "("...
54.59375
34.25
def pls(df): """ A simple implementation of a least-squares approach to imputation using partial least squares regression (PLS). :param df: :return: """ if not sklearn: assert('This library depends on scikit-learn (sklearn) to perform PLS-based imputation') df = df.copy() ...
[ "def", "pls", "(", "df", ")", ":", "if", "not", "sklearn", ":", "assert", "(", "'This library depends on scikit-learn (sklearn) to perform PLS-based imputation'", ")", "df", "=", "df", ".", "copy", "(", ")", "df", "[", "np", ".", "isinf", "(", "df", ")", "]"...
27.489796
23.489796
def RangeFromPoint(self, x: int, y: int) -> TextRange: """ Call IUIAutomationTextPattern::RangeFromPoint. child: `Control` or its subclass. Return `TextRange` or None, the degenerate (empty) text range nearest to the specified screen coordinates. Refer https://docs.microsoft.com/...
[ "def", "RangeFromPoint", "(", "self", ",", "x", ":", "int", ",", "y", ":", "int", ")", "->", "TextRange", ":", "textRange", "=", "self", ".", "pattern", ".", "RangeFromPoint", "(", "ctypes", ".", "wintypes", ".", "POINT", "(", "x", ",", "y", ")", "...
57.8
27.4
def mock_django_setup(settings_module, disabled_features=None): """ Must be called *AT IMPORT TIME* to pretend that Django is set up. This is useful for running tests without using the Django test runner. This must be called before any Django models are imported, or they will complain. Call this from a...
[ "def", "mock_django_setup", "(", "settings_module", ",", "disabled_features", "=", "None", ")", ":", "if", "apps", ".", "ready", ":", "# We're running in a real Django unit test, don't do anything.", "return", "if", "'DJANGO_SETTINGS_MODULE'", "not", "in", "os", ".", "e...
48.086957
24.173913
def detectBlackBerry10Phone(self): """Return detection of a Blackberry 10 OS phone Detects if the current browser is a BlackBerry 10 OS phone. Excludes the PlayBook. """ return UAgentInfo.deviceBB10 in self.__userAgent \ and UAgentInfo.mobile in self.__userAgent
[ "def", "detectBlackBerry10Phone", "(", "self", ")", ":", "return", "UAgentInfo", ".", "deviceBB10", "in", "self", ".", "__userAgent", "and", "UAgentInfo", ".", "mobile", "in", "self", ".", "__userAgent" ]
38.5
14.25
def Clean(self): """Clean the build environment.""" # os.unlink doesn't work effectively, use the shell to delete. if os.path.exists(args.build_dir): subprocess.call("rd /s /q %s" % args.build_dir, shell=True) if os.path.exists(args.output_dir): subprocess.call("rd /s /q %s" % args.output_di...
[ "def", "Clean", "(", "self", ")", ":", "# os.unlink doesn't work effectively, use the shell to delete.", "if", "os", ".", "path", ".", "exists", "(", "args", ".", "build_dir", ")", ":", "subprocess", ".", "call", "(", "\"rd /s /q %s\"", "%", "args", ".", "build_...
41.28125
21.40625
def orthonormal_initializer(output_size, input_size, debug=False): """adopted from Timothy Dozat https://github.com/tdozat/Parser/blob/master/lib/linalg.py Parameters ---------- output_size : int input_size : int debug : bool Whether to skip this initializer Returns ------- ...
[ "def", "orthonormal_initializer", "(", "output_size", ",", "input_size", ",", "debug", "=", "False", ")", ":", "print", "(", "(", "output_size", ",", "input_size", ")", ")", "if", "debug", ":", "Q", "=", "np", ".", "random", ".", "randn", "(", "input_siz...
35.857143
20.166667
def _read_fam(self): """Reads the FAM file.""" # Reading the FAM file and setting the values fam = pd.read_csv(self.fam_filename, delim_whitespace=True, names=["fid", "iid", "father", "mother", "gender", "status"], ...
[ "def", "_read_fam", "(", "self", ")", ":", "# Reading the FAM file and setting the values", "fam", "=", "pd", ".", "read_csv", "(", "self", ".", "fam_filename", ",", "delim_whitespace", "=", "True", ",", "names", "=", "[", "\"fid\"", ",", "\"iid\"", ",", "\"fa...
40.941176
20.882353
def allowed_entries(self, capability): """Return list of allowed entries for given capability document. Includes handling of capability = *index where the only acceptable entries are *. """ index = re.match(r'(.+)index$', capability) archive = re.match(r'(.+)\-archive$',...
[ "def", "allowed_entries", "(", "self", ",", "capability", ")", ":", "index", "=", "re", ".", "match", "(", "r'(.+)index$'", ",", "capability", ")", "archive", "=", "re", ".", "match", "(", "r'(.+)\\-archive$'", ",", "capability", ")", "if", "(", "capabilit...
44.863636
15.636364
def get_relation(self, rel_id, resolve_missing=False): """ Get a relation by its ID. :param rel_id: The relation ID :type rel_id: Integer :param resolve_missing: Query the Overpass API if the relation is missing in the result set. :return: The relation :rtype: ov...
[ "def", "get_relation", "(", "self", ",", "rel_id", ",", "resolve_missing", "=", "False", ")", ":", "relations", "=", "self", ".", "get_relations", "(", "rel_id", "=", "rel_id", ")", "if", "len", "(", "relations", ")", "==", "0", ":", "if", "resolve_missi...
38
20.823529
def _iter_all_paths(start, end, rand=False, path=tuple()): """Iterate through all paths from start to end.""" path = path + (start, ) if start is end: yield path else: nodes = [start.lo, start.hi] if rand: # pragma: no cover random.shuffle(nodes) for node in n...
[ "def", "_iter_all_paths", "(", "start", ",", "end", ",", "rand", "=", "False", ",", "path", "=", "tuple", "(", ")", ")", ":", "path", "=", "path", "+", "(", "start", ",", ")", "if", "start", "is", "end", ":", "yield", "path", "else", ":", "nodes"...
34.416667
13.916667
def ground_state_term_symbol(self): """ Ground state term symbol Selected based on Hund's Rule """ L_symbols = 'SPDFGHIKLMNOQRTUVWXYZ' term_symbols = self.term_symbols term_symbol_flat = {term: {"multiplicity": int(term[0]), "L...
[ "def", "ground_state_term_symbol", "(", "self", ")", ":", "L_symbols", "=", "'SPDFGHIKLMNOQRTUVWXYZ'", "term_symbols", "=", "self", ".", "term_symbols", "term_symbol_flat", "=", "{", "term", ":", "{", "\"multiplicity\"", ":", "int", "(", "term", "[", "0", "]", ...
37.78125
16.53125
def piece_at(self, square: Square) -> Optional[Piece]: """Gets the :class:`piece <chess.Piece>` at the given square.""" piece_type = self.piece_type_at(square) if piece_type: mask = BB_SQUARES[square] color = bool(self.occupied_co[WHITE] & mask) return Piece(p...
[ "def", "piece_at", "(", "self", ",", "square", ":", "Square", ")", "->", "Optional", "[", "Piece", "]", ":", "piece_type", "=", "self", ".", "piece_type_at", "(", "square", ")", "if", "piece_type", ":", "mask", "=", "BB_SQUARES", "[", "square", "]", "c...
40.777778
11.666667
def from_native(cls, t): """ Convert from a native Python `datetime.time` value. """ second = (1000000 * t.second + t.microsecond) / 1000000 return Time(t.hour, t.minute, second, t.tzinfo)
[ "def", "from_native", "(", "cls", ",", "t", ")", ":", "second", "=", "(", "1000000", "*", "t", ".", "second", "+", "t", ".", "microsecond", ")", "/", "1000000", "return", "Time", "(", "t", ".", "hour", ",", "t", ".", "minute", ",", "second", ",",...
43.2
10.8
def appropriate_for(self, usage, alg='HS256'): """ Make sure there is a key instance present that can be used for the specified usage. """ try: _use = USE[usage] except: raise ValueError('Unknown key usage') else: if not self.us...
[ "def", "appropriate_for", "(", "self", ",", "usage", ",", "alg", "=", "'HS256'", ")", ":", "try", ":", "_use", "=", "USE", "[", "usage", "]", "except", ":", "raise", "ValueError", "(", "'Unknown key usage'", ")", "else", ":", "if", "not", "self", ".", ...
32.529412
15.823529
def is_true(entity, prop, name): "bool: True if the value of a property is True." return is_not_empty(entity, prop, name) and name in entity._data and bool(getattr(entity, name))
[ "def", "is_true", "(", "entity", ",", "prop", ",", "name", ")", ":", "return", "is_not_empty", "(", "entity", ",", "prop", ",", "name", ")", "and", "name", "in", "entity", ".", "_data", "and", "bool", "(", "getattr", "(", "entity", ",", "name", ")", ...
61.333333
26.666667
def create_kubernetes_role(self, name, bound_service_account_names, bound_service_account_namespaces, ttl="", max_ttl="", period="", policies=None, mount_point='kubernetes'): """POST /auth/<mount_point>/role/:name :param name: Name of the role. :type name: str. ...
[ "def", "create_kubernetes_role", "(", "self", ",", "name", ",", "bound_service_account_names", ",", "bound_service_account_namespaces", ",", "ttl", "=", "\"\"", ",", "max_ttl", "=", "\"\"", ",", "period", "=", "\"\"", ",", "policies", "=", "None", ",", "mount_po...
58.97561
32.463415
def parse_options(s): """ Expects a string in the form "key=val:key2=val2" and returns a dictionary. """ options = {} for option in s.split(':'): if '=' in option: key, val = option.split('=') options[str(key).strip()] = val.strip() return options
[ "def", "parse_options", "(", "s", ")", ":", "options", "=", "{", "}", "for", "option", "in", "s", ".", "split", "(", "':'", ")", ":", "if", "'='", "in", "option", ":", "key", ",", "val", "=", "option", ".", "split", "(", "'='", ")", "options", ...
24.75
15.916667
def _get_args(self): """ Lazily evaluate the args. """ if not hasattr(self, '_args_evaled'): # cache the args in case handler is re-invoked due to flags change self._args_evaled = list(chain.from_iterable(self._args)) return self._args_evaled
[ "def", "_get_args", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'_args_evaled'", ")", ":", "# cache the args in case handler is re-invoked due to flags change", "self", ".", "_args_evaled", "=", "list", "(", "chain", ".", "from_iterable", "(", ...
37.375
13.375
def array_to_image( arr, mask=None, img_format="png", color_map=None, **creation_options ): """ Translate numpy ndarray to image buffer using GDAL. Usage ----- tile, mask = rio_tiler.utils.tile_read(......) with open('test.jpg', 'wb') as f: f.write(array_to_image(tile, mask, img_for...
[ "def", "array_to_image", "(", "arr", ",", "mask", "=", "None", ",", "img_format", "=", "\"png\"", ",", "color_map", "=", "None", ",", "*", "*", "creation_options", ")", ":", "img_format", "=", "img_format", ".", "lower", "(", ")", "if", "len", "(", "ar...
30.753425
21.383562
def _insert(self, query, vars): """ Insert, with return. """ cursor = self.get_db().cursor() self._log(cursor, query, vars) cursor.execute(query, vars) self.get_db().commit() return cursor.fetchone()
[ "def", "_insert", "(", "self", ",", "query", ",", "vars", ")", ":", "cursor", "=", "self", ".", "get_db", "(", ")", ".", "cursor", "(", ")", "self", ".", "_log", "(", "cursor", ",", "query", ",", "vars", ")", "cursor", ".", "execute", "(", "query...
28.333333
5.222222
def slice_by_component( self, component_index, start, end ): """ Return a slice of the alignment, corresponding to an coordinate interval in a specific component. component_index is one of an integer offset into the components list a string indicating the src of the desi...
[ "def", "slice_by_component", "(", "self", ",", "component_index", ",", "start", ",", "end", ")", ":", "if", "type", "(", "component_index", ")", "==", "type", "(", "0", ")", ":", "ref", "=", "self", ".", "components", "[", "component_index", "]", "elif",...
41.48
18.76
def get_external_tools_in_account(self, account_id, params={}): """ Return external tools for the passed canvas account id. https://canvas.instructure.com/doc/api/external_tools.html#method.external_tools.index """ url = ACCOUNTS_API.format(account_id) + "/external_tools" ...
[ "def", "get_external_tools_in_account", "(", "self", ",", "account_id", ",", "params", "=", "{", "}", ")", ":", "url", "=", "ACCOUNTS_API", ".", "format", "(", "account_id", ")", "+", "\"/external_tools\"", "external_tools", "=", "[", "]", "for", "data", "in...
38.916667
21.25
def _space(self, hwr_obj, stroke, kind): """Do the interpolation of 'kind' for 'stroke'""" new_stroke = [] stroke = sorted(stroke, key=lambda p: p['time']) x, y, t = [], [], [] for point in stroke: x.append(point['x']) y.append(point['y']) t....
[ "def", "_space", "(", "self", ",", "hwr_obj", ",", "stroke", ",", "kind", ")", ":", "new_stroke", "=", "[", "]", "stroke", "=", "sorted", "(", "stroke", ",", "key", "=", "lambda", "p", ":", "p", "[", "'time'", "]", ")", "x", ",", "y", ",", "t",...
34.511111
16
def extract_source_geom(dstore, srcidxs): """ Extract the geometry of a given sources Example: http://127.0.0.1:8800/v1/calc/30/extract/source_geom/1,2,3 """ for i in srcidxs.split(','): rec = dstore['source_info'][int(i)] geom = dstore['source_geom'][rec['gidx1']:rec['gidx2']] ...
[ "def", "extract_source_geom", "(", "dstore", ",", "srcidxs", ")", ":", "for", "i", "in", "srcidxs", ".", "split", "(", "','", ")", ":", "rec", "=", "dstore", "[", "'source_info'", "]", "[", "int", "(", "i", ")", "]", "geom", "=", "dstore", "[", "'s...
34.6
9.2
def mode_database_functions(): "Select a function to perform from chill.database" print globals()['mode_database_functions'].__doc__ selection = True database_functions = [ 'init_db', 'insert_node', 'insert_node_node', 'delete_node', 'select_n...
[ "def", "mode_database_functions", "(", ")", ":", "print", "globals", "(", ")", "[", "'mode_database_functions'", "]", ".", "__doc__", "selection", "=", "True", "database_functions", "=", "[", "'init_db'", ",", "'insert_node'", ",", "'insert_node_node'", ",", "'del...
35.8
14.978947
def check_shastore_version(from_store, settings): """ This function gives us the option to emit errors or warnings after sake upgrades """ sprint = settings["sprint"] error = settings["error"] sprint("checking .shastore version for potential incompatibilities", level="verbose") ...
[ "def", "check_shastore_version", "(", "from_store", ",", "settings", ")", ":", "sprint", "=", "settings", "[", "\"sprint\"", "]", "error", "=", "settings", "[", "\"error\"", "]", "sprint", "(", "\"checking .shastore version for potential incompatibilities\"", ",", "le...
39.588235
19.588235
def NewSection(self, token_type, section_name, pre_formatters): """For sections or repeated sections.""" pre_formatters = [self._GetFormatter(f) for f in pre_formatters] # TODO: Consider getting rid of this dispatching, and turn _Do* into methods if token_type == REPEATED_SECTIO...
[ "def", "NewSection", "(", "self", ",", "token_type", ",", "section_name", ",", "pre_formatters", ")", ":", "pre_formatters", "=", "[", "self", ".", "_GetFormatter", "(", "f", ")", "for", "f", "in", "pre_formatters", "]", "# TODO: Consider getting rid of this dispa...
44.777778
18
def get_model(model, ctx, opt): """Model initialization.""" kwargs = {'ctx': ctx, 'pretrained': opt.use_pretrained, 'classes': classes} if model.startswith('resnet'): kwargs['thumbnail'] = opt.use_thumbnail elif model.startswith('vgg'): kwargs['batch_norm'] = opt.batch_norm net = mo...
[ "def", "get_model", "(", "model", ",", "ctx", ",", "opt", ")", ":", "kwargs", "=", "{", "'ctx'", ":", "ctx", ",", "'pretrained'", ":", "opt", ".", "use_pretrained", ",", "'classes'", ":", "classes", "}", "if", "model", ".", "startswith", "(", "'resnet'...
34.055556
13.555556
def repr_assist(obj, remap=None): """Helper function to simplify ``__repr__`` methods. Args: obj: Object to pull argument values for remap (dict): Argument pairs to remap before output Returns: str: Self-documenting representation of ``value`` """ if not remap: rema...
[ "def", "repr_assist", "(", "obj", ",", "remap", "=", "None", ")", ":", "if", "not", "remap", ":", "remap", "=", "{", "}", "data", "=", "[", "]", "for", "arg", "in", "inspect", ".", "getargspec", "(", "getattr", "(", "obj", ".", "__class__", ",", ...
31.793103
17.896552
def _get_pitcher(self, pitcher): """ get pitcher object :param pitcher: Beautifulsoup object(pitcher element) :return: pitcher(dict) """ values = OrderedDict() player = self.players.rosters.get(pitcher.get('id')) values['pos'] = pitcher.get('pos', MlbamCon...
[ "def", "_get_pitcher", "(", "self", ",", "pitcher", ")", ":", "values", "=", "OrderedDict", "(", ")", "player", "=", "self", ".", "players", ".", "rosters", ".", "get", "(", "pitcher", ".", "get", "(", "'id'", ")", ")", "values", "[", "'pos'", "]", ...
40.888889
12.888889
def PopTask(self): """Retrieves and removes the first task from the heap. Returns: Task: the task or None if the heap is empty. """ try: _, task = heapq.heappop(self._heap) except IndexError: return None self._task_identifiers.remove(task.identifier) return task
[ "def", "PopTask", "(", "self", ")", ":", "try", ":", "_", ",", "task", "=", "heapq", ".", "heappop", "(", "self", ".", "_heap", ")", "except", "IndexError", ":", "return", "None", "self", ".", "_task_identifiers", ".", "remove", "(", "task", ".", "id...
22.923077
19.153846
def triangulate(self): """ Convert mesh points to vectors in Cartesian space. :returns: Tuple of four elements, each being 2d numpy array of 3d vectors (the same structure and shape as the mesh itself). Those arrays are: #. points vectors, ...
[ "def", "triangulate", "(", "self", ")", ":", "points", "=", "geo_utils", ".", "spherical_to_cartesian", "(", "self", ".", "lons", ",", "self", ".", "lats", ",", "self", ".", "depths", ")", "# triangulate the mesh by defining vectors of triangles edges:", "# →", "a...
39.064516
22.354839
def forward(self, # pylint: disable=arguments-differ inputs: PackedSequence, initial_state: Optional[Tuple[torch.Tensor, torch.Tensor]] = None) -> \ Tuple[Union[torch.Tensor, PackedSequence], Tuple[torch.Tensor, torch.Tensor]]: """ Parameters --------...
[ "def", "forward", "(", "self", ",", "# pylint: disable=arguments-differ", "inputs", ":", "PackedSequence", ",", "initial_state", ":", "Optional", "[", "Tuple", "[", "torch", ".", "Tensor", ",", "torch", ".", "Tensor", "]", "]", "=", "None", ")", "->", "Tuple...
51.525
26.775
def index_to_rawjson(ix): """ :param ix: dict or IndexInfo object :return: serialized JSON """ if isinstance(ix, N1qlIndex): ix = ix.raw return _to_json(ix)
[ "def", "index_to_rawjson", "(", "ix", ")", ":", "if", "isinstance", "(", "ix", ",", "N1qlIndex", ")", ":", "ix", "=", "ix", ".", "raw", "return", "_to_json", "(", "ix", ")" ]
22.625
9.125
def discard_between( self, min_rank=None, max_rank=None, min_score=None, max_score=None, ): """ Remove members whose ranking is between *min_rank* and *max_rank* OR whose score is between *min_score* and *max_score* (both ranges inclusive). If ...
[ "def", "discard_between", "(", "self", ",", "min_rank", "=", "None", ",", "max_rank", "=", "None", ",", "min_score", "=", "None", ",", "max_score", "=", "None", ",", ")", ":", "no_ranks", "=", "(", "min_rank", "is", "None", ")", "and", "(", "max_rank",...
34.71875
19.09375
def _unpack_episode_title(element: ET.Element): """Unpack EpisodeTitle from title XML element.""" return EpisodeTitle(title=element.text, lang=element.get(f'{XML}lang'))
[ "def", "_unpack_episode_title", "(", "element", ":", "ET", ".", "Element", ")", ":", "return", "EpisodeTitle", "(", "title", "=", "element", ".", "text", ",", "lang", "=", "element", ".", "get", "(", "f'{XML}lang'", ")", ")" ]
49.5
6.25
def log_state(entity, state): """Logs a new state of an entity """ p = {'on': entity, 'state': state} _log(TYPE_CODES.STATE, p)
[ "def", "log_state", "(", "entity", ",", "state", ")", ":", "p", "=", "{", "'on'", ":", "entity", ",", "'state'", ":", "state", "}", "_log", "(", "TYPE_CODES", ".", "STATE", ",", "p", ")" ]
27.8
4.8
def _on_connect(self, sequence, topic, message): """Process a request to connect to an IOTile device A connection message triggers an attempt to connect to a device, any error checking is done by the DeviceManager that is actually managing the devices. A disconnection message i...
[ "def", "_on_connect", "(", "self", ",", "sequence", ",", "topic", ",", "message", ")", ":", "try", ":", "slug", "=", "None", "parts", "=", "topic", ".", "split", "(", "'/'", ")", "slug", "=", "parts", "[", "-", "3", "]", "uuid", "=", "self", ".",...
41.030303
23.939394
def sanitize_report_string(txt: str) -> str: """ Provides sanitization for operations that work better when the report is a string Returns the first pass sanitized report string """ if len(txt) < 4: return txt # Standardize whitespace txt = ' '.join(txt.split()) # Prevent change...
[ "def", "sanitize_report_string", "(", "txt", ":", "str", ")", "->", "str", ":", "if", "len", "(", "txt", ")", "<", "4", ":", "return", "txt", "# Standardize whitespace", "txt", "=", "' '", ".", "join", "(", "txt", ".", "split", "(", ")", ")", "# Prev...
39.90625
14.09375
def interpret(marker, execution_context=None): """ Interpret a marker and return a result depending on environment. :param marker: The marker to interpret. :type marker: str :param execution_context: The context used for name lookup. :type execution_context: mapping """ try: exp...
[ "def", "interpret", "(", "marker", ",", "execution_context", "=", "None", ")", ":", "try", ":", "expr", ",", "rest", "=", "parse_marker", "(", "marker", ")", "except", "Exception", "as", "e", ":", "raise", "SyntaxError", "(", "'Unable to interpret marker synta...
37.578947
15.578947
def get_default_metrics(config): """ Get the default metrics for a configuration. :param config: The configuration :type config: :class:`wily.config.WilyConfig` :return: Return the list of default metrics in this index :rtype: ``list`` of ``str`` """ archivers = list_archivers(config)...
[ "def", "get_default_metrics", "(", "config", ")", ":", "archivers", "=", "list_archivers", "(", "config", ")", "default_metrics", "=", "[", "]", "for", "archiver", "in", "archivers", ":", "index", "=", "get_archiver_index", "(", "config", ",", "archiver", ")",...
32.925926
17.666667
def dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, **kw): """ Serialize ``obj`` to a JSON formatted ``str``. If ``skipkeys`` is ``True`` then ``dict`` keys that are not basic types (``str``, ``unicode``, ``int``, ``long``, ``float``, ``...
[ "def", "dumps", "(", "obj", ",", "skipkeys", "=", "False", ",", "ensure_ascii", "=", "True", ",", "check_circular", "=", "True", ",", "allow_nan", "=", "True", ",", "cls", "=", "None", ",", "indent", "=", "None", ",", "*", "*", "kw", ")", ":", "if"...
49.029412
28.264706
def download_if_missing(self, version=None, verbose=True): """Download the jar for version into the jar_filename specified in the constructor. Will not overwrite jar_filename if it already exists. version defaults to DEFAULT_CORENLP_VERSION (ideally the latest but we can't guarantee that...
[ "def", "download_if_missing", "(", "self", ",", "version", "=", "None", ",", "verbose", "=", "True", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "self", ".", "jar_filename", ")", ":", "return", "jar_url", "=", "self", ".", "get_jar_url", "("...
48.428571
18.5
def module_can_run_parallel(test_module: unittest.TestSuite) -> bool: """ Checks if a given module of tests can be run in parallel or not :param test_module: the module to run :return: True if the module can be run on parallel, False otherwise """ for test_class in test_...
[ "def", "module_can_run_parallel", "(", "test_module", ":", "unittest", ".", "TestSuite", ")", "->", "bool", ":", "for", "test_class", "in", "test_module", ":", "# if the test is already failed, we just don't filter it", "# and let the test runner deal with it later.", "if", "...
53.391304
27.565217
def get_default_config(self): """ Returns the default collector settings """ config = super(UnboundCollector, self).get_default_config() config.update({ 'path': 'unbound', 'bin': self.find_binary('/usr/sbin/unbound-control'), '...
[ "def", "get_default_config", "(", "self", ")", ":", "config", "=", "super", "(", "UnboundCollector", ",", "self", ")", ".", "get_default_config", "(", ")", "config", ".", "update", "(", "{", "'path'", ":", "'unbound'", ",", "'bin'", ":", "self", ".", "fi...
33
13.909091
async def start(self): """Starts receiving messages on the underlying socket and passes them to the message router. """ self._is_running = True while self._is_running: try: zmq_msg = await self._socket.recv_multipart() message = Messa...
[ "async", "def", "start", "(", "self", ")", ":", "self", ".", "_is_running", "=", "True", "while", "self", ".", "_is_running", ":", "try", ":", "zmq_msg", "=", "await", "self", ".", "_socket", ".", "recv_multipart", "(", ")", "message", "=", "Message", ...
34.047619
14.619048
def _generic_hook(self, name, **kwargs): """ A generic hook that links the TemplateHelper with PluginManager """ entries = [entry for entry in self._plugin_manager.call_hook(name, **kwargs) if entry is not None] return "\n".join(entries)
[ "def", "_generic_hook", "(", "self", ",", "name", ",", "*", "*", "kwargs", ")", ":", "entries", "=", "[", "entry", "for", "entry", "in", "self", ".", "_plugin_manager", ".", "call_hook", "(", "name", ",", "*", "*", "kwargs", ")", "if", "entry", "is",...
64.5
18.25
def db_access_point(func): """ Wraps a function that actually accesses the database. It injects a session into the method and attempts to handle it after the function has run. :param method func: The method that is interacting with the database. """ @wraps(func) def wrapper(self, *args,...
[ "def", "db_access_point", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "wrapper", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "\"\"\"\n Wrapper responsible for handling\n sessions\n \"\"\"", "session", "=...
31.125
15.458333
def qualified_note_rate(pianoroll, threshold=2): """Return the ratio of the number of the qualified notes (notes longer than `threshold` (in time step)) to the total number of notes in a pianoroll.""" _validate_pianoroll(pianoroll) if np.issubdtype(pianoroll.dtype, np.bool_): pianoroll = pianoro...
[ "def", "qualified_note_rate", "(", "pianoroll", ",", "threshold", "=", "2", ")", ":", "_validate_pianoroll", "(", "pianoroll", ")", "if", "np", ".", "issubdtype", "(", "pianoroll", ".", "dtype", ",", "np", ".", "bool_", ")", ":", "pianoroll", "=", "pianoro...
52.166667
7.833333
def _get_bool_attribute(elem, name, default=False): """! @brief Extract an XML attribute with a boolean value. Supports "true"/"false" or "1"/"0" as the attribute values. Leading and trailing whitespace is stripped, and the comparison is case-insensitive. @param elem ElementTree.Element object...
[ "def", "_get_bool_attribute", "(", "elem", ",", "name", ",", "default", "=", "False", ")", ":", "if", "name", "not", "in", "elem", ".", "attrib", ":", "return", "default", "else", ":", "value", "=", "elem", ".", "attrib", "[", "name", "]", ".", "stri...
35.952381
17.809524
def add_lun(self, luns): """A wrapper for modify method. .. note:: This API only append luns to existing luns. """ curr_lun_ids, curr_smp_names = self._get_current_names() luns = normalize_lun(luns, self._cli) new_ids, new_smps = convert_lun(luns) if new_ids: ...
[ "def", "add_lun", "(", "self", ",", "luns", ")", ":", "curr_lun_ids", ",", "curr_smp_names", "=", "self", ".", "_get_current_names", "(", ")", "luns", "=", "normalize_lun", "(", "luns", ",", "self", ".", "_cli", ")", "new_ids", ",", "new_smps", "=", "con...
37.307692
14.538462
def _byteify(input): """ Force the given input to only use `str` instead of `bytes` or `unicode`. This works even if the input is a dict, list, """ if isinstance(input, dict): return {_byteify(key): _byteify(value) for key, value in input.items()} elif isinstance(input, list): re...
[ "def", "_byteify", "(", "input", ")", ":", "if", "isinstance", "(", "input", ",", "dict", ")", ":", "return", "{", "_byteify", "(", "key", ")", ":", "_byteify", "(", "value", ")", "for", "key", ",", "value", "in", "input", ".", "items", "(", ")", ...
41.466667
17.466667
def stack_frame_info(stacklevel): ''' Return a named tuple with information about the given stack frame: - filename - line_number - module_name - function_name stacklevel: How far up the stack to look. 1 means the immediate caller, 2 its caller, and so on. ''' ...
[ "def", "stack_frame_info", "(", "stacklevel", ")", ":", "import", "inspect", "if", "stacklevel", "<", "1", ":", "raise", "ValueError", "(", "'A stacklevel less than 1 is pointless'", ")", "frame", ",", "filename", ",", "line_number", ",", "function_name", ",", "_"...
28.241379
24.034483
def plotAccuracyDuringSensorimotorInference(resultsFig5B, title="", yaxis=""): """ Plot accuracy vs number of features """ # Read out results and get the ranges we want. with open(resultsFig5B, "rb") as f: results = cPickle.load(f) objectRange = [] featureRange = [] for r in results: if r["numO...
[ "def", "plotAccuracyDuringSensorimotorInference", "(", "resultsFig5B", ",", "title", "=", "\"\"", ",", "yaxis", "=", "\"\"", ")", ":", "# Read out results and get the ranges we want.", "with", "open", "(", "resultsFig5B", ",", "\"rb\"", ")", "as", "f", ":", "results...
33.649351
21
def _Backward3_T_Ph(P, h): """Backward equation for region 3, T=f(P,h) Parameters ---------- P : float Pressure, [MPa] h : float Specific enthalpy, [kJ/kg] Returns ------- T : float Temperature, [K] """ hf = _h_3ab(P) if h <= hf: T = _Backwar...
[ "def", "_Backward3_T_Ph", "(", "P", ",", "h", ")", ":", "hf", "=", "_h_3ab", "(", "P", ")", "if", "h", "<=", "hf", ":", "T", "=", "_Backward3a_T_Ph", "(", "P", ",", "h", ")", "else", ":", "T", "=", "_Backward3b_T_Ph", "(", "P", ",", "h", ")", ...
17.714286
21.047619
def read_write( adr, index_group, index_offset, plc_read_datatype, value, plc_write_datatype, return_ctypes=False, ): # type: (AmsAddr, int, int, Type, Any, Type, bool) -> Any """Read and write data synchronous from/to an ADS-device. :param AmsAddr adr: local or remo...
[ "def", "read_write", "(", "adr", ",", "index_group", ",", "index_offset", ",", "plc_read_datatype", ",", "value", ",", "plc_write_datatype", ",", "return_ctypes", "=", "False", ",", ")", ":", "# type: (AmsAddr, int, int, Type, Any, Type, bool) -> Any\r", "if", "port", ...
30.35
21
def reflectance(self, band): """ :param band: An optical band, i.e. 1-5, 7 :return: At satellite reflectance, [-] """ if band == 6: raise ValueError('LT5 reflectance must be other than band 6') rad = self.radiance(band) esun = self.ex_atm_irrad[band...
[ "def", "reflectance", "(", "self", ",", "band", ")", ":", "if", "band", "==", "6", ":", "raise", "ValueError", "(", "'LT5 reflectance must be other than band 6'", ")", "rad", "=", "self", ".", "radiance", "(", "band", ")", "esun", "=", "self", ".", "ex_at...
33.769231
18.461538
def create_chunked_list(in_dir, size, out_dir, out_name): """Create a division of the input files in chunks. The result is stored to a JSON file. """ create_dirs(out_dir) in_files = get_files(in_dir) chunks = chunk(in_files, size) division = {} for i, files in enumerate(chunks): ...
[ "def", "create_chunked_list", "(", "in_dir", ",", "size", ",", "out_dir", ",", "out_name", ")", ":", "create_dirs", "(", "out_dir", ")", "in_files", "=", "get_files", "(", "in_dir", ")", "chunks", "=", "chunk", "(", "in_files", ",", "size", ")", "division"...
28.166667
17.555556
def get(self, what): """ :param what: what to extract :returns: an ArrayWrapper instance """ url = '%s/v1/calc/%d/extract/%s' % (self.server, self.calc_id, what) logging.info('GET %s', url) resp = self.sess.get(url) if resp.status_code != 200: ...
[ "def", "get", "(", "self", ",", "what", ")", ":", "url", "=", "'%s/v1/calc/%d/extract/%s'", "%", "(", "self", ".", "server", ",", "self", ".", "calc_id", ",", "what", ")", "logging", ".", "info", "(", "'GET %s'", ",", "url", ")", "resp", "=", "self",...
33.529412
10.588235
def facets(self): """A tuple containing the facets for this Slot. The Python equivalent of the CLIPS slot-facets function. """ data = clips.data.DataObject(self._env) lib.EnvSlotFacets(self._env, self._cls, self._name, data.byref) return tuple(data.value) if isinstanc...
[ "def", "facets", "(", "self", ")", ":", "data", "=", "clips", ".", "data", ".", "DataObject", "(", "self", ".", "_env", ")", "lib", ".", "EnvSlotFacets", "(", "self", ".", "_env", ",", "self", ".", "_cls", ",", "self", ".", "_name", ",", "data", ...
30.636364
25.181818
def is_valid(self, tol: float = DISTANCE_TOLERANCE) -> bool: """ True if SiteCollection does not contain atoms that are too close together. Note that the distance definition is based on type of SiteCollection. Cartesian distances are used for non-periodic Molecules, while PBC is ...
[ "def", "is_valid", "(", "self", ",", "tol", ":", "float", "=", "DISTANCE_TOLERANCE", ")", "->", "bool", ":", "if", "len", "(", "self", ".", "sites", ")", "==", "1", ":", "return", "True", "all_dists", "=", "self", ".", "distance_matrix", "[", "np", "...
40.722222
22.722222
def build_swagger_12_endpoints(resource_listing, api_declarations): """ :param resource_listing: JSON representing a Swagger 1.2 resource listing :type resource_listing: dict :param api_declarations: JSON representing Swagger 1.2 api declarations :type api_declarations: dict :rtype: iterable of ...
[ "def", "build_swagger_12_endpoints", "(", "resource_listing", ",", "api_declarations", ")", ":", "yield", "build_swagger_12_resource_listing", "(", "resource_listing", ")", "for", "name", ",", "filepath", "in", "api_declarations", ".", "items", "(", ")", ":", "with", ...
44.428571
17.142857
def _assert_can_do_op(self, value): """ Check value is valid for scalar op. """ if not is_scalar(value): msg = "'value' must be a scalar, passed: {0}" raise TypeError(msg.format(type(value).__name__))
[ "def", "_assert_can_do_op", "(", "self", ",", "value", ")", ":", "if", "not", "is_scalar", "(", "value", ")", ":", "msg", "=", "\"'value' must be a scalar, passed: {0}\"", "raise", "TypeError", "(", "msg", ".", "format", "(", "type", "(", "value", ")", ".", ...
35.714286
7.714286
def adapt_package(package): """Adapts ``.epub.Package`` to a ``BinderItem`` and cascades the adaptation downward to ``DocumentItem`` and ``ResourceItem``. The results of this process provide the same interface as ``.models.Binder``, ``.models.Document`` and ``.models.Resource``. """ navigati...
[ "def", "adapt_package", "(", "package", ")", ":", "navigation_item", "=", "package", ".", "navigation", "html", "=", "etree", ".", "parse", "(", "navigation_item", ".", "data", ")", "tree", "=", "parse_navigation_html_to_tree", "(", "html", ",", "navigation_item...
44.818182
10.727273
def cdhit_from_seqs(seqs, moltype, params=None): """Returns the CD-HIT results given seqs seqs : dict like collection of sequences moltype : cogent.core.moltype object params : cd-hit parameters NOTE: This method will call CD_HIT if moltype is PROTIEN, CD_HIT_EST if moltype is RNA/DNA,...
[ "def", "cdhit_from_seqs", "(", "seqs", ",", "moltype", ",", "params", "=", "None", ")", ":", "# keys are not remapped. Tested against seq_ids of 100char length", "seqs", "=", "SequenceCollection", "(", "seqs", ",", "MolType", "=", "moltype", ")", "# setup params and mak...
32.365854
19.317073
def transformer_ada_lmpackedbase_dialog(): """Set of hyperparameters.""" hparams = transformer_base_vq_ada_32ex_packed() hparams.max_length = 1024 hparams.ffn_layer = "dense_relu_dense" hparams.batch_size = 4096 return hparams
[ "def", "transformer_ada_lmpackedbase_dialog", "(", ")", ":", "hparams", "=", "transformer_base_vq_ada_32ex_packed", "(", ")", "hparams", ".", "max_length", "=", "1024", "hparams", ".", "ffn_layer", "=", "\"dense_relu_dense\"", "hparams", ".", "batch_size", "=", "4096"...
33.142857
8.714286
def set_sort_cb(self, w, index): """This callback is invoked when the user selects a new sort order from the preferences pane.""" name = self.sort_options[index] self.t_.set(sort_order=name)
[ "def", "set_sort_cb", "(", "self", ",", "w", ",", "index", ")", ":", "name", "=", "self", ".", "sort_options", "[", "index", "]", "self", ".", "t_", ".", "set", "(", "sort_order", "=", "name", ")" ]
43.6
2.6
def output(self, key, obj): """Pulls the value for the given key from the object, applies the field's formatting and returns the result. If the key is not found in the object, returns the default value. Field classes that create values which do not require the existence of the key in the...
[ "def", "output", "(", "self", ",", "key", ",", "obj", ")", ":", "value", "=", "get_value", "(", "key", "if", "self", ".", "attribute", "is", "None", "else", "self", ".", "attribute", ",", "obj", ")", "if", "value", "is", "None", ":", "return", "sel...
39.5
24.75
def get_category(self, id, **data): """ GET /categories/:id/ Gets a :format:`category` by ID as ``category``. """ return self.get("/categories/{0}/".format(id), data=data)
[ "def", "get_category", "(", "self", ",", "id", ",", "*", "*", "data", ")", ":", "return", "self", ".", "get", "(", "\"/categories/{0}/\"", ".", "format", "(", "id", ")", ",", "data", "=", "data", ")" ]
30.571429
12.857143
def create_data(self, extra=None): r""" Generate object for api. Example json: { "service_job_id": "1234567890", "service_name": "travis-ci", "source_files": [ { "name": "example.py", ...
[ "def", "create_data", "(", "self", ",", "extra", "=", "None", ")", ":", "if", "self", ".", "_data", ":", "return", "self", ".", "_data", "self", ".", "_data", "=", "{", "'source_files'", ":", "self", ".", "get_coverage", "(", ")", "}", "self", ".", ...
32.243243
16.216216
def get(self, block=True, timeout=None): """Remove and return an item from the queue. If optional args 'block' is true and 'timeout' is None (the default), block if necessary until an item is available. If 'timeout' is a positive number, it blocks at most 'timeout' seconds and raises ...
[ "def", "get", "(", "self", ",", "block", "=", "True", ",", "timeout", "=", "None", ")", ":", "self", ".", "not_empty", ".", "acquire", "(", ")", "try", ":", "if", "not", "block", ":", "if", "not", "self", ".", "_qsize", "(", ")", ":", "raise", ...
39.612903
15.064516
def get_assessment_part_form_for_update(self, assessment_part_id): """Gets the assessment part form for updating an existing assessment part. A new assessment part form should be requested for each update transaction. arg: assessment_part_id (osid.id.Id): the ``Id`` of the ...
[ "def", "get_assessment_part_form_for_update", "(", "self", ",", "assessment_part_id", ")", ":", "collection", "=", "JSONClientValidated", "(", "'assessment_authoring'", ",", "collection", "=", "'AssessmentPart'", ",", "runtime", "=", "self", ".", "_runtime", ")", "if"...
52.681818
26.931818
def push_msg(self, channel_id, msg): """Push ``msg`` for given ``channel_id``. If ``msg`` is not string, it will be urlencoded """ if type(msg) is not str: msg = urlencode(msg) return self.push(channel_id, msg)
[ "def", "push_msg", "(", "self", ",", "channel_id", ",", "msg", ")", ":", "if", "type", "(", "msg", ")", "is", "not", "str", ":", "msg", "=", "urlencode", "(", "msg", ")", "return", "self", ".", "push", "(", "channel_id", ",", "msg", ")" ]
28.555556
12.666667
def _condHasEffect(self) -> bool: """ :return: True if statements in branches has different effect """ if not self.cases: return False # [TODO] type_domain_covered = bool(self.default) or len( self.cases) == self.switchOn._dtype.domain_size() ...
[ "def", "_condHasEffect", "(", "self", ")", "->", "bool", ":", "if", "not", "self", ".", "cases", ":", "return", "False", "# [TODO]", "type_domain_covered", "=", "bool", "(", "self", ".", "default", ")", "or", "len", "(", "self", ".", "cases", ")", "=="...
31.666667
14.083333
def is_negative(pattern, flags): """Check if negative pattern.""" if flags & MINUSNEGATE: return flags & NEGATE and pattern[0:1] in MINUS_NEGATIVE_SYM else: return flags & NEGATE and pattern[0:1] in NEGATIVE_SYM
[ "def", "is_negative", "(", "pattern", ",", "flags", ")", ":", "if", "flags", "&", "MINUSNEGATE", ":", "return", "flags", "&", "NEGATE", "and", "pattern", "[", "0", ":", "1", "]", "in", "MINUS_NEGATIVE_SYM", "else", ":", "return", "flags", "&", "NEGATE", ...
33.428571
20.285714
def get_gaf_gene_ontology_file(path): """Extract the gene ontology file associated with a GO annotation file. Parameters ---------- path: str The path name of the GO annotation file. Returns ------- str The URL of the associated gene ontology file. """ assert isinst...
[ "def", "get_gaf_gene_ontology_file", "(", "path", ")", ":", "assert", "isinstance", "(", "path", ",", "str", ")", "version", "=", "None", "with", "misc", ".", "smart_open_read", "(", "path", ",", "encoding", "=", "'UTF-8'", ",", "try_gzip", "=", "True", ")...
25.291667
19.875
def get_initial_states(self, input_var, init_state=None): """ :type input_var: T.var :rtype: dict """ initial_states = {} for state in self.state_names: if state != "state" or not init_state: if self._input_type == 'sequence' and input_var.ndim...
[ "def", "get_initial_states", "(", "self", ",", "input_var", ",", "init_state", "=", "None", ")", ":", "initial_states", "=", "{", "}", "for", "state", "in", "self", ".", "state_names", ":", "if", "state", "!=", "\"state\"", "or", "not", "init_state", ":", ...
42.857143
17.714286
def batch_eval_multi_worker(sess, graph_factory, numpy_inputs, batch_size=None, devices=None, feed=None): """ Generic computation engine for evaluating an expression across a whole dataset, divided into batches. This function assumes that the work can be parallelized with one worker...
[ "def", "batch_eval_multi_worker", "(", "sess", ",", "graph_factory", ",", "numpy_inputs", ",", "batch_size", "=", "None", ",", "devices", "=", "None", ",", "feed", "=", "None", ")", ":", "canary", ".", "run_canary", "(", ")", "global", "_batch_eval_multi_worke...
39.889503
19.801105
def cosinebell(n, fraction): """Return a cosine bell spanning n pixels, masking a fraction of pixels Parameters ---------- n : int Number of pixels. fraction : float Length fraction over which the data will be masked. """ mask = np.ones(n) nmasked = int(fraction * n) ...
[ "def", "cosinebell", "(", "n", ",", "fraction", ")", ":", "mask", "=", "np", ".", "ones", "(", "n", ")", "nmasked", "=", "int", "(", "fraction", "*", "n", ")", "for", "i", "in", "range", "(", "nmasked", ")", ":", "yval", "=", "0.5", "*", "(", ...
23.4
21.4
def plot_metric(booster, metric=None, dataset_names=None, ax=None, xlim=None, ylim=None, title='Metric during training', xlabel='Iterations', ylabel='auto', figsize=None, grid=True): """Plot one metric during training. Parameters ---------- ...
[ "def", "plot_metric", "(", "booster", ",", "metric", "=", "None", ",", "dataset_names", "=", "None", ",", "ax", "=", "None", ",", "xlim", "=", "None", ",", "ylim", "=", "None", ",", "title", "=", "'Metric during training'", ",", "xlabel", "=", "'Iteratio...
35.655738
18.360656
def broadcast(client, sender, msg_name, dest_name=None, block=None): """broadcast a message from one engine to all others.""" dest_name = msg_name if dest_name is None else dest_name client[sender].execute('com.publish(%s)'%msg_name, block=None) targets = client.ids targets.remove(sender) return...
[ "def", "broadcast", "(", "client", ",", "sender", ",", "msg_name", ",", "dest_name", "=", "None", ",", "block", "=", "None", ")", ":", "dest_name", "=", "msg_name", "if", "dest_name", "is", "None", "else", "dest_name", "client", "[", "sender", "]", ".", ...
54.285714
20
def __find_block_neighbors(self, block, level_blocks, unhandled_block_indexes): """! @brief Search block neighbors that are parts of new clusters (density is greater than threshold and that are not cluster members yet), other neighbors are ignored. @param[in] block (bang_bl...
[ "def", "__find_block_neighbors", "(", "self", ",", "block", ",", "level_blocks", ",", "unhandled_block_indexes", ")", ":", "neighbors", "=", "[", "]", "handled_block_indexes", "=", "[", "]", "for", "unhandled_index", "in", "unhandled_block_indexes", ":", "if", "bl...
43.285714
28.464286
def read_cache(self): """Reads the cached contents into memory.""" if os.path.exists(self._cache_file): self._cache = read_cache_file(self._cache_file) else: self._cache = {}
[ "def", "read_cache", "(", "self", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "self", ".", "_cache_file", ")", ":", "self", ".", "_cache", "=", "read_cache_file", "(", "self", ".", "_cache_file", ")", "else", ":", "self", ".", "_cache", "=...
36.166667
13.5
def _setup_global_state_for_execution(laser_evm, transaction) -> None: """Sets up global state and cfg for a transactions execution. :param laser_evm: :param transaction: """ # TODO: Resolve circular import between .transaction and ..svm to import LaserEVM here global_state = transaction.initia...
[ "def", "_setup_global_state_for_execution", "(", "laser_evm", ",", "transaction", ")", "->", "None", ":", "# TODO: Resolve circular import between .transaction and ..svm to import LaserEVM here", "global_state", "=", "transaction", ".", "initial_global_state", "(", ")", "global_s...
37.257143
19.885714
def unpackbools(integers, dtype='L'): """Yield booleans unpacking integers of dtype bit-length. >>> list(unpackbools([42], 'B')) [False, True, False, True, False, True, False, False] """ atoms = ATOMS[dtype] for chunk in integers: for a in atoms: yield not not chunk & a
[ "def", "unpackbools", "(", "integers", ",", "dtype", "=", "'L'", ")", ":", "atoms", "=", "ATOMS", "[", "dtype", "]", "for", "chunk", "in", "integers", ":", "for", "a", "in", "atoms", ":", "yield", "not", "not", "chunk", "&", "a" ]
27.818182
14.181818
def _delete_record(self, identifier=None, rtype=None, name=None, content=None): """ delete a record filter selection to delete by identifier or rtype/name/content :param int identifier: identifier of record to update :param str rtype: rtype of record ...
[ "def", "_delete_record", "(", "self", ",", "identifier", "=", "None", ",", "rtype", "=", "None", ",", "name", "=", "None", ",", "content", "=", "None", ")", ":", "record_ids", "=", "[", "]", "if", "not", "identifier", ":", "records", "=", "self", "."...
35.428571
15.071429
def get_changes(self, remove=True, only_current=False, resources=None, task_handle=taskhandle.NullTaskHandle()): """Get the changes this refactoring makes If `remove` is `False` the definition will not be removed. If `only_current` is `True`, the the current occurrence will...
[ "def", "get_changes", "(", "self", ",", "remove", "=", "True", ",", "only_current", "=", "False", ",", "resources", "=", "None", ",", "task_handle", "=", "taskhandle", ".", "NullTaskHandle", "(", ")", ")", ":", "changes", "=", "ChangeSet", "(", "'Inline me...
47.025641
17.435897
def _set_attr(self, name, doc=None, preload=False): "Initially sets up an attribute." if doc is None: doc = 'The {name} attribute.'.format(name=name) if not hasattr(self._attr_func_, name): attr_prop = property( functools.partial(self._setable_get_, name...
[ "def", "_set_attr", "(", "self", ",", "name", ",", "doc", "=", "None", ",", "preload", "=", "False", ")", ":", "if", "doc", "is", "None", ":", "doc", "=", "'The {name} attribute.'", ".", "format", "(", "name", "=", "name", ")", "if", "not", "hasattr"...
30.689655
19.37931
def read_message(self): """Try to read a message from the buffered data. A message is defined as a 32-bit integer size, followed that number of bytes. First we try to non-destructively read the integer. Then, we try to non- destructively read the remaining bytes. If both are successful,...
[ "def", "read_message", "(", "self", ")", ":", "with", "self", ".", "__class__", ".", "__locker", ":", "result", "=", "self", ".", "__passive_read", "(", "4", ")", "if", "result", "is", "None", ":", "return", "None", "(", "four_bytes", ",", "last_buffer_i...
37.526316
22.026316
def to_xdr_object(self): """Create an XDR object for this :class:`Asset`. :return: An XDR Asset object """ if self.is_native(): xdr_type = Xdr.const.ASSET_TYPE_NATIVE return Xdr.types.Asset(type=xdr_type) else: x = Xdr.nullclass() ...
[ "def", "to_xdr_object", "(", "self", ")", ":", "if", "self", ".", "is_native", "(", ")", ":", "xdr_type", "=", "Xdr", ".", "const", ".", "ASSET_TYPE_NATIVE", "return", "Xdr", ".", "types", ".", "Asset", "(", "type", "=", "xdr_type", ")", "else", ":", ...
40.7
17.05
def ds_fitplane(ds): """Fit a plane to values in GDAL Dataset """ from pygeotools.lib import iolib bma = iolib.ds_getma(ds) gt = ds.GetGeoTransform() return ma_fitplane(bma, gt)
[ "def", "ds_fitplane", "(", "ds", ")", ":", "from", "pygeotools", ".", "lib", "import", "iolib", "bma", "=", "iolib", ".", "ds_getma", "(", "ds", ")", "gt", "=", "ds", ".", "GetGeoTransform", "(", ")", "return", "ma_fitplane", "(", "bma", ",", "gt", "...
27.857143
8