text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def get_recursive_subclasses(cls): """Return list of all subclasses for a class, including subclasses of direct subclasses""" return cls.__subclasses__() + [g for s in cls.__subclasses__() for g in get_recursive_subclasses(s)]
[ "def", "get_recursive_subclasses", "(", "cls", ")", ":", "return", "cls", ".", "__subclasses__", "(", ")", "+", "[", "g", "for", "s", "in", "cls", ".", "__subclasses__", "(", ")", "for", "g", "in", "get_recursive_subclasses", "(", "s", ")", "]" ]
77.333333
0.012821
def write_mapping_file(mapF, sampleIDs, barcodes, treatment=None): """ Given a mapping from sample IDs to barcodes/primers/other info, write out a QIIME-compatible mapping file. File format described at: http://qiime.org/documentation/file_formats.html Note that primer column can be left blank. ...
[ "def", "write_mapping_file", "(", "mapF", ",", "sampleIDs", ",", "barcodes", ",", "treatment", "=", "None", ")", ":", "header", "=", "[", "'#SampleID'", ",", "'BarcodeSequence'", ",", "'LinkerPrimerSequence'", ",", "'Description'", ",", "'\\n'", "]", "if", "tr...
36.24
0.001075
def paddr(address): """Parse a string representation of an address. This function is the inverse of :func:`saddr`. """ if not isinstance(address, six.string_types): raise TypeError('expecting a string') if address.startswith('['): p1 = address.find(']:') if p1 == -1: ...
[ "def", "paddr", "(", "address", ")", ":", "if", "not", "isinstance", "(", "address", ",", "six", ".", "string_types", ")", ":", "raise", "TypeError", "(", "'expecting a string'", ")", "if", "address", ".", "startswith", "(", "'['", ")", ":", "p1", "=", ...
30.411765
0.001876
def registry_comparison(registry0, registry1): """Compares two dictionaries of registry keys returning their difference.""" comparison = {'created_keys': {}, 'deleted_keys': [], 'created_values': {}, 'deleted_values': {}, 'modified_values':...
[ "def", "registry_comparison", "(", "registry0", ",", "registry1", ")", ":", "comparison", "=", "{", "'created_keys'", ":", "{", "}", ",", "'deleted_keys'", ":", "[", "]", ",", "'created_values'", ":", "{", "}", ",", "'deleted_values'", ":", "{", "}", ",", ...
37.142857
0.001874
def field_mask(original, modified): """Create a field mask by comparing two messages. Args: original (~google.protobuf.message.Message): the original message. If set to None, this field will be interpretted as an empty message. modified (~google.protobuf.message.Message)...
[ "def", "field_mask", "(", "original", ",", "modified", ")", ":", "if", "original", "is", "None", "and", "modified", "is", "None", ":", "return", "field_mask_pb2", ".", "FieldMask", "(", ")", "if", "original", "is", "None", "and", "modified", "is", "not", ...
36.512821
0.001368
def _serialize_argument(rargname, value, varprops): """Serialize an MRS argument into the SimpleMRS format.""" _argument = '{rargname}: {value}{props}' if rargname == CONSTARG_ROLE: value = '"{}"'.format(value) props = '' if value in varprops: props = ' [ {} ]'.format( ' ...
[ "def", "_serialize_argument", "(", "rargname", ",", "value", ",", "varprops", ")", ":", "_argument", "=", "'{rargname}: {value}{props}'", "if", "rargname", "==", "CONSTARG_ROLE", ":", "value", "=", "'\"{}\"'", ".", "format", "(", "value", ")", "props", "=", "'...
32.55
0.001493
def load_builtin_slots(): ''' Helper function to load builtin slots from the data location ''' builtin_slots = {} for index, line in enumerate(open(BUILTIN_SLOTS_LOCATION)): o = line.strip().split('\t') builtin_slots[index] = {'name' : o[0], 'descript...
[ "def", "load_builtin_slots", "(", ")", ":", "builtin_slots", "=", "{", "}", "for", "index", ",", "line", "in", "enumerate", "(", "open", "(", "BUILTIN_SLOTS_LOCATION", ")", ")", ":", "o", "=", "line", ".", "strip", "(", ")", ".", "split", "(", "'\\t'",...
35
0.016713
def print_file_details_as_csv(self, fname, col_headers): """ saves as csv format """ line = '' qu = '"' d = ',' for fld in col_headers: if fld == "fullfilename": line = line + qu + fname + qu + d if fld == "name": l...
[ "def", "print_file_details_as_csv", "(", "self", ",", "fname", ",", "col_headers", ")", ":", "line", "=", "''", "qu", "=", "'\"'", "d", "=", "','", "for", "fld", "in", "col_headers", ":", "if", "fld", "==", "\"fullfilename\"", ":", "line", "=", "line", ...
38.285714
0.002427
def to_locale(language, to_lower=False): """ Turns a language name (en-us) into a locale name (en_US). If 'to_lower' is True, the last component is lower-cased (en_us). Taken `from Django <http://bit.ly/1ssrxqE>`_. """ p = language.find('-') if p >= 0: if to_lower: retur...
[ "def", "to_locale", "(", "language", ",", "to_lower", "=", "False", ")", ":", "p", "=", "language", ".", "find", "(", "'-'", ")", "if", "p", ">=", "0", ":", "if", "to_lower", ":", "return", "language", "[", ":", "p", "]", ".", "lower", "(", ")", ...
37.263158
0.001377
def download(sid, credentials=None, subjects_path=None, overwrite=False, release='HCP_1200', database='hcp-openaccess', file_list=None): ''' download(sid) downloads the data for subject with the given subject id. By default, the subject will be placed in the first HCP subject directory in the...
[ "def", "download", "(", "sid", ",", "credentials", "=", "None", ",", "subjects_path", "=", "None", ",", "overwrite", "=", "False", ",", "release", "=", "'HCP_1200'", ",", "database", "=", "'hcp-openaccess'", ",", "file_list", "=", "None", ")", ":", "if", ...
60.266667
0.008707
def _calculate_block_structure(self, inequalities, equalities, momentinequalities, momentequalities, extramomentmatrix, removeequalities, block_struct=None): """Calculates the block_struct array for the outp...
[ "def", "_calculate_block_structure", "(", "self", ",", "inequalities", ",", "equalities", ",", "momentinequalities", ",", "momentequalities", ",", "extramomentmatrix", ",", "removeequalities", ",", "block_struct", "=", "None", ")", ":", "if", "block_struct", "is", "...
48.11828
0.001095
def fit_params_to_1d_data(logX): """ Fit skewed normal distributions to 1-D capactity data, and return the distribution parameters. Args ---- logX: Logarithm of one-dimensional capacity data, indexed by module and phase resolution index """ m_max = logX.shape[0] p...
[ "def", "fit_params_to_1d_data", "(", "logX", ")", ":", "m_max", "=", "logX", ".", "shape", "[", "0", "]", "p_max", "=", "logX", ".", "shape", "[", "1", "]", "params", "=", "np", ".", "zeros", "(", "(", "m_max", ",", "p_max", ",", "3", ")", ")", ...
25
0.013487
def set_status(self, instance, status): """Sets the field status for up to 5 minutes.""" status_key = self.get_status_key(instance) cache.set(status_key, status, timeout=300)
[ "def", "set_status", "(", "self", ",", "instance", ",", "status", ")", ":", "status_key", "=", "self", ".", "get_status_key", "(", "instance", ")", "cache", ".", "set", "(", "status_key", ",", "status", ",", "timeout", "=", "300", ")" ]
48.75
0.010101
def info(self, buf=None): """ Concise summary of a Dataset variables and attributes. Parameters ---------- buf : writable buffer, defaults to sys.stdout See Also -------- pandas.DataFrame.assign netCDF's ncdump """ if buf is None...
[ "def", "info", "(", "self", ",", "buf", "=", "None", ")", ":", "if", "buf", "is", "None", ":", "# pragma: no cover", "buf", "=", "sys", ".", "stdout", "lines", "=", "[", "]", "lines", ".", "append", "(", "'xarray.Dataset {'", ")", "lines", ".", "appe...
33.027778
0.001634
def sys_munmap(self, addr, size): """ Unmaps a file from memory. It deletes the mappings for the specified address range :rtype: int :param addr: the starting address to unmap. :param size: the size of the portion to unmap. :return: C{0} on success. """ s...
[ "def", "sys_munmap", "(", "self", ",", "addr", ",", "size", ")", ":", "self", ".", "current", ".", "memory", ".", "munmap", "(", "addr", ",", "size", ")", "return", "0" ]
33.090909
0.008021
def absent(name, domain, user=None): ''' Make sure the defaults value is absent name The key of the given domain to remove domain The name of the domain to remove from user The user to write the defaults to ''' ret = {'name': name, 'result': True, ...
[ "def", "absent", "(", "name", ",", "domain", ",", "user", "=", "None", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'result'", ":", "True", ",", "'comment'", ":", "''", ",", "'changes'", ":", "{", "}", "}", "out", "=", "__salt__", "[",...
21.857143
0.001565
def iter_package_families(paths=None): """Iterate over package families, in no particular order. Note that multiple package families with the same name can be returned. Unlike packages, families later in the searchpath are not hidden by earlier families. Args: paths (list of str, optional)...
[ "def", "iter_package_families", "(", "paths", "=", "None", ")", ":", "for", "path", "in", "(", "paths", "or", "config", ".", "packages_path", ")", ":", "repo", "=", "package_repository_manager", ".", "get_repository", "(", "path", ")", "for", "resource", "in...
36.333333
0.00149
def _Parse(self): """Extracts attributes and extents from the volume.""" vshadow_store = self._file_entry.GetVShadowStore() self._AddAttribute(volume_system.VolumeAttribute( 'identifier', vshadow_store.identifier)) self._AddAttribute(volume_system.VolumeAttribute( 'copy_identifier', vsh...
[ "def", "_Parse", "(", "self", ")", ":", "vshadow_store", "=", "self", ".", "_file_entry", ".", "GetVShadowStore", "(", ")", "self", ".", "_AddAttribute", "(", "volume_system", ".", "VolumeAttribute", "(", "'identifier'", ",", "vshadow_store", ".", "identifier", ...
46.6
0.001403
def _delete(self, **kwargs): """Delete a resource from a remote Transifex server.""" path = self._construct_path_to_item() return self._http.delete(path)
[ "def", "_delete", "(", "self", ",", "*", "*", "kwargs", ")", ":", "path", "=", "self", ".", "_construct_path_to_item", "(", ")", "return", "self", ".", "_http", ".", "delete", "(", "path", ")" ]
43.5
0.011299
def get_post_addresses(self): """ : returns: dict of type and post address list :rtype: dict(str, list(dict(str,list|str))) """ post_adr_dict = {} for child in self.vcard.getChildren(): if child.name == "ADR": type = helpers.list_to_string( ...
[ "def", "get_post_addresses", "(", "self", ")", ":", "post_adr_dict", "=", "{", "}", "for", "child", "in", "self", ".", "vcard", ".", "getChildren", "(", ")", ":", "if", "child", ".", "name", "==", "\"ADR\"", ":", "type", "=", "helpers", ".", "list_to_s...
43.107143
0.001621
def PDBasXMLwithSymwithPolarH(self, id): """ Adds Hydrogen Atoms to a Structure. """ print _WARNING # Protonated Structure in XML Format h_s_xml = urllib.urlopen("http://www.cmbi.ru.nl/wiwsd/rest/PDBasXMLwithSymwithPolarH/id/" + id) self.raw = h_s_xml ...
[ "def", "PDBasXMLwithSymwithPolarH", "(", "self", ",", "id", ")", ":", "print", "_WARNING", "# Protonated Structure in XML Format", "h_s_xml", "=", "urllib", ".", "urlopen", "(", "\"http://www.cmbi.ru.nl/wiwsd/rest/PDBasXMLwithSymwithPolarH/id/\"", "+", "id", ")", "self", ...
31.923077
0.01171
def ReplaceHomoglyphs(s): """Returns s with unicode homoglyphs replaced by ascii equivalents.""" homoglyphs = { '\xa0': ' ', # &nbsp; ? '\u00e3': '', # TODO(gsfowler) drop after .proto spurious char elided '\u00a0': ' ', # &nbsp; ? '\u00a9': '(C)', # COPYRIGHT SIGN (would you...
[ "def", "ReplaceHomoglyphs", "(", "s", ")", ":", "homoglyphs", "=", "{", "'\\xa0'", ":", "' '", ",", "# &nbsp; ?", "'\\u00e3'", ":", "''", ",", "# TODO(gsfowler) drop after .proto spurious char elided", "'\\u00a0'", ":", "' '", ",", "# &nbsp; ?", "'\\u00a9'", ":", ...
36.212121
0.000815
def holding_pnl(self): """ [float] 浮动盈亏 """ return sum(position.holding_pnl for position in six.itervalues(self._positions))
[ "def", "holding_pnl", "(", "self", ")", ":", "return", "sum", "(", "position", ".", "holding_pnl", "for", "position", "in", "six", ".", "itervalues", "(", "self", ".", "_positions", ")", ")" ]
30.4
0.019231
def build_list_result(results, xml): """ 构建带翻页的列表 :param results: 已获取的数据列表 :param xml: 原始页面xml :return: {'results': list, 'count': int, 'next_start': int|None} 如果count与results长度不同,则有更多 如果next_start不为None,则可以到下一页 """ xml_count = xml.xpath('//div[@class="paginator"...
[ "def", "build_list_result", "(", "results", ",", "xml", ")", ":", "xml_count", "=", "xml", ".", "xpath", "(", "'//div[@class=\"paginator\"]/span[@class=\"count\"]/text()'", ")", "xml_next", "=", "xml", ".", "xpath", "(", "'//div[@class=\"paginator\"]/span[@class=\"next\"]...
45.066667
0.008696
def logger(ref=0): """Finds a module logger. If the argument passed is a module, find the logger for that module using the modules' name; if it's a string, finds a logger of that name; if an integer, walks the stack to the module at that height. The logger is always extended with a ``.configure()`...
[ "def", "logger", "(", "ref", "=", "0", ")", ":", "if", "inspect", ".", "ismodule", "(", "ref", ")", ":", "return", "extend", "(", "logging", ".", "getLogger", "(", "ref", ".", "__name__", ")", ")", "if", "isinstance", "(", "ref", ",", "basestring", ...
43.375
0.00141
def email_change(request, username, email_form=ChangeEmailForm, template_name='userena/email_form.html', success_url=None, extra_context=None): """ Change email address :param username: String of the username which specifies the current account. :param email_f...
[ "def", "email_change", "(", "request", ",", "username", ",", "email_form", "=", "ChangeEmailForm", ",", "template_name", "=", "'userena/email_form.html'", ",", "success_url", "=", "None", ",", "extra_context", "=", "None", ")", ":", "user", "=", "get_object_or_404...
37.647059
0.001523
def pull(self, dict_name): '''Get the entire contents of a single dictionary. This operates without a session lock, but is still atomic. In particular this will run even if someone else holds a session lock and you do not. This is only suitable for "small" dictionaries; if you...
[ "def", "pull", "(", "self", ",", "dict_name", ")", ":", "dict_name", "=", "self", ".", "_namespace", "(", "dict_name", ")", "conn", "=", "redis", ".", "Redis", "(", "connection_pool", "=", "self", ".", "pool", ")", "res", "=", "conn", ".", "hgetall", ...
39.681818
0.002237
def _create_pipeline_parser(): """ Create the parser for the %pipeline magics. Note that because we use the func default handler dispatch mechanism of argparse, our handlers can take only one argument which is the parsed args. So we must create closures for the handlers that bind the cell contents and th...
[ "def", "_create_pipeline_parser", "(", ")", ":", "parser", "=", "google", ".", "datalab", ".", "utils", ".", "commands", ".", "CommandParser", "(", "prog", "=", "'%pipeline'", ",", "description", "=", "\"\"\"\nExecute various pipeline-related operations. Use \"%pipeline...
37.944444
0.011429
def paste_traceback(self, request, traceback): """Paste the traceback and return a JSON response.""" rv = traceback.paste() return Response(json.dumps(rv), content_type='application/json')
[ "def", "paste_traceback", "(", "self", ",", "request", ",", "traceback", ")", ":", "rv", "=", "traceback", ".", "paste", "(", ")", "return", "Response", "(", "json", ".", "dumps", "(", "rv", ")", ",", "content_type", "=", "'application/json'", ")" ]
52.25
0.009434
def get_bandcamp_metadata(url): """ Read information from the Bandcamp JavaScript object. The method may return a list of URLs (indicating this is probably a "main" page which links to one or more albums), or a JSON if we can already parse album/track info from the given url. The JSON is "sloppy". T...
[ "def", "get_bandcamp_metadata", "(", "url", ")", ":", "request", "=", "requests", ".", "get", "(", "url", ")", "try", ":", "sloppy_json", "=", "request", ".", "text", ".", "split", "(", "\"var TralbumData = \"", ")", "sloppy_json", "=", "sloppy_json", "[", ...
48.22
0.002033
def register_onchain_secret( channel_state: NettingChannelState, secret: Secret, secrethash: SecretHash, secret_reveal_block_number: BlockNumber, delete_lock: bool = True, ) -> None: """This will register the onchain secret and set the lock to the unlocked stated. Even t...
[ "def", "register_onchain_secret", "(", "channel_state", ":", "NettingChannelState", ",", "secret", ":", "Secret", ",", "secrethash", ":", "SecretHash", ",", "secret_reveal_block_number", ":", "BlockNumber", ",", "delete_lock", ":", "bool", "=", "True", ",", ")", "...
28.413793
0.002347
def from_mediaid(cls, context: InstaloaderContext, mediaid: int): """Create a post object from a given mediaid""" return cls.from_shortcode(context, Post.mediaid_to_shortcode(mediaid))
[ "def", "from_mediaid", "(", "cls", ",", "context", ":", "InstaloaderContext", ",", "mediaid", ":", "int", ")", ":", "return", "cls", ".", "from_shortcode", "(", "context", ",", "Post", ".", "mediaid_to_shortcode", "(", "mediaid", ")", ")" ]
66
0.01
def traceParseAction(f): """Decorator for debugging parse actions. When the parse action is called, this decorator will print ``">> entering method-name(line:<current_source_line>, <parse_location>, <matched_tokens>)"``. When the parse action completes, the decorator will print ``"<<"`` followed by...
[ "def", "traceParseAction", "(", "f", ")", ":", "f", "=", "_trim_arity", "(", "f", ")", "def", "z", "(", "*", "paArgs", ")", ":", "thisFunc", "=", "f", ".", "__name__", "s", ",", "l", ",", "t", "=", "paArgs", "[", "-", "3", ":", "]", "if", "le...
34.590909
0.014058
def main(): """The main entry """ args = getArguments() try: if args.action == 'init': # Ask for init while True: print 'Initialize the path [%s] will cause any files or dirs be removed, continue?[y/n]' % args.basePath, text = raw_input() ...
[ "def", "main", "(", ")", ":", "args", "=", "getArguments", "(", ")", "try", ":", "if", "args", ".", "action", "==", "'init'", ":", "# Ask for init", "while", "True", ":", "print", "'Initialize the path [%s] will cause any files or dirs be removed, continue?[y/n]'", ...
38.25
0.002451
def Receive(self, replytype, chain=None, **kw): """This method allows code to act in a synchronous manner, it waits to return until the deferred fires but it doesn't prevent other queued calls from being executed. Send must be called first, which sets up the chain/factory. ...
[ "def", "Receive", "(", "self", ",", "replytype", ",", "chain", "=", "None", ",", "*", "*", "kw", ")", ":", "chain", "=", "chain", "or", "self", ".", "chain", "d", "=", "chain", ".", "flow", ".", "deferred", "if", "self", ".", "trace", ":", "def",...
31.660377
0.009827
def check_exists_repositories(repo): """Checking if repositories exists by PACKAGES.TXT file """ pkg_list = "PACKAGES.TXT" if repo == "sbo": pkg_list = "SLACKBUILDS.TXT" if check_for_local_repos(repo) is True: pkg_list = "PACKAGES.TXT" return "" if not os.path.isfile("{0}...
[ "def", "check_exists_repositories", "(", "repo", ")", ":", "pkg_list", "=", "\"PACKAGES.TXT\"", "if", "repo", "==", "\"sbo\"", ":", "pkg_list", "=", "\"SLACKBUILDS.TXT\"", "if", "check_for_local_repos", "(", "repo", ")", "is", "True", ":", "pkg_list", "=", "\"PA...
32.615385
0.002294
def compute_K_numerical(dataframe, settings=None, keep_dir=None): """Use a finite-element modeling code to infer geometric factors for meshes with topography or irregular electrode spacings. Parameters ---------- dataframe : pandas.DataFrame the data frame that contains the data setting...
[ "def", "compute_K_numerical", "(", "dataframe", ",", "settings", "=", "None", ",", "keep_dir", "=", "None", ")", ":", "inversion_code", "=", "reda", ".", "rcParams", ".", "get", "(", "'geom_factor.inversion_code'", ",", "'crtomo'", ")", "if", "inversion_code", ...
29.065217
0.000724
def make_password(password, encoding='BCRYPT'): """ Make a password with PLAIN, SSHA or BCRYPT (default) encoding. >>> make_password('foo', encoding='PLAIN') '{PLAIN}foo' >>> make_password(u're-foo', encoding='SSHA')[:6] '{SSHA}' >>> make_password(u're-foo')[:8] '{BCRYPT}' >>> make_...
[ "def", "make_password", "(", "password", ",", "encoding", "=", "'BCRYPT'", ")", ":", "if", "encoding", "not", "in", "[", "'PLAIN'", ",", "'SSHA'", ",", "'BCRYPT'", "]", ":", "raise", "ValueError", "(", "\"Unknown encoding %s\"", "%", "encoding", ")", "if", ...
42.288889
0.002054
def min_geodetic_distance(a, b): """ Compute the minimum distance between first mesh and each point of the second mesh when both are defined on the earth surface. :param a: a pair of (lons, lats) or an array of cartesian coordinates :param b: a pair of (lons, lats) or an array of cartesian coordina...
[ "def", "min_geodetic_distance", "(", "a", ",", "b", ")", ":", "if", "isinstance", "(", "a", ",", "tuple", ")", ":", "a", "=", "spherical_to_cartesian", "(", "a", "[", "0", "]", ".", "flatten", "(", ")", ",", "a", "[", "1", "]", ".", "flatten", "(...
42
0.001792
def diagnose(df,preview_rows = 2, display_max_cols = 0,display_width = None): """ Prints information about the DataFrame pertinent to data cleaning. Parameters ---------- df - DataFrame The DataFrame to summarize preview_rows - int, default 5 Amount of rows to preview f...
[ "def", "diagnose", "(", "df", ",", "preview_rows", "=", "2", ",", "display_max_cols", "=", "0", ",", "display_width", "=", "None", ")", ":", "assert", "type", "(", "df", ")", "is", "pd", ".", "DataFrame", "# Diagnose problems with the data formats that can be ad...
38.527778
0.02355
def get_lrc(self, playingsong): """ 获取歌词 如果测试频繁会发如下信息: {'msg': 'You API access rate limit has been exceeded. Contact api-master@douban.com if you want higher limit. ', 'code': 1998, 'request': 'GET /j/v2/lyric'} """ try: url...
[ "def", "get_lrc", "(", "self", ",", "playingsong", ")", ":", "try", ":", "url", "=", "\"https://douban.fm/j/v2/lyric\"", "postdata", "=", "{", "'sid'", ":", "playingsong", "[", "'sid'", "]", ",", "'ssid'", ":", "playingsong", "[", "'ssid'", "]", ",", "}", ...
34.95
0.001392
def envify(app=None, add_repo_to_path=True): """ This will simply activate virtualenv on openshift ans returs the app in a wsgi.py or app.py in your openshift python web app - wsgi.py from shiftpy.wsgi_utils import envify from myproject import app # wsgi expects an object named 'application...
[ "def", "envify", "(", "app", "=", "None", ",", "add_repo_to_path", "=", "True", ")", ":", "if", "getvar", "(", "'HOMEDIR'", ")", ":", "if", "add_repo_to_path", ":", "sys", ".", "path", ".", "append", "(", "os", ".", "path", ".", "join", "(", "getvar"...
32.3125
0.000939
def find_all_paths(G, start, end, path=[]): """ Find all paths between vertices start and end in graph. """ path = path + [start] if start == end: return [path] if start not in G.vertices: raise GraphInsertError("Vertex %s doesn't exist." % (start,)) if end not in G....
[ "def", "find_all_paths", "(", "G", ",", "start", ",", "end", ",", "path", "=", "[", "]", ")", ":", "path", "=", "path", "+", "[", "start", "]", "if", "start", "==", "end", ":", "return", "[", "path", "]", "if", "start", "not", "in", "G", ".", ...
34.611111
0.001563
def finish(self): "End this session" log.debug("Session disconnected.") try: self.sock.shutdown(socket.SHUT_RDWR) except: pass self.session_end()
[ "def", "finish", "(", "self", ")", ":", "log", ".", "debug", "(", "\"Session disconnected.\"", ")", "try", ":", "self", ".", "sock", ".", "shutdown", "(", "socket", ".", "SHUT_RDWR", ")", "except", ":", "pass", "self", ".", "session_end", "(", ")" ]
27.285714
0.020305
def fingerprint(self, field_keys=None): """A memoizing fingerprint that rolls together the fingerprints of underlying PayloadFields. If no fields were hashed (or all fields opted out of being hashed by returning `None`), then `fingerprint()` also returns `None`. :param iterable<string> field_keys: A s...
[ "def", "fingerprint", "(", "self", ",", "field_keys", "=", "None", ")", ":", "field_keys", "=", "frozenset", "(", "field_keys", "or", "self", ".", "_fields", ".", "keys", "(", ")", ")", "if", "field_keys", "not", "in", "self", ".", "_fingerprint_memo_map",...
51.846154
0.008746
def modify_db_instance(name, allocated_storage=None, allow_major_version_upgrade=None, apply_immediately=None, auto_minor_version_upgrade=None, backup_retention_period=None, ca_certi...
[ "def", "modify_db_instance", "(", "name", ",", "allocated_storage", "=", "None", ",", "allow_major_version_upgrade", "=", "None", ",", "apply_immediately", "=", "None", ",", "auto_minor_version_upgrade", "=", "None", ",", "backup_retention_period", "=", "None", ",", ...
42.546667
0.000919
def isQualified(self): """ Local elements can be qualified or unqualifed according to the attribute form, or the elementFormDefault. By default local elements are unqualified. """ form = self.getAttribute('form') if form == 'qualified': return True if...
[ "def", "isQualified", "(", "self", ")", ":", "form", "=", "self", ".", "getAttribute", "(", "'form'", ")", "if", "form", "==", "'qualified'", ":", "return", "True", "if", "form", "==", "'unqualified'", ":", "return", "False", "raise", "SchemaError", ",", ...
37.083333
0.010965
def control(self): """the type of control this player exhibits""" if self.isComputer: value = c.COMPUTER else: value = c.PARTICIPANT return c.PlayerControls(value)
[ "def", "control", "(", "self", ")", ":", "if", "self", ".", "isComputer", ":", "value", "=", "c", ".", "COMPUTER", "else", ":", "value", "=", "c", ".", "PARTICIPANT", "return", "c", ".", "PlayerControls", "(", "value", ")" ]
42.6
0.023041
def _create_tag_lowlevel(self, tag_name, message=None, force=True, patch=False): """Create a tag on the toplevel or patch repo If the tag exists, and force is False, no tag is made. If force is True, and a tag exists, but it is a direct ancestor of the current commi...
[ "def", "_create_tag_lowlevel", "(", "self", ",", "tag_name", ",", "message", "=", "None", ",", "force", "=", "True", ",", "patch", "=", "False", ")", ":", "# check if tag already exists, and if it does, if it is a direct", "# ancestor, and there is NO difference in the file...
46.037037
0.001575
def list_dhcp_agent_hosting_networks(self, network, **_params): """Fetches a list of dhcp agents hosting a network.""" return self.get((self.network_path + self.DHCP_AGENTS) % network, params=_params)
[ "def", "list_dhcp_agent_hosting_networks", "(", "self", ",", "network", ",", "*", "*", "_params", ")", ":", "return", "self", ".", "get", "(", "(", "self", ".", "network_path", "+", "self", ".", "DHCP_AGENTS", ")", "%", "network", ",", "params", "=", "_p...
59.25
0.008333
def add_to_fields(self): '''Add this :class:`Field` to the fields of :attr:`model`.''' meta = self.model._meta meta.scalarfields.append(self) if self.index: meta.indices.append(self)
[ "def", "add_to_fields", "(", "self", ")", ":", "meta", "=", "self", ".", "model", ".", "_meta", "meta", ".", "scalarfields", ".", "append", "(", "self", ")", "if", "self", ".", "index", ":", "meta", ".", "indices", ".", "append", "(", "self", ")" ]
36.833333
0.00885
def add_the_init(root_dir, data): """Append the new dataset file to the __init__.py.""" init_file = os.path.join(root_dir, '{dataset_type}', '__init__.py') context = ( 'from tensorflow_datasets.{dataset_type}.{dataset_name} import ' '{dataset_cls} # {TODO} Sort alphabetically\n' ) with gfile.GFil...
[ "def", "add_the_init", "(", "root_dir", ",", "data", ")", ":", "init_file", "=", "os", ".", "path", ".", "join", "(", "root_dir", ",", "'{dataset_type}'", ",", "'__init__.py'", ")", "context", "=", "(", "'from tensorflow_datasets.{dataset_type}.{dataset_name} import...
42.888889
0.01269
def compose(lead, medi, tail=0): """ Compose hangul using given consonant and vowel :param lead: lead consonant :param medi: medial vowel :param tail: tail consonant if any :return: composed hangul character """ tail_remainder = None lead = JA_LEAD.index(lead) * 588 medi = MO....
[ "def", "compose", "(", "lead", ",", "medi", ",", "tail", "=", "0", ")", ":", "tail_remainder", "=", "None", "lead", "=", "JA_LEAD", ".", "index", "(", "lead", ")", "*", "588", "medi", "=", "MO", ".", "index", "(", "medi", ")", "*", "28", "if", ...
27.809524
0.001656
def toposort_flatten(data, sort=True): """Returns a single list of dependencies. For any set returned by toposort(), those items are sorted and appended to the result (just to make the results deterministic).""" result = [] for d in toposort(data): try: result.extend((sorted if sort els...
[ "def", "toposort_flatten", "(", "data", ",", "sort", "=", "True", ")", ":", "result", "=", "[", "]", "for", "d", "in", "toposort", "(", "data", ")", ":", "try", ":", "result", ".", "extend", "(", "(", "sorted", "if", "sort", "else", "list", ")", ...
33.666667
0.00241
def contribute_to_related_class(self, cls, related): """ Called at class type creation. So, this method is called, when metaclasses get created """ super(VersionedManyToManyField, self). \ contribute_to_related_class(cls, related) accessor_name = related.get_a...
[ "def", "contribute_to_related_class", "(", "self", ",", "cls", ",", "related", ")", ":", "super", "(", "VersionedManyToManyField", ",", "self", ")", ".", "contribute_to_related_class", "(", "cls", ",", "related", ")", "accessor_name", "=", "related", ".", "get_a...
49.1875
0.002494
def pkg_manager_install( self, package_names=None, production=None, development=None, args=(), env={}, **kw): """ This will install all dependencies into the current working directory for the specific Python package from the selected JavaScript package...
[ "def", "pkg_manager_install", "(", "self", ",", "package_names", "=", "None", ",", "production", "=", "None", ",", "development", "=", "None", ",", "args", "=", "(", ")", ",", "env", "=", "{", "}", ",", "*", "*", "kw", ")", ":", "if", "not", "packa...
39.406593
0.000544
def concentrations(self, complexes, concs, ordered=False, pairs=False, cutoff=0.001, temp=37.0): ''' :param complexes: A list of the type returned by the complexes() method. :type complexes: list :param concs: The concentration(s) of each ...
[ "def", "concentrations", "(", "self", ",", "complexes", ",", "concs", ",", "ordered", "=", "False", ",", "pairs", "=", "False", ",", "cutoff", "=", "0.001", ",", "temp", "=", "37.0", ")", ":", "# Check inputs", "nstrands", "=", "len", "(", "complexes", ...
40.425532
0.001284
def _format_event(self, orig_event, external_metadata=None): """ Format the event to the expected Alooma format, packing it into a message field and adding metadata :param orig_event: The original event that was sent, should be dict, str or unic...
[ "def", "_format_event", "(", "self", ",", "orig_event", ",", "external_metadata", "=", "None", ")", ":", "event_wrapper", "=", "{", "}", "# Add ISO6801 timestamp and frame info", "timestamp", "=", "datetime", ".", "datetime", ".", "utcnow", "(", ")", ".", "isofo...
42.190476
0.001655
def scrypt_mcf(password, salt=None, N=SCRYPT_N, r=SCRYPT_r, p=SCRYPT_p, prefix=SCRYPT_MCF_PREFIX_DEFAULT): """Derives a Modular Crypt Format hash using the scrypt KDF Parameter space is smaller than for scrypt(): N must be a power of two larger than 1 but no larger than 2 ** 31 r and p m...
[ "def", "scrypt_mcf", "(", "password", ",", "salt", "=", "None", ",", "N", "=", "SCRYPT_N", ",", "r", "=", "SCRYPT_r", ",", "p", "=", "SCRYPT_p", ",", "prefix", "=", "SCRYPT_MCF_PREFIX_DEFAULT", ")", ":", "return", "mcf_mod", ".", "scrypt_mcf", "(", "scry...
46.166667
0.00177
def current_time(self) -> datetime: """Extract current time.""" _date = datetime.strptime(self.obj.SBRes.SBReq.StartT.get("date"), "%Y%m%d") _time = datetime.strptime(self.obj.SBRes.SBReq.StartT.get("time"), "%H:%M") return datetime.combine(_date.date(), _time.time())
[ "def", "current_time", "(", "self", ")", "->", "datetime", ":", "_date", "=", "datetime", ".", "strptime", "(", "self", ".", "obj", ".", "SBRes", ".", "SBReq", ".", "StartT", ".", "get", "(", "\"date\"", ")", ",", "\"%Y%m%d\"", ")", "_time", "=", "da...
59.2
0.013333
def get_key(key_name, value_name, jsonify, no_decrypt, stash, passphrase, backend): """Retrieve a key from the stash \b `KEY_NAME` is the name of the key to retrieve `VALUE_NAME` is a single value to retrieve e.g. if the value ...
[ "def", "get_key", "(", "key_name", ",", "value_name", ",", "jsonify", ",", "no_decrypt", ",", "stash", ",", "passphrase", ",", "backend", ")", ":", "if", "value_name", "and", "no_decrypt", ":", "sys", ".", "exit", "(", "'VALUE_NAME cannot be used in conjuction w...
29.658537
0.000796
def simulate(self, time, feedforwardInputI, feedforwardInputE, v, recurrent=True, dt=None, envelope=False, inputNoise=None): """ :param time: Amount of time to simulate. Divided into chunks of len...
[ "def", "simulate", "(", "self", ",", "time", ",", "feedforwardInputI", ",", "feedforwardInputE", ",", "v", ",", "recurrent", "=", "True", ",", "dt", "=", "None", ",", "envelope", "=", "False", ",", "inputNoise", "=", "None", ")", ":", "# Set up plotting", ...
32.246914
0.013001
def envGetList(self, name, attr_regex = '^\w+$', conv=None): """Parse the plugin environment variables to return list from variable with name list_<name>. The value of the variable must be a comma separated list of items. @param name: Name of list. ...
[ "def", "envGetList", "(", "self", ",", "name", ",", "attr_regex", "=", "'^\\w+$'", ",", "conv", "=", "None", ")", ":", "key", "=", "\"list_%s\"", "%", "name", "item_list", "=", "[", "]", "if", "self", ".", "_env", ".", "has_key", "(", "key", ")", "...
42.1
0.010062
def pickle_with_weak_refs( o ): """ Pickles an object containing weak references. :param mixed o: Any object :rtype str: The pickled object """ if isinstance(o, types.GeneratorType): o = [i for i in o] walk = dict([ (path,val) for path, val in objwalk(o)]) for path, val in walk...
[ "def", "pickle_with_weak_refs", "(", "o", ")", ":", "if", "isinstance", "(", "o", ",", "types", ".", "GeneratorType", ")", ":", "o", "=", "[", "i", "for", "i", "in", "o", "]", "walk", "=", "dict", "(", "[", "(", "path", ",", "val", ")", "for", ...
32.235294
0.014184
def get_border_phase(self, idn=0, idr=0): """Return one of nine border fields Parameters ---------- idn: int Index for refractive index. One of -1 (left), 0 (center), 1 (right) idr: int Index for radius. One of -1 (left), 0 (center...
[ "def", "get_border_phase", "(", "self", ",", "idn", "=", "0", ",", "idr", "=", "0", ")", ":", "assert", "idn", "in", "[", "-", "1", ",", "0", ",", "1", "]", "assert", "idr", "in", "[", "-", "1", ",", "0", ",", "1", "]", "n", "=", "self", ...
35.659091
0.001241
def setup_logging(namespace): """ setup global logging """ loglevel = { 0: logging.ERROR, 1: logging.WARNING, 2: logging.INFO, 3: logging.DEBUG, }.get(namespace.verbosity, logging.DEBUG) if namespace.verbosity > 1: logformat = '%(levelname)s csvpandas %(...
[ "def", "setup_logging", "(", "namespace", ")", ":", "loglevel", "=", "{", "0", ":", "logging", ".", "ERROR", ",", "1", ":", "logging", ".", "WARNING", ",", "2", ":", "logging", ".", "INFO", ",", "3", ":", "logging", ".", "DEBUG", ",", "}", ".", "...
25.5
0.002101
def __get_html(self, body=None): """ Returns the html content with given body tag content. :param body: Body tag content. :type body: unicode :return: Html. :rtype: unicode """ output = [] output.append("<html>") output.append("<head>") ...
[ "def", "__get_html", "(", "self", ",", "body", "=", "None", ")", ":", "output", "=", "[", "]", "output", ".", "append", "(", "\"<html>\"", ")", "output", ".", "append", "(", "\"<head>\"", ")", "for", "javascript", "in", "(", "self", ".", "__jquery_java...
32.71875
0.001855
def create_channel( target, credentials=None, scopes=None, ssl_credentials=None, **kwargs ): """Create a secure channel with credentials. Args: target (str): The target service address in the format 'hostname:port'. credentials (google.auth.credentials.Credentials): The credentials. If ...
[ "def", "create_channel", "(", "target", ",", "credentials", "=", "None", ",", "scopes", "=", "None", ",", "ssl_credentials", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "credentials", "is", "None", ":", "credentials", ",", "_", "=", "google", ...
41.75
0.00045
def get_prefixes(self, ns_uri): """Gets (a copy of) the prefix set for the given namespace.""" ni = self.__lookup_uri(ns_uri) return ni.prefixes.copy()
[ "def", "get_prefixes", "(", "self", ",", "ns_uri", ")", ":", "ni", "=", "self", ".", "__lookup_uri", "(", "ns_uri", ")", "return", "ni", ".", "prefixes", ".", "copy", "(", ")" ]
43
0.011429
def reset_tasks(self, request, context): """Resets all captured tasks.""" _log_request(request, context) self.listener.memory.clear_tasks() return clearly_pb2.Empty()
[ "def", "reset_tasks", "(", "self", ",", "request", ",", "context", ")", ":", "_log_request", "(", "request", ",", "context", ")", "self", ".", "listener", ".", "memory", ".", "clear_tasks", "(", ")", "return", "clearly_pb2", ".", "Empty", "(", ")" ]
38.8
0.010101
def _sorted_keys(self, keys): """Sort keys, dropping the ones that should be ignored. The keys that are in ``self.ignored_keys`` or that end on '_best' are dropped. Among the remaining keys: * 'epoch' is put first; * 'dur' is put last; * keys that start with 'event...
[ "def", "_sorted_keys", "(", "self", ",", "keys", ")", ":", "sorted_keys", "=", "[", "]", "if", "(", "'epoch'", "in", "keys", ")", "and", "(", "'epoch'", "not", "in", "self", ".", "keys_ignored_", ")", ":", "sorted_keys", ".", "append", "(", "'epoch'", ...
38.206897
0.001761
def sum(self, values): """ Calculates the total values for the inputed values. :return <int> """ values = sorted(values) try: return (values[-1] - values[0]).total_seconds() except IndexError, TypeError: return 0
[ "def", "sum", "(", "self", ",", "values", ")", ":", "values", "=", "sorted", "(", "values", ")", "try", ":", "return", "(", "values", "[", "-", "1", "]", "-", "values", "[", "0", "]", ")", ".", "total_seconds", "(", ")", "except", "IndexError", "...
27.727273
0.009524
def _get_window_data(self, data, asset, window_length): """ Internal utility method to return the trailing mean volume over the past 'window_length' days, and volatility of close prices for a specific asset. Parameters ---------- data : The BarData from which to ...
[ "def", "_get_window_data", "(", "self", ",", "data", ",", "asset", ",", "window_length", ")", ":", "try", ":", "values", "=", "self", ".", "_window_data_cache", ".", "get", "(", "asset", ",", "data", ".", "current_session", ")", "except", "KeyError", ":", ...
38.565217
0.0011
def __search(self): """ Performs the search. """ self.__search_results = [] editorsFiles = self.__container.default_target in self.__location.targets and \ [editor.file for editor in self.__container.script_editor.list_editors()] or [] self.__sear...
[ "def", "__search", "(", "self", ")", ":", "self", ".", "__search_results", "=", "[", "]", "editorsFiles", "=", "self", ".", "__container", ".", "default_target", "in", "self", ".", "__location", ".", "targets", "and", "[", "editor", ".", "file", "for", "...
43.52
0.008993
def _fonts2pys(self): """Writes fonts to pys file""" # Get mapping from fonts to fontfiles system_fonts = font_manager.findSystemFonts() font_name2font_file = {} for sys_font in system_fonts: font_name = font_manager.FontProperties(fname=sys_font).get_name() ...
[ "def", "_fonts2pys", "(", "self", ")", ":", "# Get mapping from fonts to fontfiles", "system_fonts", "=", "font_manager", ".", "findSystemFonts", "(", ")", "font_name2font_file", "=", "{", "}", "for", "sys_font", "in", "system_fonts", ":", "font_name", "=", "font_ma...
38
0.002232
def bind_fields_to_model_cls(cls, model_fields): """Bind fields to model class.""" return dict( (field.name, field.bind_model_cls(cls)) for field in model_fields)
[ "def", "bind_fields_to_model_cls", "(", "cls", ",", "model_fields", ")", ":", "return", "dict", "(", "(", "field", ".", "name", ",", "field", ".", "bind_model_cls", "(", "cls", ")", ")", "for", "field", "in", "model_fields", ")" ]
46.75
0.010526
def stereonet2xyz(lon, lat): """ Converts a sequence of longitudes and latitudes from a lower-hemisphere stereonet into _world_ x,y,z coordinates. Parameters ---------- lon, lat : array-likes Sequences of longitudes and latitudes (in radians) from a lower-hemisphere stereonet ...
[ "def", "stereonet2xyz", "(", "lon", ",", "lat", ")", ":", "lon", ",", "lat", "=", "np", ".", "atleast_1d", "(", "lon", ",", "lat", ")", "x", ",", "y", ",", "z", "=", "sph2cart", "(", "lon", ",", "lat", ")", "return", "y", ",", "z", ",", "-", ...
28
0.001727
def neto(fastas, algorithm = 'usearch', e = 0.01, bit = 40, length = .65, norm_bit = False): """ make and split a rbh network """ thresholds = [e, bit, length, norm_bit] id2desc = get_descriptions(fastas) # get [fasta, description, length] for ORF id id2desc = self_compare(fastas, id...
[ "def", "neto", "(", "fastas", ",", "algorithm", "=", "'usearch'", ",", "e", "=", "0.01", ",", "bit", "=", "40", ",", "length", "=", ".65", ",", "norm_bit", "=", "False", ")", ":", "thresholds", "=", "[", "e", ",", "bit", ",", "length", ",", "norm...
65.133333
0.025214
def str_to_timedelta(value): """Convert a string to a datetime.timedelta value. The following strings are accepted: - 'datetime.timedelta(1, 5, 12345)' - 'timedelta(1, 5, 12345)' - '(1, 5, 12345)' - '1, 5, 12345' - '1' if there are less then three parameters, the m...
[ "def", "str_to_timedelta", "(", "value", ")", ":", "m", "=", "re", ".", "match", "(", "r'^(?:(?:datetime\\.)?timedelta)?'", "r'\\(?'", "r'([^)]*)'", "r'\\)?$'", ",", "value", ")", "if", "not", "m", ":", "raise", "ValueError", "(", "'Invalid string for datetime.tim...
30.5
0.001222
def get_checksum(self): """ Returns a checksum based on the IDL that ignores comments and ordering, but detects changes to types, parameter order, and enum values. """ arr = [ ] for elem in self.parsed: s = elem_checksum(elem) if s: ...
[ "def", "get_checksum", "(", "self", ")", ":", "arr", "=", "[", "]", "for", "elem", "in", "self", ".", "parsed", ":", "s", "=", "elem_checksum", "(", "elem", ")", "if", "s", ":", "arr", ".", "append", "(", "s", ")", "arr", ".", "sort", "(", ")",...
28.928571
0.014354
def register(self, module, *args, **kwargs): """ Register a new module. :param module: Either a string module name, or a module class, or a module instance (in which case args and kwargs are invalid). :param kwargs: Settings for the module. ...
[ "def", "register", "(", "self", ",", "module", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "from", "i3pystatus", ".", "text", "import", "Text", "if", "not", "module", ":", "return", "# Merge the module's hints with the default hints", "# and overwrite a...
33.588235
0.001702
def props_to_image(regionprops, shape, prop): r""" Creates an image with each region colored according the specified ``prop``, as obtained by ``regionprops_3d``. Parameters ---------- regionprops : list This is a list of properties for each region that is computed by PoreSpy's `...
[ "def", "props_to_image", "(", "regionprops", ",", "shape", ",", "prop", ")", ":", "im", "=", "sp", ".", "zeros", "(", "shape", "=", "shape", ")", "for", "r", "in", "regionprops", ":", "if", "prop", "==", "'convex'", ":", "mask", "=", "r", ".", "con...
30.238095
0.000763
def srv_event(token, hits, url=RBA_URL): """Serve event to RainbowAlga""" if url is None: log.error("Please provide a valid RainbowAlga URL.") return ws_url = url + '/message' if isinstance(hits, pd.core.frame.DataFrame): pos = [tuple(x) for x in hits[['x', 'y', 'z']].values] ...
[ "def", "srv_event", "(", "token", ",", "hits", ",", "url", "=", "RBA_URL", ")", ":", "if", "url", "is", "None", ":", "log", ".", "error", "(", "\"Please provide a valid RainbowAlga URL.\"", ")", "return", "ws_url", "=", "url", "+", "'/message'", "if", "isi...
24.823529
0.00114
def read_logodata(handle): """Get weblogo data for a sequence alignment. Returns a list of tuples: (posn, letter_counts, entropy, weight) """ seqs = weblogolib.read_seq_data(handle, alphabet=unambiguous_protein_alphabet) ldata = weblogolib.LogoData.from_seqs(seqs...
[ "def", "read_logodata", "(", "handle", ")", ":", "seqs", "=", "weblogolib", ".", "read_seq_data", "(", "handle", ",", "alphabet", "=", "unambiguous_protein_alphabet", ")", "ldata", "=", "weblogolib", ".", "LogoData", ".", "from_seqs", "(", "seqs", ")", "letter...
41.705882
0.001379
def edit(self): """ Edits the usage report. To edit a usage report, you need to submit the complete JSON representation of the usage report which includes updates to the usage report properties. The name of the report cannot be changed when editing the usage report. Valu...
[ "def", "edit", "(", "self", ")", ":", "usagereport_dict", "=", "{", "\"reportname\"", ":", "self", ".", "reportname", ",", "\"queries\"", ":", "self", ".", "_queries", ",", "\"since\"", ":", "self", ".", "since", ",", "\"metadata\"", ":", "self", ".", "_...
35.735294
0.008814
def cluster_setup(name, nodes, pcsclustername='pcscluster', extra_args=None): ''' Setup Pacemaker cluster on nodes. Should be run on one cluster node only (there may be races) name Irrelevant, not used (recommended: pcs_setup__setup) nodes a list of nodes which should be set up ...
[ "def", "cluster_setup", "(", "name", ",", "nodes", ",", "pcsclustername", "=", "'pcscluster'", ",", "extra_args", "=", "None", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'result'", ":", "True", ",", "'comment'", ":", "''", ",", "'changes'", ...
32.965517
0.001693
def find(self, other): """Return an interable of elements that overlap other in the tree.""" iset = self._iset l = binsearch_left_start(iset, other[0] - self._maxlen, 0, len(iset)) r = binsearch_right_end(iset, other[1], 0, len(iset)) iopts = iset[l:r] iiter = (s for s in...
[ "def", "find", "(", "self", ",", "other", ")", ":", "iset", "=", "self", ".", "_iset", "l", "=", "binsearch_left_start", "(", "iset", ",", "other", "[", "0", "]", "-", "self", ".", "_maxlen", ",", "0", ",", "len", "(", "iset", ")", ")", "r", "=...
49.125
0.01
def display_items(self) -> typing.List[Display]: """Return the list of display items. :return: The list of :py:class:`nion.swift.Facade.Display` objects. .. versionadded:: 1.0 Scriptable: Yes """ return [Display(display_item) for display_item in self.__document_model.d...
[ "def", "display_items", "(", "self", ")", "->", "typing", ".", "List", "[", "Display", "]", ":", "return", "[", "Display", "(", "display_item", ")", "for", "display_item", "in", "self", ".", "__document_model", ".", "display_items", "]" ]
32.4
0.009009
def fit_doublegauss_samples(samples,**kwargs): """Fits a two-sided Gaussian to a set of samples. Calculates 0.16, 0.5, and 0.84 quantiles and passes these to `fit_doublegauss` for fitting. Parameters ---------- samples : array-like Samples to which to fit the Gaussian. kwargs ...
[ "def", "fit_doublegauss_samples", "(", "samples", ",", "*", "*", "kwargs", ")", ":", "sorted_samples", "=", "np", ".", "sort", "(", "samples", ")", "N", "=", "len", "(", "samples", ")", "med", "=", "sorted_samples", "[", "N", "/", "2", "]", "siglo", ...
30.25
0.009615
def start_response(self, status = 200, headers = [], clearheaders = True, disabletransferencoding = False): "Start to send response" if self._sendHeaders: raise HttpProtocolException('Cannot modify response, headers already sent') self.status = status self.disabledeflate = di...
[ "def", "start_response", "(", "self", ",", "status", "=", "200", ",", "headers", "=", "[", "]", ",", "clearheaders", "=", "True", ",", "disabletransferencoding", "=", "False", ")", ":", "if", "self", ".", "_sendHeaders", ":", "raise", "HttpProtocolException"...
46
0.025586
def make_plot(self): """Draw the plot on the figure attribute Uses matplotlib to draw and format the chart """ X, Y, DX, DY = self._calc_partials() # Plot the values self.figure = plt.Figure() axes = self.figure.add_subplot(1, 1, 1) axes....
[ "def", "make_plot", "(", "self", ")", ":", "X", ",", "Y", ",", "DX", ",", "DY", "=", "self", ".", "_calc_partials", "(", ")", "# Plot the values", "self", ".", "figure", "=", "plt", ".", "Figure", "(", ")", "axes", "=", "self", ".", "figure", ".", ...
37.866667
0.008591
def create_push_handlers(): """Create a handler for upload per package format.""" # pylint: disable=fixme # HACK: hacky territory - Dynamically generate a handler for each of the # package formats, until we have slightly more clever 'guess type' # handling. :-) handlers = create_push_handlers.ha...
[ "def", "create_push_handlers", "(", ")", ":", "# pylint: disable=fixme", "# HACK: hacky territory - Dynamically generate a handler for each of the", "# package formats, until we have slightly more clever 'guess type'", "# handling. :-)", "handlers", "=", "create_push_handlers", ".", "handl...
34.889655
0.000577
def all(self): """ Gets all saved queries for a project from the Keen IO API. Master key must be set. """ response = self._get_json(HTTPMethods.GET, self.saved_query_url, self._get_master_key()) return response
[ "def", "all", "(", "self", ")", ":", "response", "=", "self", ".", "_get_json", "(", "HTTPMethods", ".", "GET", ",", "self", ".", "saved_query_url", ",", "self", ".", "_get_master_key", "(", ")", ")", "return", "response" ]
28
0.011538
def get_rprof(step, var): """Extract or compute and rescale requested radial profile. Args: step (:class:`~stagpy.stagyydata._Step`): a step of a StagyyData instance. var (str): radial profile name, a key of :data:`stagpy.phyvars.RPROF` or :data:`stagpy.phyvars.RPROF_EXT...
[ "def", "get_rprof", "(", "step", ",", "var", ")", ":", "if", "var", "in", "step", ".", "rprof", ".", "columns", ":", "rprof", "=", "step", ".", "rprof", "[", "var", "]", "rad", "=", "None", "if", "var", "in", "phyvars", ".", "RPROF", ":", "meta",...
38.314286
0.000727
def all(self, data={}, **kwargs): """" Fetch all plan entities Returns: Dictionary of plan data """ return super(Plan, self).all(data, **kwargs)
[ "def", "all", "(", "self", ",", "data", "=", "{", "}", ",", "*", "*", "kwargs", ")", ":", "return", "super", "(", "Plan", ",", "self", ")", ".", "all", "(", "data", ",", "*", "*", "kwargs", ")" ]
23.75
0.010152
def calc_cat_clust_order(net, inst_rc): ''' cluster category subset of data ''' from .__init__ import Network from copy import deepcopy from . import calc_clust, run_filter inst_keys = list(net.dat['node_info'][inst_rc].keys()) all_cats = [x for x in inst_keys if 'cat-' in x] if len(all_cats) > 0: ...
[ "def", "calc_cat_clust_order", "(", "net", ",", "inst_rc", ")", ":", "from", ".", "__init__", "import", "Network", "from", "copy", "import", "deepcopy", "from", ".", "import", "calc_clust", ",", "run_filter", "inst_keys", "=", "list", "(", "net", ".", "dat",...
31.326531
0.019577
def get_distance(F, x): """Helper function for margin-based loss. Return a distance matrix given a matrix.""" n = x.shape[0] square = F.sum(x ** 2.0, axis=1, keepdims=True) distance_square = square + square.transpose() - (2.0 * F.dot(x, x.transpose())) # Adding identity to make sqrt work. retu...
[ "def", "get_distance", "(", "F", ",", "x", ")", ":", "n", "=", "x", ".", "shape", "[", "0", "]", "square", "=", "F", ".", "sum", "(", "x", "**", "2.0", ",", "axis", "=", "1", ",", "keepdims", "=", "True", ")", "distance_square", "=", "square", ...
40.444444
0.008065
def ReleaseSW(self): ' Go away from Limit Switch ' while self.ReadStatusBit(2) == 1: # is Limit Switch ON ? spi.SPI_write(self.CS, [0x92, 0x92] | (~self.Dir & 1)) # release SW while self.IsBusy(): pass self.MoveWait(10)
[ "def", "ReleaseSW", "(", "self", ")", ":", "while", "self", ".", "ReadStatusBit", "(", "2", ")", "==", "1", ":", "# is Limit Switch ON ?", "spi", ".", "SPI_write", "(", "self", ".", "CS", ",", "[", "0x92", ",", "0x92", "]", "|", "(", "~", "self", "...
42.285714
0.013245
def down(self): """ Move this object down one position. """ self.swap(self.get_ordering_queryset().filter(order__gt=self.order))
[ "def", "down", "(", "self", ")", ":", "self", ".", "swap", "(", "self", ".", "get_ordering_queryset", "(", ")", ".", "filter", "(", "order__gt", "=", "self", ".", "order", ")", ")" ]
31.2
0.0125
def clip(attrs, inputs, proto_obj): """Clips (limits) the values in an array.""" new_attrs = translation_utils._fix_attribute_names(attrs, {'min' : 'a_min', 'max' : 'a_max'}) if 'a_max' not in new_attrs: new_attrs = translation_utils._ad...
[ "def", "clip", "(", "attrs", ",", "inputs", ",", "proto_obj", ")", ":", "new_attrs", "=", "translation_utils", ".", "_fix_attribute_names", "(", "attrs", ",", "{", "'min'", ":", "'a_min'", ",", "'max'", ":", "'a_max'", "}", ")", "if", "'a_max'", "not", "...
58.111111
0.015066