text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def get_parent_label(self, treepos): """Given the treeposition of a node, return the label of its parent. Returns None, if the tree has no parent. """ parent_pos = self.get_parent_treepos(treepos) if parent_pos is not None: parent = self.dgtree[parent_pos] ...
[ "def", "get_parent_label", "(", "self", ",", "treepos", ")", ":", "parent_pos", "=", "self", ".", "get_parent_treepos", "(", "treepos", ")", "if", "parent_pos", "is", "not", "None", ":", "parent", "=", "self", ".", "dgtree", "[", "parent_pos", "]", "return...
37.1
8.6
def get_go2nt(self, usr_go2nt): """Combine user namedtuple fields, GO object fields, and format_txt.""" gos_all = self.get_gos_all() # Minimum set of namedtuple fields available for use with Sorter on grouped GO IDs prt_flds_all = get_hdridx_flds() + self.gosubdag.prt_attr['flds'] ...
[ "def", "get_go2nt", "(", "self", ",", "usr_go2nt", ")", ":", "gos_all", "=", "self", ".", "get_gos_all", "(", ")", "# Minimum set of namedtuple fields available for use with Sorter on grouped GO IDs", "prt_flds_all", "=", "get_hdridx_flds", "(", ")", "+", "self", ".", ...
61.384615
22.692308
def create_logger(app): """Creates a logger for the given application. This logger works similar to a regular Python logger but changes the effective logging level based on the application's debug flag. Furthermore this function also removes all attached handlers in case there was a logger with th...
[ "def", "create_logger", "(", "app", ")", ":", "Logger", "=", "getLoggerClass", "(", ")", "class", "DebugLogger", "(", "Logger", ")", ":", "def", "getEffectiveLevel", "(", "x", ")", ":", "if", "x", ".", "level", "==", "0", "and", "app", ".", "debug", ...
35.793103
15.586207
def ipv6_reassembly(packet, *, count=NotImplemented): """Make data for IPv6 reassembly.""" if scapy_all is None: raise ModuleNotFound("No module named 'scapy'", name='scapy') if 'IPv6' in packet: ipv6 = packet['IPv6'] if scapy_all.IPv6ExtHdrFragment not in ipv6: # pylint: disable=E1...
[ "def", "ipv6_reassembly", "(", "packet", ",", "*", ",", "count", "=", "NotImplemented", ")", ":", "if", "scapy_all", "is", "None", ":", "raise", "ModuleNotFound", "(", "\"No module named 'scapy'\"", ",", "name", "=", "'scapy'", ")", "if", "'IPv6'", "in", "pa...
60.923077
34.230769
def write(self, filename): """ Write detector to a file - uses HDF5 file format. Meta-data are stored alongside numpy data arrays. See h5py.org for \ details of the methods. :type filename: str :param filename: Filename to save the detector to. """ f = h...
[ "def", "write", "(", "self", ",", "filename", ")", ":", "f", "=", "h5py", ".", "File", "(", "filename", ",", "\"w\"", ")", "# Must store eqcorrscan version number, username would be useful too.", "data_group", "=", "f", ".", "create_group", "(", "name", "=", "\"...
46.912281
16.631579
def group_by_key(dirnames, key): """Group a set of output directories according to a model parameter. Parameters ---------- dirnames: list[str] Output directories key: various A field of a :class:`Model` instance. Returns ------- groups: dict[various: list[str]] ...
[ "def", "group_by_key", "(", "dirnames", ",", "key", ")", ":", "groups", "=", "defaultdict", "(", "lambda", ":", "[", "]", ")", "for", "dirname", "in", "dirnames", ":", "m", "=", "get_recent_model", "(", "dirname", ")", "groups", "[", "m", ".", "__dict_...
29.47619
17.428571
def get_noconflict_metaclass(bases, left_metas, right_metas): """ Not intended to be used outside of this module, unless you know what you are doing. """ # make tuple of needed metaclasses in specified priority order metas = left_metas + tuple(map(type, bases)) + right_metas needed_metas = remov...
[ "def", "get_noconflict_metaclass", "(", "bases", ",", "left_metas", ",", "right_metas", ")", ":", "# make tuple of needed metaclasses in specified priority order", "metas", "=", "left_metas", "+", "tuple", "(", "map", "(", "type", ",", "bases", ")", ")", "+", "right...
45.958333
18.541667
def get_wd_search_results(search_string='', mediawiki_api_url='https://www.wikidata.org/w/api.php', user_agent=config['USER_AGENT_DEFAULT'], max_results=500, language='en'): """ Performs a search in WD for a certain WD search string :pa...
[ "def", "get_wd_search_results", "(", "search_string", "=", "''", ",", "mediawiki_api_url", "=", "'https://www.wikidata.org/w/api.php'", ",", "user_agent", "=", "config", "[", "'USER_AGENT_DEFAULT'", "]", ",", "max_results", "=", "500", ",", "language", "=", "'en'", ...
36.571429
21.821429
def to_dict(self, **kwargs): """ Serialize the search into the dictionary that will be sent over as the request'ubq body. All additional keyword arguments will be included into the dictionary. """ d = {} if self.query: d["query"] = self.query.to_dict(...
[ "def", "to_dict", "(", "self", ",", "*", "*", "kwargs", ")", ":", "d", "=", "{", "}", "if", "self", ".", "query", ":", "d", "[", "\"query\"", "]", "=", "self", ".", "query", ".", "to_dict", "(", ")", "if", "self", ".", "_script", ":", "d", "[...
24.611111
21.166667
def broadcast(self, channel, event, data): """Broadcasts an event to all sockets listening on a channel.""" payload = self._server.serialize_event(event, data) for socket_id in self.subscriptions.get(channel, ()): rv = self._server.sockets.get(socket_id) if rv is not None...
[ "def", "broadcast", "(", "self", ",", "channel", ",", "event", ",", "data", ")", ":", "payload", "=", "self", ".", "_server", ".", "serialize_event", "(", "event", ",", "data", ")", "for", "socket_id", "in", "self", ".", "subscriptions", ".", "get", "(...
50.714286
9.285714
def work(self): """ Start ternya work. First, import customer's service modules. Second, init openstack mq. Third, keep a ternya connection that can auto-reconnect. """ self.init_modules() connection = self.init_mq() TernyaConnection(self, connect...
[ "def", "work", "(", "self", ")", ":", "self", ".", "init_modules", "(", ")", "connection", "=", "self", ".", "init_mq", "(", ")", "TernyaConnection", "(", "self", ",", "connection", ")", ".", "connect", "(", ")" ]
29.454545
13.454545
def detrended_price_oscillator(data, period): """ Detrended Price Oscillator. Formula: DPO = DATA[i] - Avg(DATA[period/2 + 1]) """ catch_errors.check_for_period_error(data, period) period = int(period) dop = [data[idx] - np.mean(data[idx+1-(int(period/2)+1):idx+1]) for idx in range(peri...
[ "def", "detrended_price_oscillator", "(", "data", ",", "period", ")", ":", "catch_errors", ".", "check_for_period_error", "(", "data", ",", "period", ")", "period", "=", "int", "(", "period", ")", "dop", "=", "[", "data", "[", "idx", "]", "-", "np", ".",...
32.5
17.833333
def liste_parametres(self, parametre=None): """ Liste des paramètres Paramètres: parametre: si fourni, retourne l'entrée pour ce parametre uniquement """ condition = "" if parametre: condition = "WHERE CCHIM='%s'" % parametre _sql = """SELECT...
[ "def", "liste_parametres", "(", "self", ",", "parametre", "=", "None", ")", ":", "condition", "=", "\"\"", "if", "parametre", ":", "condition", "=", "\"WHERE CCHIM='%s'\"", "%", "parametre", "_sql", "=", "\"\"\"SELECT CCHIM AS PARAMETRE,\n NCON AS LIBELLE,\n ...
29.6875
15.1875
def write_pdb(self, custom_name='', out_suffix='', out_dir=None, custom_selection=None, force_rerun=False): """Write a new PDB file for the Structure's FIRST MODEL. Set custom_selection to a PDB.Select class for custom SMCRA selections. Args: custom_name: Filename of the new file (...
[ "def", "write_pdb", "(", "self", ",", "custom_name", "=", "''", ",", "out_suffix", "=", "''", ",", "out_dir", "=", "None", ",", "custom_selection", "=", "None", ",", "force_rerun", "=", "False", ")", ":", "if", "not", "custom_selection", ":", "custom_selec...
45.325
26.55
def _establish_authenticated_session(self, kik_node): """ Updates the kik node and creates a new connection to kik servers. This new connection will be initiated with another payload which proves we have the credentials for a specific user. This is how authentication is done. :p...
[ "def", "_establish_authenticated_session", "(", "self", ",", "kik_node", ")", ":", "self", ".", "kik_node", "=", "kik_node", "log", ".", "info", "(", "\"[+] Closing current connection and creating a new authenticated one.\"", ")", "self", ".", "disconnect", "(", ")", ...
43
25.923077
def __update_binding( self, dependency, service, reference, old_properties, new_value ): # type: (Any, Any, ServiceReference, dict, bool) -> None """ Calls back component binding and field binding methods when the properties of an injected dependency have been updated. ...
[ "def", "__update_binding", "(", "self", ",", "dependency", ",", "service", ",", "reference", ",", "old_properties", ",", "new_value", ")", ":", "# type: (Any, Any, ServiceReference, dict, bool) -> None", "if", "new_value", ":", "# Set the value", "setattr", "(", "self",...
34.875
21.375
def _column_width(self, index=None, name=None, max_width=300, **kwargs): """ :param index: int of the column index :param name: str of the name of the column :param max_width: int of the max size of characters in the width :return: int of the width of this column """ ...
[ "def", "_column_width", "(", "self", ",", "index", "=", "None", ",", "name", "=", "None", ",", "max_width", "=", "300", ",", "*", "*", "kwargs", ")", ":", "assert", "name", "is", "not", "None", "or", "index", "is", "not", "None", "if", "name", "and...
38.192308
17.038462
def normalize_tuple_slice(node): """ Normalize an ast.Tuple node representing the internals of a slice. Returns the node wrapped in an ast.Index. Returns an ExtSlice node built from the tuple elements if there are any slices. """ if not any(isinstance(elt, ast.Slice) for elt in node.elts): ...
[ "def", "normalize_tuple_slice", "(", "node", ")", ":", "if", "not", "any", "(", "isinstance", "(", "elt", ",", "ast", ".", "Slice", ")", "for", "elt", "in", "node", ".", "elts", ")", ":", "return", "ast", ".", "Index", "(", "value", "=", "node", ")...
30.388889
20.944444
def list_memberships(self, subject_descriptor, direction=None, depth=None): """ListMemberships. [Preview API] Get all the memberships where this descriptor is a member in the relationship. :param str subject_descriptor: Fetch all direct memberships of this descriptor. :param str directio...
[ "def", "list_memberships", "(", "self", ",", "subject_descriptor", ",", "direction", "=", "None", ",", "depth", "=", "None", ")", ":", "route_values", "=", "{", "}", "if", "subject_descriptor", "is", "not", "None", ":", "route_values", "[", "'subjectDescriptor...
61.954545
28.5
def headerHTML(header,fname): """given the bytestring ABF header, make and launch HTML.""" html="<html><body><code>" html+="<h2>%s</h2>"%(fname) html+=pprint.pformat(header, indent=1) html=html.replace("\n",'<br>').replace(" ","&nbsp;") html=html.replace(r"\x00","") ...
[ "def", "headerHTML", "(", "header", ",", "fname", ")", ":", "html", "=", "\"<html><body><code>\"", "html", "+=", "\"<h2>%s</h2>\"", "%", "(", "fname", ")", "html", "+=", "pprint", ".", "pformat", "(", "header", ",", "indent", "=", "1", ")", "html", "=", ...
36.923077
9.538462
def getParam(xmlelement): """Converts an mzML xml element to a param tuple. :param xmlelement: #TODO docstring :returns: a param tuple or False if the xmlelement is not a parameter ('userParam', 'cvParam' or 'referenceableParamGroupRef') """ elementTag = clearTag(xmlelement.tag) if ele...
[ "def", "getParam", "(", "xmlelement", ")", ":", "elementTag", "=", "clearTag", "(", "xmlelement", ".", "tag", ")", "if", "elementTag", "in", "[", "'userParam'", ",", "'cvParam'", ",", "'referenceableParamGroupRef'", "]", ":", "if", "elementTag", "==", "'cvPara...
35.789474
18.315789
def _plot_thermo(self, func, temperatures, factor=1, ax=None, ylabel=None, label=None, ylim=None, **kwargs): """ Plots a thermodynamic property for a generic function from a PhononDos instance. Args: func: the thermodynamic function to be used to calculate the property t...
[ "def", "_plot_thermo", "(", "self", ",", "func", ",", "temperatures", ",", "factor", "=", "1", ",", "ax", "=", "None", ",", "ylabel", "=", "None", ",", "label", "=", "None", ",", "ylim", "=", "None", ",", "*", "*", "kwargs", ")", ":", "ax", ",", ...
34.175
24.925
def check_vtech(text): """Suggest the correct name. source: Virginia Tech Division of Student Affairs source_url: http://bit.ly/2en1zbv """ err = "institution.vtech" msg = "Incorrect name. Use '{}' instead of '{}'." institution = [ ["Virginia Polytechnic Institute and State Univers...
[ "def", "check_vtech", "(", "text", ")", ":", "err", "=", "\"institution.vtech\"", "msg", "=", "\"Incorrect name. Use '{}' instead of '{}'.\"", "institution", "=", "[", "[", "\"Virginia Polytechnic Institute and State University\"", ",", "[", "\"Virginia Polytechnic and State Un...
31.214286
18.142857
def esc_ansicolor (color): """convert a named color definition to an escaped ANSI color""" control = '' if ";" in color: control, color = color.split(";", 1) control = AnsiControl.get(control, '')+";" cnum = AnsiColor.get(color, '0') return AnsiEsc % (control+cnum)
[ "def", "esc_ansicolor", "(", "color", ")", ":", "control", "=", "''", "if", "\";\"", "in", "color", ":", "control", ",", "color", "=", "color", ".", "split", "(", "\";\"", ",", "1", ")", "control", "=", "AnsiControl", ".", "get", "(", "control", ",",...
36.75
10.125
def sd(series): """ Returns the standard deviation of values in a series. Args: series (pandas.Series): column to summarize. """ if np.issubdtype(series.dtype, np.number): return series.std() else: return np.nan
[ "def", "sd", "(", "series", ")", ":", "if", "np", ".", "issubdtype", "(", "series", ".", "dtype", ",", "np", ".", "number", ")", ":", "return", "series", ".", "std", "(", ")", "else", ":", "return", "np", ".", "nan" ]
20.833333
19.5
def purge_object(self, pid, log_message=None): """ Purge an object from Fedora. Calls :meth:`ApiFacade.purgeObject`. :param pid: pid of the object to be purged :param log_message: optional log message :rtype: boolean """ kwargs = {'pid': pid} if log_mess...
[ "def", "purge_object", "(", "self", ",", "pid", ",", "log_message", "=", "None", ")", ":", "kwargs", "=", "{", "'pid'", ":", "pid", "}", "if", "log_message", ":", "kwargs", "[", "'logMessage'", "]", "=", "log_message", "response", "=", "self", ".", "ap...
35.846154
13.384615
def read_plink(file_prefix, verbose=True): r"""Read PLINK files into Pandas data frames. Parameters ---------- file_prefix : str Path prefix to the set of PLINK files. It supports loading many BED files at once using globstrings wildcard. verbose : bool ``True`` for progress...
[ "def", "read_plink", "(", "file_prefix", ",", "verbose", "=", "True", ")", ":", "from", "dask", ".", "array", "import", "concatenate", "file_prefixes", "=", "sorted", "(", "glob", "(", "file_prefix", ")", ")", "if", "len", "(", "file_prefixes", ")", "==", ...
31.818898
21.88189
def get_services_uids(context=None, analyses_serv=None, values=None): """ This function returns a list of UIDs from analyses services from its parameters. :param analyses_serv: A list (or one object) of service-related info items. see _resolve_items_to_service_uids() docstring. :type analyse...
[ "def", "get_services_uids", "(", "context", "=", "None", ",", "analyses_serv", "=", "None", ",", "values", "=", "None", ")", ":", "if", "not", "analyses_serv", ":", "analyses_serv", "=", "[", "]", "if", "not", "values", ":", "values", "=", "{", "}", "i...
41.708333
21.333333
def ranking_metric(df, method, pos, neg, classes, ascending): """The main function to rank an expression table. :param df: gene_expression DataFrame. :param method: The method used to calculate a correlation or ranking. Default: 'log2_ratio_of_classes'. Others methods are...
[ "def", "ranking_metric", "(", "df", ",", "method", ",", "pos", ",", "neg", ",", "classes", ",", "ascending", ")", ":", "# exclude any zero stds.", "df_mean", "=", "df", ".", "groupby", "(", "by", "=", "classes", ",", "axis", "=", "1", ")", ".", "mean",...
47.333333
35
def compute_samples(self): """ Sample from a Normal distribution with inferred mu and std """ eps = tf.random_normal([self.batch_size, self.eq_samples, self.iw_samples, self.num_latent]) z = tf.reshape(eps * self.std + self.mu, [-1, self.num_latent]) return z
[ "def", "compute_samples", "(", "self", ")", ":", "eps", "=", "tf", ".", "random_normal", "(", "[", "self", ".", "batch_size", ",", "self", ".", "eq_samples", ",", "self", ".", "iw_samples", ",", "self", ".", "num_latent", "]", ")", "z", "=", "tf", "....
57.4
25.8
def _get(self, text): """ Analyze the text to get the right function Parameters ---------- text : str The text that could call a function """ if self.strict: match = self.prog.match(text) if match: cmd = mat...
[ "def", "_get", "(", "self", ",", "text", ")", ":", "if", "self", ".", "strict", ":", "match", "=", "self", ".", "prog", ".", "match", "(", "text", ")", "if", "match", ":", "cmd", "=", "match", ".", "group", "(", ")", "if", "cmd", "in", "self", ...
26.4
13.2
def context(name=None): """Declare that a class defines a context. Contexts are for use with HierarchicalShell for discovering and using functionality from the command line. Args: name (str): Optional name for this context if you don't want to just use the class name. """ ...
[ "def", "context", "(", "name", "=", "None", ")", ":", "def", "_context", "(", "cls", ")", ":", "annotated", "(", "cls", ",", "name", ")", "cls", ".", "context", "=", "True", "return", "cls", "return", "_context" ]
23.222222
22.055556
def data(self): """ Get the content for the response (lazily decoded). """ if self._data is None: self._data = self.response.content.decode("utf-8") return self._data
[ "def", "data", "(", "self", ")", ":", "if", "self", ".", "_data", "is", "None", ":", "self", ".", "_data", "=", "self", ".", "response", ".", "content", ".", "decode", "(", "\"utf-8\"", ")", "return", "self", ".", "_data" ]
30.285714
12.857143
def absent(name, region=None, key=None, keyid=None, profile=None): ''' Ensure a pipeline with the service_name does not exist name Name of the service to ensure a data pipeline does not exist for. region Region to connect to. key Secret key to be used. keyid A...
[ "def", "absent", "(", "name", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'result'", ":", "True", ",", "'comment'", ":", "''"...
28.367347
24.244898
def workspace_from_nothing(self, directory, mets_basename='mets.xml', clobber_mets=False): """ Create an empty workspace. """ if directory is None: directory = tempfile.mkdtemp(prefix=TMP_PREFIX) if not exists(directory): makedirs(directory) mets_...
[ "def", "workspace_from_nothing", "(", "self", ",", "directory", ",", "mets_basename", "=", "'mets.xml'", ",", "clobber_mets", "=", "False", ")", ":", "if", "directory", "is", "None", ":", "directory", "=", "tempfile", ".", "mkdtemp", "(", "prefix", "=", "TMP...
39.333333
15.555556
def open_fileswitcher(self, symbol=False): """Open file list management dialog box.""" if self.fileswitcher is not None and \ self.fileswitcher.is_visible: self.fileswitcher.hide() self.fileswitcher.is_visible = False return if symbol: ...
[ "def", "open_fileswitcher", "(", "self", ",", "symbol", "=", "False", ")", ":", "if", "self", ".", "fileswitcher", "is", "not", "None", "and", "self", ".", "fileswitcher", ".", "is_visible", ":", "self", ".", "fileswitcher", ".", "hide", "(", ")", "self"...
39.142857
9.428571
def align(self): """Align to the next byte, returns the amount of bits skipped""" bits = self._bits self._buffer = 0 self._bits = 0 return bits
[ "def", "align", "(", "self", ")", ":", "bits", "=", "self", ".", "_bits", "self", ".", "_buffer", "=", "0", "self", ".", "_bits", "=", "0", "return", "bits" ]
25.428571
19.142857
def get_environment_tar(self): '''return the environment.tar generated with the Singularity software. We first try the Linux Filesystem expected location in /usr/libexec If not found, we detect the system archicture dirname $(singularity selftest 2>&1 | grep 'lib' | awk '{print $4}' | sed -e '...
[ "def", "get_environment_tar", "(", "self", ")", ":", "from", "sregistry", ".", "utils", "import", "(", "which", ",", "run_command", ")", "# First attempt - look at File System Hierarchy Standard (FHS)", "res", "=", "which", "(", "'singularity'", ")", "[", "'message'",...
41
25.967742
def p_DictionaryMember(p): """DictionaryMember : Type IDENTIFIER Default ";" """ p[0] = model.DictionaryMember(type=p[1], name=p[2], default=p[3])
[ "def", "p_DictionaryMember", "(", "p", ")", ":", "p", "[", "0", "]", "=", "model", ".", "DictionaryMember", "(", "type", "=", "p", "[", "1", "]", ",", "name", "=", "p", "[", "2", "]", ",", "default", "=", "p", "[", "3", "]", ")" ]
37.25
10.25
def read_memory(self, addr, transfer_size=32, now=True): """ read a memory location. By default, a word will be read """ result = self.ap.read_memory(addr, transfer_size, now) # Read callback returned for async reads. def read_memory_cb(): return self...
[ "def", "read_memory", "(", "self", ",", "addr", ",", "transfer_size", "=", "32", ",", "now", "=", "True", ")", ":", "result", "=", "self", ".", "ap", ".", "read_memory", "(", "addr", ",", "transfer_size", ",", "now", ")", "# Read callback returned for asyn...
33.666667
20.866667
def get_all_host_templates(resource_root, cluster_name="default"): """ Get all host templates in a cluster. @param cluster_name: Cluster name. @return: ApiList of ApiHostTemplate objects for all host templates in a cluster. @since: API v3 """ return call(resource_root.get, HOST_TEMPLATES_PATH % (clu...
[ "def", "get_all_host_templates", "(", "resource_root", ",", "cluster_name", "=", "\"default\"", ")", ":", "return", "call", "(", "resource_root", ".", "get", ",", "HOST_TEMPLATES_PATH", "%", "(", "cluster_name", ",", ")", ",", "ApiHostTemplate", ",", "True", ","...
36.7
11.3
def xpathNextPreceding(self, ctxt): """Traversal function for the "preceding" direction the preceding axis contains all nodes in the same document as the context node that are before the context node in document order, excluding any ancestors and excluding attribute nodes...
[ "def", "xpathNextPreceding", "(", "self", ",", "ctxt", ")", ":", "if", "ctxt", "is", "None", ":", "ctxt__o", "=", "None", "else", ":", "ctxt__o", "=", "ctxt", ".", "_o", "ret", "=", "libxml2mod", ".", "xmlXPathNextPreceding", "(", "ctxt__o", ",", "self",...
50.615385
15.307692
def extract(self, url=None, raw_html=None): ''' Extract the most likely article content from the html page Args: url (str): URL to pull and parse raw_html (str): String representation of the HTML page Returns: Article: Representation of th...
[ "def", "extract", "(", "self", ",", "url", "=", "None", ",", "raw_html", "=", "None", ")", ":", "crawl_candidate", "=", "CrawlCandidate", "(", "self", ".", "config", ",", "url", ",", "raw_html", ")", "return", "self", ".", "__crawl", "(", "crawl_candidat...
46.363636
21.454545
def from_statement(cls, statement, filename='<expr>'): """A helper to construct a PythonFile from a triple-quoted string, for testing. :param statement: Python file contents :return: Instance of PythonFile """ lines = textwrap.dedent(statement).split('\n') if lines and not lines[0]: # Remove th...
[ "def", "from_statement", "(", "cls", ",", "statement", ",", "filename", "=", "'<expr>'", ")", ":", "lines", "=", "textwrap", ".", "dedent", "(", "statement", ")", ".", "split", "(", "'\\n'", ")", "if", "lines", "and", "not", "lines", "[", "0", "]", "...
44.666667
14.666667
def _process_response(cls, response): """ Examine the response and raise an error is something is off """ if len(response) != 1: raise BadResponseError("Malformed response: {}".format(response)) stats = list(itervalues(response))[0] if not len(stats): ...
[ "def", "_process_response", "(", "cls", ",", "response", ")", ":", "if", "len", "(", "response", ")", "!=", "1", ":", "raise", "BadResponseError", "(", "\"Malformed response: {}\"", ".", "format", "(", "response", ")", ")", "stats", "=", "list", "(", "iter...
33.916667
19.916667
def list(self, **kwds): """ Endpoint: /tags/list.json Returns a list of Tag objects. """ tags = self._client.get("/tags/list.json", **kwds)["result"] tags = self._result_to_list(tags) return [Tag(self._client, tag) for tag in tags]
[ "def", "list", "(", "self", ",", "*", "*", "kwds", ")", ":", "tags", "=", "self", ".", "_client", ".", "get", "(", "\"/tags/list.json\"", ",", "*", "*", "kwds", ")", "[", "\"result\"", "]", "tags", "=", "self", ".", "_result_to_list", "(", "tags", ...
31.111111
12.222222
def is_import_exception(mod): """Check module name to see if import has been whitelisted. Import based rules should not run on any whitelisted module """ return (mod in IMPORT_EXCEPTIONS or any(mod.startswith(m + '.') for m in IMPORT_EXCEPTIONS))
[ "def", "is_import_exception", "(", "mod", ")", ":", "return", "(", "mod", "in", "IMPORT_EXCEPTIONS", "or", "any", "(", "mod", ".", "startswith", "(", "m", "+", "'.'", ")", "for", "m", "in", "IMPORT_EXCEPTIONS", ")", ")" ]
39.285714
15.142857
def covariance_points(self,x0,y0,xother,yother): """ get the covariance between base point x0,y0 and other points xother,yother implied by Vario2d Parameters ---------- x0 : (float) x-coordinate of base point y0 : (float) y-coordinate of base poin...
[ "def", "covariance_points", "(", "self", ",", "x0", ",", "y0", ",", "xother", ",", "yother", ")", ":", "dx", "=", "x0", "-", "xother", "dy", "=", "y0", "-", "yother", "dxx", ",", "dyy", "=", "self", ".", "_apply_rotation", "(", "dx", ",", "dy", "...
27.935484
15.806452
def get_security_zones_activation(self) -> (bool, bool): """ returns the value of the security zones if they are armed or not Returns internal True if the internal zone is armed external True if the external zone is armed """ ...
[ "def", "get_security_zones_activation", "(", "self", ")", "->", "(", "bool", ",", "bool", ")", ":", "internal_active", "=", "False", "external_active", "=", "False", "for", "g", "in", "self", ".", "groups", ":", "if", "isinstance", "(", "g", ",", "Security...
37.833333
10.555556
def get_perm_name(cls, action, full=True): """ Return the name of the permission for a given model and action. By default it returns the full permission name `app_label.perm_codename`. If `full=False`, it returns only the `perm_codename`. """ codename = "{}_{}".format(action, cls.__name__.lower...
[ "def", "get_perm_name", "(", "cls", ",", "action", ",", "full", "=", "True", ")", ":", "codename", "=", "\"{}_{}\"", ".", "format", "(", "action", ",", "cls", ".", "__name__", ".", "lower", "(", ")", ")", "if", "full", ":", "return", "\"{}.{}\"", "."...
37
22.818182
def get_peptable_headerfields(headertypes, lookup=False, poolnames=False): """Called by driver to generate headerfields object""" field_defs = {'isoquant': get_isoquant_fields, 'precursorquant': get_precursorquant_fields, 'peptidefdr': get_peptidefdr_fields, ...
[ "def", "get_peptable_headerfields", "(", "headertypes", ",", "lookup", "=", "False", ",", "poolnames", "=", "False", ")", ":", "field_defs", "=", "{", "'isoquant'", ":", "get_isoquant_fields", ",", "'precursorquant'", ":", "get_precursorquant_fields", ",", "'peptide...
55.888889
18.555556
def pick_peaks(nc, L=16, offset_denom=0.1): """Obtain peaks from a novelty curve using an adaptive threshold.""" offset = nc.mean() * float(offset_denom) th = filters.median_filter(nc, size=L) + offset #th = filters.gaussian_filter(nc, sigma=L/2., mode="nearest") + offset #import pylab as plt #p...
[ "def", "pick_peaks", "(", "nc", ",", "L", "=", "16", ",", "offset_denom", "=", "0.1", ")", ":", "offset", "=", "nc", ".", "mean", "(", ")", "*", "float", "(", "offset_denom", ")", "th", "=", "filters", ".", "median_filter", "(", "nc", ",", "size", ...
36.111111
13.777778
def reset(self, total_size=None): """Remove all file system contents and reset the root.""" self.root = FakeDirectory(self.path_separator, filesystem=self) self.cwd = self.root.name self.open_files = [] self._free_fd_heap = [] self._last_ino = 0 self._last_dev = ...
[ "def", "reset", "(", "self", ",", "total_size", "=", "None", ")", ":", "self", ".", "root", "=", "FakeDirectory", "(", "self", ".", "path_separator", ",", "filesystem", "=", "self", ")", "self", ".", "cwd", "=", "self", ".", "root", ".", "name", "sel...
36.25
13.666667
def list_firmware_manifests(self, **kwargs): """List all manifests. :param int limit: number of manifests to retrieve :param str order: sort direction of manifests when ordered by time. 'desc' or 'asc' :param str after: get manifests after given `image_id` :param dict filters: D...
[ "def", "list_firmware_manifests", "(", "self", ",", "*", "*", "kwargs", ")", ":", "kwargs", "=", "self", ".", "_verify_sort_options", "(", "kwargs", ")", "kwargs", "=", "self", ".", "_verify_filters", "(", "kwargs", ",", "FirmwareManifest", ",", "True", ")",...
51.428571
20.928571
def connect(self): """ Creates a new KazooClient and establishes a connection. Passes the client the `handle_connection_change` method as a callback to fire when the Zookeeper connection changes state. """ self.client = client.KazooClient(hosts=",".join(self.hosts)) ...
[ "def", "connect", "(", "self", ")", ":", "self", ".", "client", "=", "client", ".", "KazooClient", "(", "hosts", "=", "\",\"", ".", "join", "(", "self", ".", "hosts", ")", ")", "self", ".", "client", ".", "add_listener", "(", "self", ".", "handle_con...
36.727273
21.818182
def emit(self, data_frame): """Use this function in emit data into the store. :param data_frame: DataFrame to be recorded. """ if self.result is not None: raise MultipleEmitsError() data_frame.columns = [self.prefix + '__' + c for c in d...
[ "def", "emit", "(", "self", ",", "data_frame", ")", ":", "if", "self", ".", "result", "is", "not", "None", ":", "raise", "MultipleEmitsError", "(", ")", "data_frame", ".", "columns", "=", "[", "self", ".", "prefix", "+", "'__'", "+", "c", "for", "c",...
36.2
11
def _decode(rawstr): """Convert a raw string to a Message. """ # Check for the magick word. try: rawstr = rawstr.decode('utf-8') except (AttributeError, UnicodeEncodeError): pass except (UnicodeDecodeError): try: rawstr = rawstr.decode('iso-8859-1') ex...
[ "def", "_decode", "(", "rawstr", ")", ":", "# Check for the magick word.", "try", ":", "rawstr", "=", "rawstr", ".", "decode", "(", "'utf-8'", ")", "except", "(", "AttributeError", ",", "UnicodeEncodeError", ")", ":", "pass", "except", "(", "UnicodeDecodeError",...
32.166667
16
def get_hist(rfile, histname, get_overflow=False): """Read a 1D Histogram.""" import root_numpy as rnp rfile = open_rfile(rfile) hist = rfile[histname] xlims = np.array(list(hist.xedges())) bin_values = rnp.hist2array(hist, include_overflow=get_overflow) rfile.close() return bin_values,...
[ "def", "get_hist", "(", "rfile", ",", "histname", ",", "get_overflow", "=", "False", ")", ":", "import", "root_numpy", "as", "rnp", "rfile", "=", "open_rfile", "(", "rfile", ")", "hist", "=", "rfile", "[", "histname", "]", "xlims", "=", "np", ".", "arr...
31.7
15.1
def execute(handlers): ''' Run the command :return: ''' # verify if the environment variables are correctly set check_environment() # create the argument parser parser = create_parser(handlers) # if no argument is provided, print help and exit if len(sys.argv[1:]) == 0: parser.print_help() ...
[ "def", "execute", "(", "handlers", ")", ":", "# verify if the environment variables are correctly set", "check_environment", "(", ")", "# create the argument parser", "parser", "=", "create_parser", "(", "handlers", ")", "# if no argument is provided, print help and exit", "if", ...
26
22.904762
def create(cls, name, enabled=True, superuser=True): """ Create a new API Client. Once client is created, you can create a new password by:: >>> client = ApiClient.create('myclient') >>> print(client) ApiClient(name=myclient) >>> client.change_pas...
[ "def", "create", "(", "cls", ",", "name", ",", "enabled", "=", "True", ",", "superuser", "=", "True", ")", ":", "json", "=", "{", "'enabled'", ":", "enabled", ",", "'name'", ":", "name", ",", "'superuser'", ":", "superuser", "}", "return", "ElementCrea...
32.913043
13.608696
def bakery_client_for_controller(self, controller_name): '''Make a copy of the bakery client with a the appropriate controller's cookiejar in it. ''' bakery_client = self.bakery_client if bakery_client: bakery_client = copy.copy(bakery_client) else: ...
[ "def", "bakery_client_for_controller", "(", "self", ",", "controller_name", ")", ":", "bakery_client", "=", "self", ".", "bakery_client", "if", "bakery_client", ":", "bakery_client", "=", "copy", ".", "copy", "(", "bakery_client", ")", "else", ":", "bakery_client"...
39.5
18
def aloha_to_etree(html_source): """ Converts HTML5 from Aloha editor output to a lxml etree. """ xml = _tidy2xhtml5(html_source) for i, transform in enumerate(ALOHA2HTML_TRANSFORM_PIPELINE): xml = transform(xml) return xml
[ "def", "aloha_to_etree", "(", "html_source", ")", ":", "xml", "=", "_tidy2xhtml5", "(", "html_source", ")", "for", "i", ",", "transform", "in", "enumerate", "(", "ALOHA2HTML_TRANSFORM_PIPELINE", ")", ":", "xml", "=", "transform", "(", "xml", ")", "return", "...
40.333333
12.666667
def _build_latex_array(self, aliases=None): """Returns an array of strings containing \\LaTeX for this circuit. If aliases is not None, aliases contains a dict mapping the current qubits in the circuit to new qubit names. We will deduce the register names and sizes from aliases. ...
[ "def", "_build_latex_array", "(", "self", ",", "aliases", "=", "None", ")", ":", "columns", "=", "1", "# Rename qregs if necessary", "if", "aliases", ":", "qregdata", "=", "{", "}", "for", "q", "in", "aliases", ".", "values", "(", ")", ":", "if", "q", ...
55.248227
22.3026
def youtube_meta(client, channel, nick, message, match): """ Return meta information about a video """ if not API_KEY: return 'You must set YOUTUBE_DATA_API_KEY in settings!' identifier = match[0] params = { 'id': identifier, 'key': API_KEY, 'part': 'snippet,statistics,co...
[ "def", "youtube_meta", "(", "client", ",", "channel", ",", "nick", ",", "message", ",", "match", ")", ":", "if", "not", "API_KEY", ":", "return", "'You must set YOUTUBE_DATA_API_KEY in settings!'", "identifier", "=", "match", "[", "0", "]", "params", "=", "{",...
37.451613
21.677419
def add_task_to_diagram(self, process_id, task_name="", node_id=None): """ Adds a Task element to BPMN diagram. User-defined attributes: - name :param process_id: string object. ID of parent process, :param task_name: string object. Name of task, :param node_id...
[ "def", "add_task_to_diagram", "(", "self", ",", "process_id", ",", "task_name", "=", "\"\"", ",", "node_id", "=", "None", ")", ":", "return", "self", ".", "add_flow_node_to_diagram", "(", "process_id", ",", "consts", ".", "Consts", ".", "task", ",", "task_na...
40
26.142857
def submit_snl(self, snl): """ Submits a list of StructureNL to the Materials Project site. .. note:: As of now, this MP REST feature is open only to a select group of users. Opening up submissions to all users is being planned for the future. Args:...
[ "def", "submit_snl", "(", "self", ",", "snl", ")", ":", "try", ":", "snl", "=", "snl", "if", "isinstance", "(", "snl", ",", "list", ")", "else", "[", "snl", "]", "jsondata", "=", "[", "s", ".", "as_dict", "(", ")", "for", "s", "in", "snl", "]",...
36.125
22.125
def response(self, component_id, component=None, **kwargs): """Add a response which can be referenced. :param str component_id: ref_id to use as reference :param dict component: response fields :param dict kwargs: plugin-specific arguments """ if component_id in self._re...
[ "def", "response", "(", "self", ",", "component_id", ",", "component", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "component_id", "in", "self", ".", "_responses", ":", "raise", "DuplicateComponentNameError", "(", "'Another response with name \"{}\" is a...
38.347826
14.652174
def new_contact(cls, address_book, supported_private_objects, version, localize_dates): """Use this to create a new and empty contact.""" return cls(address_book, None, supported_private_objects, version, localize_dates)
[ "def", "new_contact", "(", "cls", ",", "address_book", ",", "supported_private_objects", ",", "version", ",", "localize_dates", ")", ":", "return", "cls", "(", "address_book", ",", "None", ",", "supported_private_objects", ",", "version", ",", "localize_dates", ")...
52
17
def _store_inferential_results(self, value_array, index_names, attribute_name, series_name=None, column_names=None): """ Store th...
[ "def", "_store_inferential_results", "(", "self", ",", "value_array", ",", "index_names", ",", "attribute_name", ",", "series_name", "=", "None", ",", "column_names", "=", "None", ")", ":", "if", "len", "(", "value_array", ".", "shape", ")", "==", "1", ":", ...
45.854167
20.520833
def _calc_eta(self): """ Calculates estimated time left until completion. """ elapsed = self._elapsed() if self.cnt == 0 or elapsed < 0.001: return None rate = float(self.cnt) / elapsed self.eta = (float(self.max_iter) - float(self.cnt)) / rate
[ "def", "_calc_eta", "(", "self", ")", ":", "elapsed", "=", "self", ".", "_elapsed", "(", ")", "if", "self", ".", "cnt", "==", "0", "or", "elapsed", "<", "0.001", ":", "return", "None", "rate", "=", "float", "(", "self", ".", "cnt", ")", "/", "ela...
41.428571
10.571429
def get_s3_region_from_endpoint(endpoint): """ Extracts and returns an AWS S3 region from an endpoint of form `s3-ap-southeast-1.amazonaws.com` :param endpoint: Endpoint region to be extracted. """ # Extract region by regex search. m = _EXTRACT_REGION_REGEX.search(endpoint) if m: ...
[ "def", "get_s3_region_from_endpoint", "(", "endpoint", ")", ":", "# Extract region by regex search.", "m", "=", "_EXTRACT_REGION_REGEX", ".", "search", "(", "endpoint", ")", "if", "m", ":", "# Regex matches, we have found a region.", "region", "=", "m", ".", "group", ...
30.73913
13.869565
def zoom_in_pixel(self, curr_pixel): """ return the curr_frag at a higher resolution""" low_frag = curr_pixel[0] high_frag = curr_pixel[1] level = curr_pixel[2] if level > 0: str_level = str(level) low_sub_low = self.spec_level[str_level]["fragments_dict"]...
[ "def", "zoom_in_pixel", "(", "self", ",", "curr_pixel", ")", ":", "low_frag", "=", "curr_pixel", "[", "0", "]", "high_frag", "=", "curr_pixel", "[", "1", "]", "level", "=", "curr_pixel", "[", "2", "]", "if", "level", ">", "0", ":", "str_level", "=", ...
39.37037
15
def from_stream(cls, stream): """ Read the first occurrence of ScfCycle from stream. Returns: None if no `ScfCycle` entry is found. """ fields = _magic_parser(stream, magic=cls.MAGIC) if fields: fields.pop("iter") return cls(fields) ...
[ "def", "from_stream", "(", "cls", ",", "stream", ")", ":", "fields", "=", "_magic_parser", "(", "stream", ",", "magic", "=", "cls", ".", "MAGIC", ")", "if", "fields", ":", "fields", ".", "pop", "(", "\"iter\"", ")", "return", "cls", "(", "fields", ")...
24.5
17.357143
def status(sec): """Toolbar progressive status """ if _meta_.prg_bar in ["on", "ON"]: syms = ["|", "/", "-", "\\"] for sym in syms: sys.stdout.write("\b{0}{1}{2}".format(_meta_.color["GREY"], sym, _meta_.color["ENDC"])) ...
[ "def", "status", "(", "sec", ")", ":", "if", "_meta_", ".", "prg_bar", "in", "[", "\"on\"", ",", "\"ON\"", "]", ":", "syms", "=", "[", "\"|\"", ",", "\"/\"", ",", "\"-\"", ",", "\"\\\\\"", "]", "for", "sym", "in", "syms", ":", "sys", ".", "stdout...
36.6
13
def auc_roc_score(input:Tensor, targ:Tensor): "Using trapezoid method to calculate the area under roc curve" fpr, tpr = roc_curve(input, targ) d = fpr[1:] - fpr[:-1] sl1, sl2 = [slice(None)], [slice(None)] sl1[-1], sl2[-1] = slice(1, None), slice(None, -1) return (d * (tpr[tuple(sl1)] + tpr[tupl...
[ "def", "auc_roc_score", "(", "input", ":", "Tensor", ",", "targ", ":", "Tensor", ")", ":", "fpr", ",", "tpr", "=", "roc_curve", "(", "input", ",", "targ", ")", "d", "=", "fpr", "[", "1", ":", "]", "-", "fpr", "[", ":", "-", "1", "]", "sl1", "...
48
12.857143
def find_alliteration(self): """ Find alliterations in the complete verse. :return: """ if len(self.phonological_features_text) == 0: logger.error("No phonological transcription found") raise ValueError else: first_sounds = [] ...
[ "def", "find_alliteration", "(", "self", ")", ":", "if", "len", "(", "self", ".", "phonological_features_text", ")", "==", "0", ":", "logger", ".", "error", "(", "\"No phonological transcription found\"", ")", "raise", "ValueError", "else", ":", "first_sounds", ...
49.03125
19.15625
def translate_codons(sequence): '''Return the translated protein from 'sequence' assuming +1 reading frame Source - http://adamcoster.com/2011/01/13/python-clean-up-and-translate-nucleotide-sequences/ ''' return ''.join([gencode.get(sequence[3*i:3*i+3],'X') for i in range(len(sequence)//3)])
[ "def", "translate_codons", "(", "sequence", ")", ":", "return", "''", ".", "join", "(", "[", "gencode", ".", "get", "(", "sequence", "[", "3", "*", "i", ":", "3", "*", "i", "+", "3", "]", ",", "'X'", ")", "for", "i", "in", "range", "(", "len", ...
61.4
38.2
def finalize(self): """ Is called before destruction. Can be used to clean-up resources """ logger.debug("Finalizing: {}".format(self)) self.plotItem.scene().sigMouseMoved.disconnect(self.mouseMoved) self.plotItem.close() self.graphicsLayoutWidget.close()
[ "def", "finalize", "(", "self", ")", ":", "logger", ".", "debug", "(", "\"Finalizing: {}\"", ".", "format", "(", "self", ")", ")", "self", ".", "plotItem", ".", "scene", "(", ")", ".", "sigMouseMoved", ".", "disconnect", "(", "self", ".", "mouseMoved", ...
42.428571
10.714286
def getextensibleindex(self, key, name): """ Get the index of the first extensible item. Only for internal use. # TODO : hide this Parameters ---------- key : str The type of IDF object. This must be in ALL_CAPS. name : str The name of th...
[ "def", "getextensibleindex", "(", "self", ",", "key", ",", "name", ")", ":", "return", "getextensibleindex", "(", "self", ".", "idfobjects", ",", "self", ".", "model", ",", "self", ".", "idd_info", ",", "key", ",", "name", ")" ]
23.333333
19.619048
def DEFINE_flag(flag, flag_values=_flagvalues.FLAGS, module_name=None): # pylint: disable=invalid-name """Registers a 'Flag' object with a 'FlagValues' object. By default, the global FLAGS 'FlagValue' object is used. Typical users will use one of the more specialized DEFINE_xxx functions, such as DEFINE_stri...
[ "def", "DEFINE_flag", "(", "flag", ",", "flag_values", "=", "_flagvalues", ".", "FLAGS", ",", "module_name", "=", "None", ")", ":", "# pylint: disable=invalid-name", "# Copying the reference to flag_values prevents pychecker warnings.", "fv", "=", "flag_values", "fv", "["...
44.814815
24.925926
def dump_code(disassembly, pc = None, bLowercase = True, bits = None): """ Dump a disassembly. Optionally mark where the program counter is. ...
[ "def", "dump_code", "(", "disassembly", ",", "pc", "=", "None", ",", "bLowercase", "=", "True", ",", "bits", "=", "None", ")", ":", "if", "not", "disassembly", ":", "return", "''", "table", "=", "Table", "(", "sep", "=", "' | '", ")", "for", "(", "...
37.891892
20.972973
def _convert_choices(self, choices): """Auto create db values then call super method""" final_choices = [] for choice in choices: if isinstance(choice, ChoiceEntry): final_choices.append(choice) continue original_choice = choice ...
[ "def", "_convert_choices", "(", "self", ",", "choices", ")", ":", "final_choices", "=", "[", "]", "for", "choice", "in", "choices", ":", "if", "isinstance", "(", "choice", ",", "ChoiceEntry", ")", ":", "final_choices", ".", "append", "(", "choice", ")", ...
34.811321
19.943396
def compute_taxes(self, precision=None): ''' Returns the total amount of taxes of this group. @param precision:int Total amount of discounts @return: Decimal ''' return sum([line.compute_taxes(precision) for line in self.__lines])
[ "def", "compute_taxes", "(", "self", ",", "precision", "=", "None", ")", ":", "return", "sum", "(", "[", "line", ".", "compute_taxes", "(", "precision", ")", "for", "line", "in", "self", ".", "__lines", "]", ")" ]
38.857143
20
def centerOn(self, point): """ Centers this node on the inputed point. :param point | <QPointF> """ rect = self.rect() x = point.x() - rect.width() / 2.0 y = point.y() - rect.height() / 2.0 self.setPos(x, y)
[ "def", "centerOn", "(", "self", ",", "point", ")", ":", "rect", "=", "self", ".", "rect", "(", ")", "x", "=", "point", ".", "x", "(", ")", "-", "rect", ".", "width", "(", ")", "/", "2.0", "y", "=", "point", ".", "y", "(", ")", "-", "rect", ...
25.818182
11.090909
def get_history(self): """Get history of applied upgrades.""" self.load_history() return map(lambda x: (x, self.history[x]), self.ordered_history)
[ "def", "get_history", "(", "self", ")", ":", "self", ".", "load_history", "(", ")", "return", "map", "(", "lambda", "x", ":", "(", "x", ",", "self", ".", "history", "[", "x", "]", ")", ",", "self", ".", "ordered_history", ")" ]
41.75
15.75
def update(self, other: 'Language') -> 'Language': """ Update this Language with the fields of another Language. """ return Language.make( language=other.language or self.language, extlangs=other.extlangs or self.extlangs, script=other.script or self.s...
[ "def", "update", "(", "self", ",", "other", ":", "'Language'", ")", "->", "'Language'", ":", "return", "Language", ".", "make", "(", "language", "=", "other", ".", "language", "or", "self", ".", "language", ",", "extlangs", "=", "other", ".", "extlangs",...
41.230769
12.153846
def current_model(self, controller_name=None, model_only=False): '''Return the current model, qualified by its controller name. If controller_name is specified, the current model for that controller will be returned. If model_only is true, only the model name, not qualified by i...
[ "def", "current_model", "(", "self", ",", "controller_name", "=", "None", ",", "model_only", "=", "False", ")", ":", "# TODO respect JUJU_MODEL environment variable.", "if", "not", "controller_name", ":", "controller_name", "=", "self", ".", "current_controller", "(",...
43.315789
16.157895
def patch(destination, name=None, settings=None): """Decorator to create a patch. The object being decorated becomes the :attr:`~Patch.obj` attribute of the patch. Parameters ---------- destination : object Patch destination. name : str Name of the attribute at the destinat...
[ "def", "patch", "(", "destination", ",", "name", "=", "None", ",", "settings", "=", "None", ")", ":", "def", "decorator", "(", "wrapped", ")", ":", "base", "=", "_get_base", "(", "wrapped", ")", "name_", "=", "base", ".", "__name__", "if", "name", "i...
24.5
21.5
def parse_global_args(argv): """Parse all global iotile tool arguments. Any flag based argument at the start of the command line is considered as a global flag and parsed. The first non flag argument starts the commands that are passed to the underlying hierarchical shell. Args: argv (lis...
[ "def", "parse_global_args", "(", "argv", ")", ":", "parser", "=", "create_parser", "(", ")", "args", "=", "parser", ".", "parse_args", "(", "argv", ")", "should_log", "=", "args", ".", "include", "or", "args", ".", "exclude", "or", "(", "args", ".", "v...
32.516129
22.629032
def add_rrset(self, section, rrset, **kw): """Add the rrset to the specified section. Any keyword arguments are passed on to the rdataset's to_wire() routine. @param section: the section @type section: int @param rrset: the rrset @type rrset: dns.rrset.RRset obj...
[ "def", "add_rrset", "(", "self", ",", "section", ",", "rrset", ",", "*", "*", "kw", ")", ":", "self", ".", "_set_section", "(", "section", ")", "before", "=", "self", ".", "output", ".", "tell", "(", ")", "n", "=", "rrset", ".", "to_wire", "(", "...
31.95
13.9
def predict(self, a, b): """ Compute the test statistic Args: a (array-like): Variable 1 b (array-like): Variable 2 Returns: float: test statistic """ a = np.array(a).reshape((-1, 1)) b = np.array(b).reshape((-1, 1)) return (m...
[ "def", "predict", "(", "self", ",", "a", ",", "b", ")", ":", "a", "=", "np", ".", "array", "(", "a", ")", ".", "reshape", "(", "(", "-", "1", ",", "1", ")", ")", "b", "=", "np", ".", "array", "(", "b", ")", ".", "reshape", "(", "(", "-"...
30.692308
17.384615
def insert_tile(self, tile_info): """Add or replace an entry in the tile cache. Args: tile_info (TileInfo): The newly registered tile. """ for i, tile in enumerate(self.registered_tiles): if tile.slot == tile_info.slot: self.registered_tiles[i] =...
[ "def", "insert_tile", "(", "self", ",", "tile_info", ")", ":", "for", "i", ",", "tile", "in", "enumerate", "(", "self", ".", "registered_tiles", ")", ":", "if", "tile", ".", "slot", "==", "tile_info", ".", "slot", ":", "self", ".", "registered_tiles", ...
30
17.692308
def add_upsert(self, value, criteria): """Add a tag or populator to the batch by value and criteria""" value = value.strip() v = value.lower() self.lower_val_to_val[v] = value criteria_array = self.upserts.get(v) if criteria_array is None: criteria_array = []...
[ "def", "add_upsert", "(", "self", ",", "value", ",", "criteria", ")", ":", "value", "=", "value", ".", "strip", "(", ")", "v", "=", "value", ".", "lower", "(", ")", "self", ".", "lower_val_to_val", "[", "v", "]", "=", "value", "criteria_array", "=", ...
40.928571
10.571429
def _backtick_columns(cols): """ Quote the column names """ def bt(s): b = '' if s == '*' or not s else '`' return [_ for _ in [b + (s or '') + b] if _] formatted = [] for c in cols: if c[0] == '#': formatted.append(c[1...
[ "def", "_backtick_columns", "(", "cols", ")", ":", "def", "bt", "(", "s", ")", ":", "b", "=", "''", "if", "s", "==", "'*'", "or", "not", "s", "else", "'`'", "return", "[", "_", "for", "_", "in", "[", "b", "+", "(", "s", "or", "''", ")", "+"...
35.35
18.95
def set_item_class_name_on_custom_generator_class(cls): """ Set the attribute `cls.__tohu_items_name__` to a string which defines the name of the namedtuple class which will be used to produce items for the custom generator. By default this will be the first part of the class name (before '...Gener...
[ "def", "set_item_class_name_on_custom_generator_class", "(", "cls", ")", ":", "if", "'__tohu__items__name__'", "in", "cls", ".", "__dict__", ":", "logger", ".", "debug", "(", "f\"Using item class name '{cls.__tohu_items_name__}' (derived from attribute '__tohu_items_name__')\"", ...
45.166667
28.833333
def size_on_disk(self): """ :return: size of data and indices in bytes on the storage device """ ret = self.connection.query( 'SHOW TABLE STATUS FROM `{database}` WHERE NAME="{table}"'.format( database=self.database, table=self.table_name), as_dict=True).fetch...
[ "def", "size_on_disk", "(", "self", ")", ":", "ret", "=", "self", ".", "connection", ".", "query", "(", "'SHOW TABLE STATUS FROM `{database}` WHERE NAME=\"{table}\"'", ".", "format", "(", "database", "=", "self", ".", "database", ",", "table", "=", "self", ".", ...
46.75
19.25
def sort_queryset(queryset, request, context=None): """ Returns a sorted queryset The context argument is only used in the template tag """ sort_by = request.GET.get('sort_by') if sort_by: if sort_by in [el.name for el in queryset.model._meta.fields]: queryset = queryset.order_by...
[ "def", "sort_queryset", "(", "queryset", ",", "request", ",", "context", "=", "None", ")", ":", "sort_by", "=", "request", ".", "GET", ".", "get", "(", "'sort_by'", ")", "if", "sort_by", ":", "if", "sort_by", "in", "[", "el", ".", "name", "for", "el"...
40.961538
14.807692
def get_fixed_param_names(self) -> List[str]: """ Get the fixed params of the network. :return: List of strings, names of the layers """ args = set(self.args.keys()) | set(self.auxs.keys()) return list(args & set(self.sym.list_arguments()))
[ "def", "get_fixed_param_names", "(", "self", ")", "->", "List", "[", "str", "]", ":", "args", "=", "set", "(", "self", ".", "args", ".", "keys", "(", ")", ")", "|", "set", "(", "self", ".", "auxs", ".", "keys", "(", ")", ")", "return", "list", ...
31.333333
15.555556
def longest_dimension_first(vector, start=(0, 0), width=None, height=None): """List the (x, y) steps on a longest-dimension first route. Note that when multiple dimensions are the same magnitude, one will be chosen at random with uniform probability. Parameters ---------- vector : (x, y, z) ...
[ "def", "longest_dimension_first", "(", "vector", ",", "start", "=", "(", "0", ",", "0", ")", ",", "width", "=", "None", ",", "height", "=", "None", ")", ":", "x", ",", "y", "=", "start", "out", "=", "[", "]", "for", "dimension", ",", "magnitude", ...
34.061538
21.646154
def _set_ipv6_track(self, v, load=False): """ Setter method for ipv6_track, mapped from YANG variable /rbridge_id/interface/ve/ipv6/ipv6_local_anycast_gateway/ipv6_track (container) If this variable is read-only (config: false) in the source YANG file, then _set_ipv6_track is considered as a private ...
[ "def", "_set_ipv6_track", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", "v", ",", "bas...
76
36.045455