text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def resume(self): """ Resumes the thread execution. @rtype: int @return: Suspend count. If zero, the thread is running. """ hThread = self.get_handle(win32.THREAD_SUSPEND_RESUME) return win32.ResumeThread(hThread)
[ "def", "resume", "(", "self", ")", ":", "hThread", "=", "self", ".", "get_handle", "(", "win32", ".", "THREAD_SUSPEND_RESUME", ")", "return", "win32", ".", "ResumeThread", "(", "hThread", ")" ]
29.222222
0.00738
def init(cls, site): """ put site settings in the header of the script """ bash_header = "" for k,v in site.items(): bash_header += "%s=%s" % (k.upper(), v) bash_header += '\n' site['bash_header'] = bash_header # TODO: execute before_deplo...
[ "def", "init", "(", "cls", ",", "site", ")", ":", "bash_header", "=", "\"\"", "for", "k", ",", "v", "in", "site", ".", "items", "(", ")", ":", "bash_header", "+=", "\"%s=%s\"", "%", "(", "k", ".", "upper", "(", ")", ",", "v", ")", "bash_header", ...
41
0.00493
def shutdown_notebook(request, username): """Stop any running notebook for a user.""" manager = get_notebook_manager(request) if manager.is_running(username): manager.stop_notebook(username)
[ "def", "shutdown_notebook", "(", "request", ",", "username", ")", ":", "manager", "=", "get_notebook_manager", "(", "request", ")", "if", "manager", ".", "is_running", "(", "username", ")", ":", "manager", ".", "stop_notebook", "(", "username", ")" ]
34.333333
0.004739
def syllabify(word): '''Syllabify the given word, whether simplex or complex.''' compound = not word.isalpha() syllabify = _syllabify_complex if compound else _syllabify_simplex syllabifications = list(syllabify(word)) # if variation, order variants from most preferred to least preferred if len...
[ "def", "syllabify", "(", "word", ")", ":", "compound", "=", "not", "word", ".", "isalpha", "(", ")", "syllabify", "=", "_syllabify_complex", "if", "compound", "else", "_syllabify_simplex", "syllabifications", "=", "list", "(", "syllabify", "(", "word", ")", ...
38.75
0.002101
def compareKmerProfiles(profileFN1, profileFN2): ''' This function takes two kmer profiles and compare them for similarity. @param profileFN1 - the first kmer-profile to compare to @param profileFN2 - the second kmer-profile to compare to @return - a tuple of the form (1-norm, 2-norm, sum of differe...
[ "def", "compareKmerProfiles", "(", "profileFN1", ",", "profileFN2", ")", ":", "fp1", "=", "open", "(", "profileFN1", ",", "'r'", ")", "fp2", "=", "open", "(", "profileFN2", ",", "'r'", ")", "oneNorm", "=", "0", "twoNorm", "=", "0", "sumDeltas", "=", "0...
32.395833
0.010612
def stack(self, k=5, stratify=False, shuffle=True, seed=100, full_test=True, add_diff=False): """Stacks sequence of models. Parameters ---------- k : int, default 5 Number of folds. stratify : bool, default False shuffle : bool, default True seed : i...
[ "def", "stack", "(", "self", ",", "k", "=", "5", ",", "stratify", "=", "False", ",", "shuffle", "=", "True", ",", "seed", "=", "100", ",", "full_test", "=", "True", ",", "add_diff", "=", "False", ")", ":", "result_train", "=", "[", "]", "result_tes...
33.638298
0.004302
def append_partition_by_name_with_environment_context(self, db_name, tbl_name, part_name, environment_context): """ Parameters: - db_name - tbl_name - part_name - environment_context """ self.send_append_partition_by_name_with_environment_context(db_name, tbl_name, part_name, environ...
[ "def", "append_partition_by_name_with_environment_context", "(", "self", ",", "db_name", ",", "tbl_name", ",", "part_name", ",", "environment_context", ")", ":", "self", ".", "send_append_partition_by_name_with_environment_context", "(", "db_name", ",", "tbl_name", ",", "...
39.7
0.007389
def _remove_entry(self, source_file, key): """Remove an entry from the cache. source_file is the name of the header and key is its corresponding cache key (obtained by a call to :meth:_create_cache_key ). The entry is removed from the index table, any referenced file name is rel...
[ "def", "_remove_entry", "(", "self", ",", "source_file", ",", "key", ")", ":", "entry", "=", "self", ".", "__index", ".", "get", "(", "key", ")", "if", "entry", "is", "None", ":", "return", "# Release the referenced files...", "for", "id_", ",", "_", "in...
33.457143
0.00166
def batch_norm(self, input_layer=None, decay=0.999, scale=False, epsilon=0.001): """Adds a Batch Normalization layer.""" if input_layer is None: input_layer = self.top_layer else: self.top_size = ...
[ "def", "batch_norm", "(", "self", ",", "input_layer", "=", "None", ",", "decay", "=", "0.999", ",", "scale", "=", "False", ",", "epsilon", "=", "0.001", ")", ":", "if", "input_layer", "is", "None", ":", "input_layer", "=", "self", ".", "top_layer", "el...
36.5625
0.004996
async def get_next_match(self): """ Return the first open match found, or if none, the first pending match found |methcoro| Raises: APIException """ if self._final_rank is not None: return None matches = await self.get_matches(MatchState.open_)...
[ "async", "def", "get_next_match", "(", "self", ")", ":", "if", "self", ".", "_final_rank", "is", "not", "None", ":", "return", "None", "matches", "=", "await", "self", ".", "get_matches", "(", "MatchState", ".", "open_", ")", "if", "len", "(", "matches",...
22.714286
0.006036
def _parse_string_to_list_of_pairs(s, seconds_to_int=False): r"""Parses a string into a list of pairs. In the input string, each pair is separated by a colon, and the delimiters between pairs are any of " ,.;". e.g. "rows:32,cols:32" Args: s: str to parse. seconds_to_int: Boolean. If True, then the...
[ "def", "_parse_string_to_list_of_pairs", "(", "s", ",", "seconds_to_int", "=", "False", ")", ":", "ret", "=", "[", "]", "for", "p", "in", "[", "s", ".", "split", "(", "\":\"", ")", "for", "s", "in", "re", ".", "sub", "(", "\"[,.;]\"", ",", "\" \"", ...
26.75
0.010309
def get_data_or_download(dir_name, file_name, url='', size='unknown'): """Returns the data. if the data hasn't been downloaded, then first download the data. :param dir_name: directory to look in :param file_name: file name to retrieve :param url: if the file is not found, then download it from this ur...
[ "def", "get_data_or_download", "(", "dir_name", ",", "file_name", ",", "url", "=", "''", ",", "size", "=", "'unknown'", ")", ":", "dname", "=", "os", ".", "path", ".", "join", "(", "stanza", ".", "DATA_DIR", ",", "dir_name", ")", "fname", "=", "os", ...
50.7
0.00484
def competition_leaderboard_view(self, competition): """ view a leaderboard based on a competition name Parameters ========== competition: the competition name to view leadboard for """ result = self.process_response( self.competition_view_leaderb...
[ "def", "competition_leaderboard_view", "(", "self", ",", "competition", ")", ":", "result", "=", "self", ".", "process_response", "(", "self", ".", "competition_view_leaderboard_with_http_info", "(", "competition", ")", ")", "return", "[", "LeaderboardEntry", "(", "...
41.2
0.004751
def _fetch(self, method, args): """Fetch NNTP data from the server or from the archive :param method: the name of the command to execute :param args: the arguments required by the command """ if self.from_archive: data = self._fetch_from_archive(method, args) ...
[ "def", "_fetch", "(", "self", ",", "method", ",", "args", ")", ":", "if", "self", ".", "from_archive", ":", "data", "=", "self", ".", "_fetch_from_archive", "(", "method", ",", "args", ")", "else", ":", "data", "=", "self", ".", "_fetch_from_remote", "...
32.75
0.00495
def list_distinfo_files(self, absolute=False): """ Iterates over the ``installed-files.txt`` entries and returns paths for each line if the path is pointing to a file located in the ``.egg-info`` directory or one of its subdirectories. :parameter absolute: If *absolute* is ``Tru...
[ "def", "list_distinfo_files", "(", "self", ",", "absolute", "=", "False", ")", ":", "record_path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "path", ",", "'installed-files.txt'", ")", "if", "os", ".", "path", ".", "exists", "(", "record_path...
44.928571
0.001556
def CMS_label(text="Preliminary 2012", sqrts=8, pad=None): """ Add a 'CMS Preliminary' style label to the current Pad. The blurbs are drawn in the top margin. The label "CMS " + text is drawn in the upper left. If sqrts is None, it will be omitted. Otherwise, it will be drawn in the upper right. ...
[ "def", "CMS_label", "(", "text", "=", "\"Preliminary 2012\"", ",", "sqrts", "=", "8", ",", "pad", "=", "None", ")", ":", "if", "pad", "is", "None", ":", "pad", "=", "ROOT", ".", "gPad", "with", "preserve_current_canvas", "(", ")", ":", "pad", ".", "c...
34.722222
0.003113
def wait_instances_running(ec2, instances): """ Wait until no instance in the given iterable is 'pending'. Yield every instance that entered the running state as soon as it does. :param boto.ec2.connection.EC2Connection ec2: the EC2 connection to use for making requests :param Iterator[Instance] in...
[ "def", "wait_instances_running", "(", "ec2", ",", "instances", ")", ":", "running_ids", "=", "set", "(", ")", "other_ids", "=", "set", "(", ")", "while", "True", ":", "pending_ids", "=", "set", "(", ")", "for", "i", "in", "instances", ":", "if", "i", ...
37.823529
0.002274
def is_same(type1, type2): """returns True, if type1 and type2 are same types""" nake_type1 = remove_declarated(type1) nake_type2 = remove_declarated(type2) return nake_type1 == nake_type2
[ "def", "is_same", "(", "type1", ",", "type2", ")", ":", "nake_type1", "=", "remove_declarated", "(", "type1", ")", "nake_type2", "=", "remove_declarated", "(", "type2", ")", "return", "nake_type1", "==", "nake_type2" ]
40
0.004902
def ask(question, default_answer=False, default_answer_str="no"): """ Ask for user input. This asks a yes/no question with a preset default. You can bypass the user-input and fetch the default answer, if you set Args: question: The question to ask on stdout. default_answer: The...
[ "def", "ask", "(", "question", ",", "default_answer", "=", "False", ",", "default_answer_str", "=", "\"no\"", ")", ":", "response", "=", "default_answer", "def", "should_ignore_tty", "(", ")", ":", "\"\"\"\n Check, if we want to ignore an opened tty result.\n ...
32.410256
0.000768
def convert_sav(inputfile, outputfile=None, method='rpy2', otype='csv'): """ Transforms the input .sav SPSS file into other format. If you don't specify an outputfile, it will use the inputfile and change its extension to .csv """ assert(os.path.isfile(inputfile)) assert(method=='rpy2' or method...
[ "def", "convert_sav", "(", "inputfile", ",", "outputfile", "=", "None", ",", "method", "=", "'rpy2'", ",", "otype", "=", "'csv'", ")", ":", "assert", "(", "os", ".", "path", ".", "isfile", "(", "inputfile", ")", ")", "assert", "(", "method", "==", "'...
31.47619
0.003668
def nationality(self, gender: Optional[Gender] = None) -> str: """Get a random nationality. :param gender: Gender. :return: Nationality. :Example: Russian """ nationalities = self._data['nationality'] # Separated by gender if isinstance(nati...
[ "def", "nationality", "(", "self", ",", "gender", ":", "Optional", "[", "Gender", "]", "=", "None", ")", "->", "str", ":", "nationalities", "=", "self", ".", "_data", "[", "'nationality'", "]", "# Separated by gender", "if", "isinstance", "(", "nationalities...
27.764706
0.004098
def credentials_from_session(session, client_config=None): """Creates :class:`google.oauth2.credentials.Credentials` from a :class:`requests_oauthlib.OAuth2Session`. :meth:`fetch_token` must be called on the session before before calling this. This uses the session's auth token and the provided client ...
[ "def", "credentials_from_session", "(", "session", ",", "client_config", "=", "None", ")", ":", "client_config", "=", "client_config", "if", "client_config", "is", "not", "None", "else", "{", "}", "if", "not", "session", ".", "token", ":", "raise", "ValueError...
41.075
0.000595
def _cmd(self, endpoint, cmd): """ endpoint is (host, port) """ cmdbuf = "%s\n" % (cmd) # some cmds have large outputs and ZK closes the connection as soon as it # finishes writing. so read in huge chunks. recvsize = 1 << 20 replies = [] host, port = endpoint ...
[ "def", "_cmd", "(", "self", ",", "endpoint", ",", "cmd", ")", ":", "cmdbuf", "=", "\"%s\\n\"", "%", "(", "cmd", ")", "# some cmds have large outputs and ZK closes the connection as soon as it", "# finishes writing. so read in huge chunks.", "recvsize", "=", "1", "<<", "...
35.066667
0.002775
def removc(item, inset): """ Remove an item from a character set. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/removc_c.html :param item: Item to be removed. :type item: str :param inset: Set to be updated. :type inset: spiceypy.utils.support_types.SpiceCell """ assert i...
[ "def", "removc", "(", "item", ",", "inset", ")", ":", "assert", "isinstance", "(", "inset", ",", "stypes", ".", "SpiceCell", ")", "assert", "inset", ".", "dtype", "==", "0", "item", "=", "stypes", ".", "stringToCharP", "(", "item", ")", "libspice", "."...
30.333333
0.002132
def visible_tile_layers(self): """Return iterator of layer indexes that are set 'visible' :rtype: Iterator """ return (i for (i, l) in enumerate(self.layers) if l.visible and isinstance(l, TiledTileLayer))
[ "def", "visible_tile_layers", "(", "self", ")", ":", "return", "(", "i", "for", "(", "i", ",", "l", ")", "in", "enumerate", "(", "self", ".", "layers", ")", "if", "l", ".", "visible", "and", "isinstance", "(", "l", ",", "TiledTileLayer", ")", ")" ]
35.428571
0.007874
def isSelfSigned(self): """ Return True if the certificate is self-signed: - issuer and subject are the same - the signature of the certificate is valid. """ if self.issuer_hash == self.subject_hash: return self.isIssuerCert(self) return False
[ "def", "isSelfSigned", "(", "self", ")", ":", "if", "self", ".", "issuer_hash", "==", "self", ".", "subject_hash", ":", "return", "self", ".", "isIssuerCert", "(", "self", ")", "return", "False" ]
34.111111
0.006349
def wsgi_handler(func): """ Set a instance method to be call as a wsgi application, adding common behavior and using webob.Request for practical use. @wsgi_handler def handle_verify_token(self, request): pass :param func: :return: """ @wraps(func) def inner(*args): ...
[ "def", "wsgi_handler", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "inner", "(", "*", "args", ")", ":", "self", ",", "environ", ",", "start_response", ",", "", "*", "args", "=", "args", "request", "=", "Request", "(", "environ", "...
21.148148
0.001675
def disasm_app(_parser, cmd, args): # pragma: no cover """ Disassemble code from commandline or stdin. """ parser = argparse.ArgumentParser( prog=_parser.prog, description=_parser.description, ) parser.add_argument('code', help='the code to disassemble, read from stdin if omitt...
[ "def", "disasm_app", "(", "_parser", ",", "cmd", ",", "args", ")", ":", "# pragma: no cover", "parser", "=", "argparse", ".", "ArgumentParser", "(", "prog", "=", "_parser", ".", "prog", ",", "description", "=", "_parser", ".", "description", ",", ")", "par...
29.914894
0.002755
def main(): """Command line interface for the ``update-dotdee`` program.""" # Initialize logging to the terminal and system log. coloredlogs.install(syslog=True) # Parse the command line arguments. context_opts = {} program_opts = {} try: options, arguments = getopt.getopt(sys.argv[1...
[ "def", "main", "(", ")", ":", "# Initialize logging to the terminal and system log.", "coloredlogs", ".", "install", "(", "syslog", "=", "True", ")", "# Parse the command line arguments.", "context_opts", "=", "{", "}", "program_opts", "=", "{", "}", "try", ":", "op...
38.276596
0.001084
def addNode(self, node): ''' Update the shared map with my in-construction node ''' self.mybldgbuids[node.buid] = node self.allbldgbuids[node.buid] = (node, self.doneevent)
[ "def", "addNode", "(", "self", ",", "node", ")", ":", "self", ".", "mybldgbuids", "[", "node", ".", "buid", "]", "=", "node", "self", ".", "allbldgbuids", "[", "node", ".", "buid", "]", "=", "(", "node", ",", "self", ".", "doneevent", ")" ]
34.5
0.009434
def bel_edges( self, nanopub: Mapping[str, Any], namespace_targets: Mapping[str, List[str]] = {}, rules: List[str] = [], orthologize_target: str = None, ) -> List[Mapping[str, Any]]: """Create BEL Edges from BEL nanopub Args: nanopub (Mapping[str,...
[ "def", "bel_edges", "(", "self", ",", "nanopub", ":", "Mapping", "[", "str", ",", "Any", "]", ",", "namespace_targets", ":", "Mapping", "[", "str", ",", "List", "[", "str", "]", "]", "=", "{", "}", ",", "rules", ":", "List", "[", "str", "]", "=",...
38.419355
0.007371
def count(self): """ Count the number of domain for each status. """ if self.status: # The status is parsed. # We increase the number of tested. PyFunceble.INTERN["counter"]["number"]["tested"] += 1 if ( self.status.lower...
[ "def", "count", "(", "self", ")", ":", "if", "self", ".", "status", ":", "# The status is parsed.", "# We increase the number of tested.", "PyFunceble", ".", "INTERN", "[", "\"counter\"", "]", "[", "\"number\"", "]", "[", "\"tested\"", "]", "+=", "1", "if", "(...
36.62069
0.001835
def adjustText(self): """ Updates the text based on the current format options. """ pos = self.cursorPosition() self.blockSignals(True) super(XLineEdit, self).setText(self.formatText(self.text())) self.setCursorPosition(pos) self.blockSignals(False)
[ "def", "adjustText", "(", "self", ")", ":", "pos", "=", "self", ".", "cursorPosition", "(", ")", "self", ".", "blockSignals", "(", "True", ")", "super", "(", "XLineEdit", ",", "self", ")", ".", "setText", "(", "self", ".", "formatText", "(", "self", ...
34.444444
0.006289
def handle_get_request(self, environ, start_response): """Handle a long-polling GET request from the client.""" connections = [ s.strip() for s in environ.get('HTTP_CONNECTION', '').lower().split(',')] transport = environ.get('HTTP_UPGRADE', '').lower() if 'upgrad...
[ "def", "handle_get_request", "(", "self", ",", "environ", ",", "start_response", ")", ":", "connections", "=", "[", "s", ".", "strip", "(", ")", "for", "s", "in", "environ", ".", "get", "(", "'HTTP_CONNECTION'", ",", "''", ")", ".", "lower", "(", ")", ...
46.777778
0.002328
def on_widget__button_press_event(self, widget, event): ''' Called when any mouse button is pressed. .. versionchanged:: 0.11 Do not trigger `route-electrode-added` event if `ALT` key is pressed. ''' if self.mode == 'register_video' and event.button == 1...
[ "def", "on_widget__button_press_event", "(", "self", ",", "widget", ",", "event", ")", ":", "if", "self", ".", "mode", "==", "'register_video'", "and", "event", ".", "button", "==", "1", ":", "self", ".", "start_event", "=", "event", ".", "copy", "(", ")...
36.16
0.003233
def __mount_device(action): ''' Small decorator to makes sure that the mount and umount happends in a transactional way. ''' @functools.wraps(action) def wrapper(*args, **kwargs): name = kwargs['name'] device = kwargs['device'] ret = { 'name': name, ...
[ "def", "__mount_device", "(", "action", ")", ":", "@", "functools", ".", "wraps", "(", "action", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "name", "=", "kwargs", "[", "'name'", "]", "device", "=", "kwargs", "[", "'...
30.266667
0.001067
def download_workflow_description_file(self, filename): '''Downloads the workflow description and writes it to a *YAML* file. Parameters ---------- filename: str path to the file to which description should be written See also -------- :meth:`tmclien...
[ "def", "download_workflow_description_file", "(", "self", ",", "filename", ")", ":", "description", "=", "self", ".", "download_workflow_description", "(", ")", "logger", ".", "info", "(", "'write workflow description to file: %s'", ",", "filename", ")", "with", "open...
36.052632
0.002845
def build(sub_parser, cmds): """todo: Docstring for build :param sub_parser: arg description :type sub_parser: type description :return: :rtype: """ res = {} for cmd in cmds: res[cmd.name] = cmd(sub_parser) # end for cmd in cmds return res
[ "def", "build", "(", "sub_parser", ",", "cmds", ")", ":", "res", "=", "{", "}", "for", "cmd", "in", "cmds", ":", "res", "[", "cmd", ".", "name", "]", "=", "cmd", "(", "sub_parser", ")", "# end for cmd in cmds", "return", "res" ]
18.4
0.003448
def createBinaryRelation(self, m): """ Initialize a two-dimensional array of size m by m. :ivar int m: A value for m. """ binaryRelation = [] for i in range(m): binaryRelation.append(range(m)) binaryRelation[i][i] = 0 return binaryRel...
[ "def", "createBinaryRelation", "(", "self", ",", "m", ")", ":", "binaryRelation", "=", "[", "]", "for", "i", "in", "range", "(", "m", ")", ":", "binaryRelation", ".", "append", "(", "range", "(", "m", ")", ")", "binaryRelation", "[", "i", "]", "[", ...
26.166667
0.009231
def parse(expression): """ Return array of parsed tokens in the expression expression String: Math expression to parse in infix notation """ result = [] current = "" for i in expression: if i.isdigit() or i == '.': current += i else: if le...
[ "def", "parse", "(", "expression", ")", ":", "result", "=", "[", "]", "current", "=", "\"\"", "for", "i", "in", "expression", ":", "if", "i", ".", "isdigit", "(", ")", "or", "i", "==", "'.'", ":", "current", "+=", "i", "else", ":", "if", "len", ...
27.434783
0.001531
def listNode(node): """ A list (numbered or not) For numbered lists, the suffix is only rendered as . in html """ if node.list_data['type'] == u'bullet': o = nodes.bullet_list(bullet=node.list_data['bullet_char']) else: o = nodes.enumerated_list(suffix=node.list_data['delimiter']...
[ "def", "listNode", "(", "node", ")", ":", "if", "node", ".", "list_data", "[", "'type'", "]", "==", "u'bullet'", ":", "o", "=", "nodes", ".", "bullet_list", "(", "bullet", "=", "node", ".", "list_data", "[", "'bullet_char'", "]", ")", "else", ":", "o...
34.75
0.004673
def cpos(string, chars, start): """ Find the first occurrence in a string of a character belonging to a collection of characters, starting at a specified location, searching forward. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/cpos_c.html :param string: Any character string. :t...
[ "def", "cpos", "(", "string", ",", "chars", ",", "start", ")", ":", "string", "=", "stypes", ".", "stringToCharP", "(", "string", ")", "chars", "=", "stypes", ".", "stringToCharP", "(", "chars", ")", "start", "=", "ctypes", ".", "c_int", "(", "start", ...
34.26087
0.001235
def save(self): """ Saves the current state of the DatabaseObject to the database. Fills in missing values from defaults before saving. NOTE: The actual operation here is to overwrite the entry in the database with the same ID_KEY. WARNING: While the sa...
[ "def", "save", "(", "self", ")", ":", "self", ".", "_pre_save", "(", ")", "self", ".", "_collection", ".", "replace_one", "(", "{", "ID_KEY", ":", "self", "[", "ID_KEY", "]", "}", ",", "dict", "(", "self", ")", ")" ]
44.526316
0.005787
def get_visible_area(self): """Returns visible area Format is a tuple of the top left tuple and the lower right tuple """ grid = self.grid top = grid.YToRow(grid.GetViewStart()[1] * grid.ScrollLineX) left = grid.XToCol(grid.GetViewStart()[0] * grid.ScrollLineY) ...
[ "def", "get_visible_area", "(", "self", ")", ":", "grid", "=", "self", ".", "grid", "top", "=", "grid", ".", "YToRow", "(", "grid", ".", "GetViewStart", "(", ")", "[", "1", "]", "*", "grid", ".", "ScrollLineX", ")", "left", "=", "grid", ".", "XToCo...
25.892857
0.00266
def get_full_psd_matrix(self): """Function that returns the tf graph corresponding to the entire matrix M. Returns: matrix_h: unrolled version of tf matrix corresponding to H matrix_m: unrolled tf matrix corresponding to M """ if self.matrix_m is not None: return self.matrix_h, self.m...
[ "def", "get_full_psd_matrix", "(", "self", ")", ":", "if", "self", ".", "matrix_m", "is", "not", "None", ":", "return", "self", ".", "matrix_h", ",", "self", ".", "matrix_m", "# Computing the matrix term", "h_columns", "=", "[", "]", "for", "i", "in", "ran...
37.068182
0.006571
def update(self): """Update load stats.""" # Init new stats stats = self.get_init_value() if self.input_method == 'local': # Update stats using the standard system lib # Get the load using the os standard lib load = self._getloadavg() if ...
[ "def", "update", "(", "self", ")", ":", "# Init new stats", "stats", "=", "self", ".", "get_init_value", "(", ")", "if", "self", ".", "input_method", "==", "'local'", ":", "# Update stats using the standard system lib", "# Get the load using the os standard lib", "load"...
30.27027
0.00173
def _compute_empirical_phi(self, beta): """Returns empirical `phi` at the given value of `beta`. Does **not** set `phi` attribute, simply returns what should be value of `phi` given the current `g` and `pi_codon` attributes, plus the passed value of `beta`. Note that it uses the...
[ "def", "_compute_empirical_phi", "(", "self", ",", "beta", ")", ":", "def", "F", "(", "phishort", ")", ":", "\"\"\"Difference between `g` and expected `g` given `phishort`.\"\"\"", "phifull", "=", "scipy", ".", "append", "(", "phishort", ",", "1", "-", "phishort", ...
44.411765
0.003889
def get_statistics_24h(self, endtime): """Return statistical data last 24h from time""" js = json.dumps( {'attrs': ["bytes", "num_sta", "time"], 'start': int(endtime - 86400) * 1000, 'end': int(endtime - 3600) * 1000}) params = urllib.urlencode({'json': js}) return self._rea...
[ "def", "get_statistics_24h", "(", "self", ",", "endtime", ")", ":", "js", "=", "json", ".", "dumps", "(", "{", "'attrs'", ":", "[", "\"bytes\"", ",", "\"num_sta\"", ",", "\"time\"", "]", ",", "'start'", ":", "int", "(", "endtime", "-", "86400", ")", ...
52.428571
0.008043
def count_comments_handler(sender, **kwargs): """ Update Entry.comment_count when a public comment was posted. """ comment = kwargs['comment'] if comment.is_public: entry = comment.content_object if isinstance(entry, Entry): entry.comment_count = F('comment_count') + 1 ...
[ "def", "count_comments_handler", "(", "sender", ",", "*", "*", "kwargs", ")", ":", "comment", "=", "kwargs", "[", "'comment'", "]", "if", "comment", ".", "is_public", ":", "entry", "=", "comment", ".", "content_object", "if", "isinstance", "(", "entry", ",...
36.4
0.002681
def highlight_block(self, text): """Implement specific highlight for Python.""" text = to_text_string(text) prev_state = tbh.get_state(self.currentBlock().previous()) if prev_state == self.INSIDE_DQ3STRING: offset = -4 text = r'""" '+text elif prev_...
[ "def", "highlight_block", "(", "self", ",", "text", ")", ":", "text", "=", "to_text_string", "(", "text", ")", "prev_state", "=", "tbh", ".", "get_state", "(", "self", ".", "currentBlock", "(", ")", ".", "previous", "(", ")", ")", "if", "prev_state", "...
53.227273
0.001258
def filter(self, criteria, applyto='measurement', ID=None): """ Filter measurements according to given criteria. Retain only Measurements for which criteria returns True. TODO: add support for multiple criteria Parameters ---------- criteria : callable ...
[ "def", "filter", "(", "self", ",", "criteria", ",", "applyto", "=", "'measurement'", ",", "ID", "=", "None", ")", ":", "fil", "=", "criteria", "new", "=", "self", ".", "copy", "(", ")", "if", "isinstance", "(", "applyto", ",", "collections", ".", "Ma...
37.97619
0.003056
def str_is_well_formed(xml_str): """ Args: xml_str : str DataONE API XML doc. Returns: bool: **True** if XML doc is well formed. """ try: str_to_etree(xml_str) except xml.etree.ElementTree.ParseError: return False else: return True
[ "def", "str_is_well_formed", "(", "xml_str", ")", ":", "try", ":", "str_to_etree", "(", "xml_str", ")", "except", "xml", ".", "etree", ".", "ElementTree", ".", "ParseError", ":", "return", "False", "else", ":", "return", "True" ]
18.533333
0.003425
def operator_iteration(self, T, v, max_iter, tol=None, *args, **kwargs): """ Iteratively apply the operator `T` to `v`. Modify `v` in-place. Iteration is performed for at most a number `max_iter` of times. If `tol` is specified, it is terminated once the distance of `T(v)` from `...
[ "def", "operator_iteration", "(", "self", ",", "T", ",", "v", ",", "max_iter", ",", "tol", "=", "None", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# May be replaced with quantecon.compute_fixed_point", "if", "max_iter", "<=", "0", ":", "return", ...
28.977778
0.001484
def create(self, re='brunel-py-ex-*.gdf', index=True): """ Create db from list of gdf file glob Parameters ---------- re : str File glob to load. index : bool Create index on neurons for speed. Returns ...
[ "def", "create", "(", "self", ",", "re", "=", "'brunel-py-ex-*.gdf'", ",", "index", "=", "True", ")", ":", "self", ".", "cursor", ".", "execute", "(", "'CREATE TABLE IF NOT EXISTS spikes (neuron INT UNSIGNED, time REAL)'", ")", "tic", "=", "now", "(", ")", "for"...
27.543478
0.009909
def get_meta_attributes(self, **kwargs): """Determine the form attributes for the meta field.""" superuser = kwargs.get('superuser', False) if (self.untl_object.qualifier == 'recordStatus' or self.untl_object.qualifier == 'system'): if superuser: self....
[ "def", "get_meta_attributes", "(", "self", ",", "*", "*", "kwargs", ")", ":", "superuser", "=", "kwargs", ".", "get", "(", "'superuser'", ",", "False", ")", "if", "(", "self", ".", "untl_object", ".", "qualifier", "==", "'recordStatus'", "or", "self", "....
40.411765
0.002845
def filterManifestPatches(self): """ Patches to manifest projects are a bit special. repo does not support a way to download them automatically, so we need to implement the boilerplate manually. This code separates the manifest patches from the other patches, and generate...
[ "def", "filterManifestPatches", "(", "self", ")", ":", "manifest_unrelated_downloads", "=", "[", "]", "manifest_related_downloads", "=", "[", "]", "for", "download", "in", "self", ".", "repoDownloads", ":", "project", ",", "ch_ps", "=", "download", ".", "split",...
50.458333
0.001621
def count_records(self, record_counter, file): """Count the number of viewed records.""" counter = record_counter events_counter = 0 for record in file.get_records(): recid = record[2] counter[recid] = counter.get(recid, 0) + 1 events_counter += 1 ...
[ "def", "count_records", "(", "self", ",", "record_counter", ",", "file", ")", ":", "counter", "=", "record_counter", "events_counter", "=", "0", "for", "record", "in", "file", ".", "get_records", "(", ")", ":", "recid", "=", "record", "[", "2", "]", "cou...
35.090909
0.005051
def match(self, row, template_row=None): """ 匹配一个模板时,只比较起始行,未来考虑支持比较关键字段即可,现在是起始行的所有字段全匹配 :param row: :return: """ if not template_row: template_cols = self.template[0]['cols'] else: template_cols = template_row['cols'] #check if l...
[ "def", "match", "(", "self", ",", "row", ",", "template_row", "=", "None", ")", ":", "if", "not", "template_row", ":", "template_cols", "=", "self", ".", "template", "[", "0", "]", "[", "'cols'", "]", "else", ":", "template_cols", "=", "template_row", ...
30.88
0.01005
def _init_length(self, request_method): """ Set initial length value for Response content if available. """ length = self.headers.get('content-length') if length is not None: if self.chunked: # This Response will fail with an IncompleteRead if it can'...
[ "def", "_init_length", "(", "self", ",", "request_method", ")", ":", "length", "=", "self", ".", "headers", ".", "get", "(", "'content-length'", ")", "if", "length", "is", "not", "None", ":", "if", "self", ".", "chunked", ":", "# This Response will fail with...
43.680851
0.003335
def push_broks_to_broker(self): # pragma: no cover - not used! """Send all broks from arbiter internal list to broker The arbiter get some broks and then pushes them to all the brokers. :return: None """ someone_is_concerned = False sent = False for broker_link...
[ "def", "push_broks_to_broker", "(", "self", ")", ":", "# pragma: no cover - not used!", "someone_is_concerned", "=", "False", "sent", "=", "False", "for", "broker_link", "in", "self", ".", "conf", ".", "brokers", ":", "# Send only if the broker is concerned...", "if", ...
38.166667
0.003195
def close(self): """ Close the sockets """ self._socket.close() if self._async_socket_cache: self._async_socket_cache.close() self._async_socket_cache = None
[ "def", "close", "(", "self", ")", ":", "self", ".", "_socket", ".", "close", "(", ")", "if", "self", ".", "_async_socket_cache", ":", "self", ".", "_async_socket_cache", ".", "close", "(", ")", "self", ".", "_async_socket_cache", "=", "None" ]
26.75
0.00905
def callback(self, provider): """ Handles 3rd party callback and processes it's data """ provider = self.get_provider(provider) try: return provider.authorized_handler(self.login)(provider=provider) except OAuthException as ex: logging.error("Data:...
[ "def", "callback", "(", "self", ",", "provider", ")", ":", "provider", "=", "self", ".", "get_provider", "(", "provider", ")", "try", ":", "return", "provider", ".", "authorized_handler", "(", "self", ".", "login", ")", "(", "provider", "=", "provider", ...
34.3
0.005682
def is_collapsed(self, id_user): """Return true if the comment is collapsed by user.""" return CmtCOLLAPSED.query.filter(db.and_( CmtCOLLAPSED.id_bibrec == self.id_bibrec, CmtCOLLAPSED.id_cmtRECORDCOMMENT == self.id, CmtCOLLAPSED.id_user == id_user)).count() > 0
[ "def", "is_collapsed", "(", "self", ",", "id_user", ")", ":", "return", "CmtCOLLAPSED", ".", "query", ".", "filter", "(", "db", ".", "and_", "(", "CmtCOLLAPSED", ".", "id_bibrec", "==", "self", ".", "id_bibrec", ",", "CmtCOLLAPSED", ".", "id_cmtRECORDCOMMENT...
51.5
0.006369
def lhood(self, trsig, recalc=False, cachefile=None): """Returns likelihood of transit signal Returns sum of ``trsig`` MCMC samples evaluated at ``self.kde``. :param trsig: :class:`vespa.TransitSignal` object. :param recalc: (optional) Whether to recalc...
[ "def", "lhood", "(", "self", ",", "trsig", ",", "recalc", "=", "False", ",", "cachefile", "=", "None", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'kde'", ")", ":", "self", ".", "_make_kde", "(", ")", "if", "cachefile", "is", "None", ":", ...
27
0.002681
def exists_locked(filepath: str) -> Tuple[bool, bool]: """ Checks if a file is locked by opening it in append mode. (If no exception is thrown in that situation, then the file is not locked.) Args: filepath: file to check Returns: tuple: ``(exists, locked)`` See https://www.ca...
[ "def", "exists_locked", "(", "filepath", ":", "str", ")", "->", "Tuple", "[", "bool", ",", "bool", "]", ":", "exists", "=", "False", "locked", "=", "None", "file_object", "=", "None", "if", "os", ".", "path", ".", "exists", "(", "filepath", ")", ":",...
28.903226
0.00108
def _import_class(self, class_path): """Try and import the specified namespaced class. :param str class_path: The full path to the class (foo.bar.Baz) :rtype: class """ LOGGER.debug('Importing %s', class_path) try: return utils.import_namespaced_class(class_...
[ "def", "_import_class", "(", "self", ",", "class_path", ")", ":", "LOGGER", ".", "debug", "(", "'Importing %s'", ",", "class_path", ")", "try", ":", "return", "utils", ".", "import_namespaced_class", "(", "class_path", ")", "except", "ImportError", "as", "erro...
34.461538
0.004348
def query(database, query, **connection_args): ''' Run an arbitrary SQL query and return the results or the number of affected rows. CLI Example: .. code-block:: bash salt '*' mysql.query mydb "UPDATE mytable set myfield=1 limit 1" Return data: .. code-block:: python {'...
[ "def", "query", "(", "database", ",", "query", ",", "*", "*", "connection_args", ")", ":", "# Doesn't do anything about sql warnings, e.g. empty values on an insert.", "# I don't think it handles multiple queries at once, so adding \"commit\"", "# might not work.", "# The following 3 l...
28.338462
0.001574
def get_cities_by_name(self, name): """Get a list of city dictionaries with the given name. City names cannot be used as keys, as they are not unique. """ if name not in self.cities_by_names: if self.cities_items is None: self.cities_items = list(self.get_ci...
[ "def", "get_cities_by_name", "(", "self", ",", "name", ")", ":", "if", "name", "not", "in", "self", ".", "cities_by_names", ":", "if", "self", ".", "cities_items", "is", "None", ":", "self", ".", "cities_items", "=", "list", "(", "self", ".", "get_cities...
41.833333
0.005848
def get_screenshot_as_file(self, filename): """ Saves a screenshot of the current window to a PNG image file. Returns False if there is any IOError, else returns True. Use full paths in your filename. :Args: - filename: The full path you wish to save your screensh...
[ "def", "get_screenshot_as_file", "(", "self", ",", "filename", ")", ":", "if", "not", "filename", ".", "lower", "(", ")", ".", "endswith", "(", "'.png'", ")", ":", "warnings", ".", "warn", "(", "\"name used for saved screenshot does not match file \"", "\"type. It...
34
0.003178
def get_default(self, *args, **kwargs): """Get the default parameters as defined in the Settings instance. This function proceeds to seamlessly retrieve the argument to pass through, depending on either it was overidden or not: If no argument was overridden in a function of the toolbox,...
[ "def", "get_default", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "def", "retrieve_param", "(", "i", ")", ":", "try", ":", "return", "self", ".", "__getattribute__", "(", "i", ")", "except", "AttributeError", ":", "if", "i", "==...
43.947368
0.002929
def fling_backward_vertically(self, *args, **selectors): """ Perform fling backward (vertically)action on the object which has *selectors* attributes. Return whether the object can be fling or not. """ return self.device(**selectors).fling.vert.backward()
[ "def", "fling_backward_vertically", "(", "self", ",", "*", "args", ",", "*", "*", "selectors", ")", ":", "return", "self", ".", "device", "(", "*", "*", "selectors", ")", ".", "fling", ".", "vert", ".", "backward", "(", ")" ]
41.428571
0.010135
def make_picks(workspace, pick_file=None, clear=False, use_cache=True, dry_run=False, keep_dups=False): """ Return a subset of the designs in the given data frame based on the conditions specified in the given "pick" file. An example pick file is show below:: threshold: - restraint_di...
[ "def", "make_picks", "(", "workspace", ",", "pick_file", "=", "None", ",", "clear", "=", "False", ",", "use_cache", "=", "True", ",", "dry_run", "=", "False", ",", "keep_dups", "=", "False", ")", ":", "# Read the rules for making picks from the given file.", "if...
33.626609
0.003719
def _get_edge_tuple(source, target, edge_data: EdgeData, ) -> Tuple[str, str, str, Optional[str], Tuple[str, Optional[Tuple], Optional[Tuple]]]: """Convert an edge to a consistent tuple. :param BaseEntity source: The source BEL node :param BaseEnt...
[ "def", "_get_edge_tuple", "(", "source", ",", "target", ",", "edge_data", ":", "EdgeData", ",", ")", "->", "Tuple", "[", "str", ",", "str", ",", "str", ",", "Optional", "[", "str", "]", ",", "Tuple", "[", "str", ",", "Optional", "[", "Tuple", "]", ...
37.166667
0.004373
def is_blankspace(self, char): """ Test if a character is a blankspace. Parameters ---------- char : str The character to test. Returns ------- ret : bool True if character is a blankspace, False otherwise. """ if...
[ "def", "is_blankspace", "(", "self", ",", "char", ")", ":", "if", "len", "(", "char", ")", ">", "1", ":", "raise", "TypeError", "(", "\"Expected a char.\"", ")", "if", "char", "in", "self", ".", "blankspaces", ":", "return", "True", "return", "False" ]
22.3
0.004301
def to_dict(self, minimal=False): """Returns the representation for serialization""" data = collections.OrderedDict() if minimal: # In the minimal representation we just output the value data['value'] = self._to_python_type(self.value) else: # I...
[ "def", "to_dict", "(", "self", ",", "minimal", "=", "False", ")", ":", "data", "=", "collections", ".", "OrderedDict", "(", ")", "if", "minimal", ":", "# In the minimal representation we just output the value", "data", "[", "'value'", "]", "=", "self", ".", "_...
32.458333
0.003741
def set_garbage_collector(self, exts=None, policy="task"): """ Enable the garbage collector that will remove the big output files that are not needed. Args: exts: string or list with the Abinit file extensions to be removed. A default is provided if exts is None ...
[ "def", "set_garbage_collector", "(", "self", ",", "exts", "=", "None", ",", "policy", "=", "\"task\"", ")", ":", "assert", "policy", "in", "(", "\"task\"", ",", "\"flow\"", ")", "exts", "=", "list_strings", "(", "exts", ")", "if", "exts", "is", "not", ...
49.521739
0.008613
def evaluate(ref_intervals, ref_pitches, est_intervals, est_pitches, **kwargs): """Compute all metrics for the given reference and estimated annotations. Examples -------- >>> ref_intervals, ref_pitches = mir_eval.io.load_valued_intervals( ... 'reference.txt') >>> est_intervals, est_pitches ...
[ "def", "evaluate", "(", "ref_intervals", ",", "ref_pitches", ",", "est_intervals", ",", "est_pitches", ",", "*", "*", "kwargs", ")", ":", "# Compute all the metrics", "scores", "=", "collections", ".", "OrderedDict", "(", ")", "# Precision, recall and f-measure taking...
38.205479
0.00035
def set_preferred_prefix_for_namespace(self, ns_uri, prefix, add_if_not_exist=False): """Sets the preferred prefix for ns_uri. If add_if_not_exist is True, the prefix is added if it's not already registered. Otherwise, setting an unknown prefix as preferred is an error. The default is...
[ "def", "set_preferred_prefix_for_namespace", "(", "self", ",", "ns_uri", ",", "prefix", ",", "add_if_not_exist", "=", "False", ")", ":", "ni", "=", "self", ".", "__lookup_uri", "(", "ns_uri", ")", "if", "not", "prefix", ":", "ni", ".", "preferred_prefix", "=...
44
0.002301
def output(self, message, color=None): """ A helper to used like print() or click's secho() tunneling all the outputs to sys.stdout or sys.stderr :param message: (str) :param color: (str) check click.secho() documentation :return: (None) prints to sys.stdout or sys.stderr...
[ "def", "output", "(", "self", ",", "message", ",", "color", "=", "None", ")", ":", "output_to", "=", "stderr", "if", "color", "==", "\"red\"", "else", "stdout", "secho", "(", "self", ".", "indent", "(", "message", ")", ",", "fg", "=", "color", ",", ...
44.2
0.004435
def get_results(self, request): """ Temporarily decreases the `level` attribute of all search results in order to prevent indendation when displaying them. """ super(MediaTreeChangeList, self).get_results(request) try: reduce_levels = abs(int(get_request_attr(...
[ "def", "get_results", "(", "self", ",", "request", ")", ":", "super", "(", "MediaTreeChangeList", ",", "self", ")", ".", "get_results", "(", "request", ")", "try", ":", "reduce_levels", "=", "abs", "(", "int", "(", "get_request_attr", "(", "request", ",", ...
41.142857
0.003394
def generate_image_beacon(event_collection, body, timestamp=None): """ Generates an image beacon URL. :param event_collection: the name of the collection to insert the event to :param body: dict, the body of the event to insert the event to :param timestamp: datetime, optional, the timestamp of the...
[ "def", "generate_image_beacon", "(", "event_collection", ",", "body", ",", "timestamp", "=", "None", ")", ":", "_initialize_client_from_environment", "(", ")", "return", "_client", ".", "generate_image_beacon", "(", "event_collection", ",", "body", ",", "timestamp", ...
45.3
0.004329
def iter_tree(jottapath, JFS): """Get a tree of of files and folders. use as an iterator, you get something like os.walk""" filedirlist = JFS.getObject('%s?mode=list' % jottapath) log.debug("got tree: %s", filedirlist) if not isinstance(filedirlist, JFSFileDirList): yield ( '', tuple(), tuple() ...
[ "def", "iter_tree", "(", "jottapath", ",", "JFS", ")", ":", "filedirlist", "=", "JFS", ".", "getObject", "(", "'%s?mode=list'", "%", "jottapath", ")", "log", ".", "debug", "(", "\"got tree: %s\"", ",", "filedirlist", ")", "if", "not", "isinstance", "(", "f...
45.875
0.010695
def make_session(username=None, password=None, bearer_token=None, extra_headers_dict=None): """Creates a Requests Session for use. Accepts a bearer token for premiums users and will override username and password information if present. Args: username (str): username for the session pa...
[ "def", "make_session", "(", "username", "=", "None", ",", "password", "=", "None", ",", "bearer_token", "=", "None", ",", "extra_headers_dict", "=", "None", ")", ":", "if", "password", "is", "None", "and", "bearer_token", "is", "None", ":", "logger", ".", ...
38.354839
0.003281
def _parse_flags(element): """Parse OSM XML element for generic data. Args: element (etree.Element): Element to parse Returns: tuple: Generic OSM data for object instantiation """ visible = True if element.get('visible') else False user = element.get('user') timestamp = ele...
[ "def", "_parse_flags", "(", "element", ")", ":", "visible", "=", "True", "if", "element", ".", "get", "(", "'visible'", ")", "else", "False", "user", "=", "element", ".", "get", "(", "'user'", ")", "timestamp", "=", "element", ".", "get", "(", "'timest...
26.416667
0.001522
def execution(): ''' Collect all the sys.doc output from each minion and return the aggregate CLI Example: .. code-block:: bash salt-run doc.execution ''' client = salt.client.get_local_client(__opts__['conf_file']) docs = {} try: for ret in client.cmd_iter('*', 'sys....
[ "def", "execution", "(", ")", ":", "client", "=", "salt", ".", "client", ".", "get_local_client", "(", "__opts__", "[", "'conf_file'", "]", ")", "docs", "=", "{", "}", "try", ":", "for", "ret", "in", "client", ".", "cmd_iter", "(", "'*'", ",", "'sys....
23.4
0.003284
def extra(self, argument_dest, **kwargs): """Register extra parameters for the given command. Typically used to augment auto-command built commands to add more parameters than the specific SDK method introspected. :param argument_dest: The destination argument to add this argument type to ...
[ "def", "extra", "(", "self", ",", "argument_dest", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_check_stale", "(", ")", "if", "not", "self", ".", "_applicable", "(", ")", ":", "return", "if", "self", ".", "command_scope", "in", "self", ".", "com...
56.26087
0.007599
def output_pins(self, pins): """Set multiple pins high or low at once. Pins should be a dict of pin name to pin value (HIGH/True for 1, LOW/False for 0). All provided pins will be set to the given values. """ [self._validate_pin(pin) for pin in pins.keys()] # Set each c...
[ "def", "output_pins", "(", "self", ",", "pins", ")", ":", "[", "self", ".", "_validate_pin", "(", "pin", ")", "for", "pin", "in", "pins", ".", "keys", "(", ")", "]", "# Set each changed pin's bit.", "for", "pin", ",", "value", "in", "iter", "(", "pins"...
41.785714
0.008361
def roles(self): """ Roles accessor """ roles = list(self.__roles) default_role = Role( handle='user', title='User role', description='All registered users get this role by default' ) roles.append(default_role) return tuple(roles)
[ "def", "roles", "(", "self", ")", ":", "roles", "=", "list", "(", "self", ".", "__roles", ")", "default_role", "=", "Role", "(", "handle", "=", "'user'", ",", "title", "=", "'User role'", ",", "description", "=", "'All registered users get this role by default...
27.727273
0.006349
def job_monitor(job, interval=None, monitor_async=False, quiet=False, output=sys.stdout): """Monitor the status of a IBMQJob instance. Args: job (BaseJob): Job to monitor. interval (int): Time interval between status queries. monitor_async (bool): Monitor asyncronously (in Jupyter only)...
[ "def", "job_monitor", "(", "job", ",", "interval", "=", "None", ",", "monitor_async", "=", "False", ",", "quiet", "=", "False", ",", "output", "=", "sys", ".", "stdout", ")", ":", "if", "interval", "is", "None", ":", "_interval_set", "=", "False", "int...
40.340426
0.002575
def get_transactions(self, date_from: datetime, date_to: datetime) -> List[Transaction]: """ Returns account transactions """ assert isinstance(date_from, datetime) assert isinstance(date_to, datetime) # fix up the parameters as we need datetime dt_from = Datum() dt_from...
[ "def", "get_transactions", "(", "self", ",", "date_from", ":", "datetime", ",", "date_to", ":", "datetime", ")", "->", "List", "[", "Transaction", "]", ":", "assert", "isinstance", "(", "date_from", ",", "datetime", ")", "assert", "isinstance", "(", "date_to...
36.952381
0.005025
def zsum(s, *args, **kwargs): """ pandas 0.21.0 changes sum() behavior so that the result of applying sum over an empty DataFrame is NaN. Meant to be set as pd.Series.zsum = zsum. """ return 0 if s.empty else s.sum(*args, **kwargs)
[ "def", "zsum", "(", "s", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "0", "if", "s", ".", "empty", "else", "s", ".", "sum", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
31.125
0.003906
def get_environments(): """Gets all environments found in the 'environments' directory""" envs = [] for root, subfolders, files in os.walk('environments'): for filename in files: if filename.endswith(".json"): path = os.path.join( root[len('environment...
[ "def", "get_environments", "(", ")", ":", "envs", "=", "[", "]", "for", "root", ",", "subfolders", ",", "files", "in", "os", ".", "walk", "(", "'environments'", ")", ":", "for", "filename", "in", "files", ":", "if", "filename", ".", "endswith", "(", ...
44.3
0.002212
def macro_network(): """A network of micro elements which has greater integrated information after coarse graining to a macro scale. """ tpm = np.array([[0.3, 0.3, 0.3, 0.3], [0.3, 0.3, 0.3, 0.3], [0.3, 0.3, 0.3, 0.3], [0.3, 0.3, 1.0, 1.0], ...
[ "def", "macro_network", "(", ")", ":", "tpm", "=", "np", ".", "array", "(", "[", "[", "0.3", ",", "0.3", ",", "0.3", ",", "0.3", "]", ",", "[", "0.3", ",", "0.3", ",", "0.3", ",", "0.3", "]", ",", "[", "0.3", ",", "0.3", ",", "0.3", ",", ...
40.952381
0.001136
def _process_server_headers( self, key: Union[str, bytes], headers: httputil.HTTPHeaders ) -> None: """Process the headers sent by the server to this client connection. 'key' is the websocket handshake challenge/response key. """ assert headers["Upgrade"].lower() == "websock...
[ "def", "_process_server_headers", "(", "self", ",", "key", ":", "Union", "[", "str", ",", "bytes", "]", ",", "headers", ":", "httputil", ".", "HTTPHeaders", ")", "->", "None", ":", "assert", "headers", "[", "\"Upgrade\"", "]", ".", "lower", "(", ")", "...
43.6
0.004489
def founditem_modify_view(request, item_id=None): """Modify a founditem. id: founditem id """ if request.method == "POST": founditem = get_object_or_404(FoundItem, id=item_id) form = FoundItemForm(request.POST, instance=founditem) if form.is_valid(): obj = form.save...
[ "def", "founditem_modify_view", "(", "request", ",", "item_id", "=", "None", ")", ":", "if", "request", ".", "method", "==", "\"POST\"", ":", "founditem", "=", "get_object_or_404", "(", "FoundItem", ",", "id", "=", "item_id", ")", "form", "=", "FoundItemForm...
37.24
0.002094
def step(self): """Do a single iteration over all cbpdn and ccmod steps. Those that are not coupled on the K axis are performed in parallel.""" # If the nproc parameter of __init__ is zero, just iterate # over the K consensus instances instead of using # multiprocessing to do th...
[ "def", "step", "(", "self", ")", ":", "# If the nproc parameter of __init__ is zero, just iterate", "# over the K consensus instances instead of using", "# multiprocessing to do the computations in parallel. This is", "# useful for debugging and timing comparisons.", "if", "self", ".", "np...
37.882353
0.00303
def navigate_subtype(supertype, rel_id): ''' Perform a navigation from *supertype* to its subtype across *rel_id*. The navigated association must be modeled as a subtype-supertype association. The return value will an instance or None. ''' if not supertype: return if isinst...
[ "def", "navigate_subtype", "(", "supertype", ",", "rel_id", ")", ":", "if", "not", "supertype", ":", "return", "if", "isinstance", "(", "rel_id", ",", "int", ")", ":", "rel_id", "=", "'R%d'", "%", "rel_id", "metaclass", "=", "get_metaclass", "(", "supertyp...
29.714286
0.006211
def set_progress_brackets(self, start, end): """Set brackets to set around a progress bar.""" self.sep_start = start self.sep_end = end
[ "def", "set_progress_brackets", "(", "self", ",", "start", ",", "end", ")", ":", "self", ".", "sep_start", "=", "start", "self", ".", "sep_end", "=", "end" ]
39
0.012579
def headers(self): """All headers needed to make a request""" return { "Content-Type": ("multipart/form-data; boundary={}".format(self.boundary)), "Content-Length": str(self.len), "Content-Encoding": self.encoding, }
[ "def", "headers", "(", "self", ")", ":", "return", "{", "\"Content-Type\"", ":", "(", "\"multipart/form-data; boundary={}\"", ".", "format", "(", "self", ".", "boundary", ")", ")", ",", "\"Content-Length\"", ":", "str", "(", "self", ".", "len", ")", ",", "...
38.571429
0.01087
def normalise_angle(th): """Normalise an angle to be in the range [-pi, pi].""" return th - (2.0 * np.pi) * np.floor((th + np.pi) / (2.0 * np.pi))
[ "def", "normalise_angle", "(", "th", ")", ":", "return", "th", "-", "(", "2.0", "*", "np", ".", "pi", ")", "*", "np", ".", "floor", "(", "(", "th", "+", "np", ".", "pi", ")", "/", "(", "2.0", "*", "np", ".", "pi", ")", ")" ]
50.666667
0.006494