text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def netstats(): ''' Return the network stats for this minion .. versionchanged:: 2016.11.4 Added support for AIX .. versionchanged:: 2018.3.0 Added support for OpenBSD CLI Example: .. code-block:: bash salt '*' status.netstats ''' def linux_netstats(): ...
[ "def", "netstats", "(", ")", ":", "def", "linux_netstats", "(", ")", ":", "'''\n linux specific netstats implementation\n '''", "ret", "=", "{", "}", "try", ":", "with", "salt", ".", "utils", ".", "files", ".", "fopen", "(", "'/proc/net/netstat'", ...
30.15873
0.00051
def get_bios_firmware_version(snmp_client): """Get bios firmware version of the node. :param snmp_client: an SNMP client object. :raises: SNMPFailure if SNMP operation failed. :returns: a string of bios firmware version. """ try: bios_firmware_version = snmp_client.get(BIOS_FW_VERSION_...
[ "def", "get_bios_firmware_version", "(", "snmp_client", ")", ":", "try", ":", "bios_firmware_version", "=", "snmp_client", ".", "get", "(", "BIOS_FW_VERSION_OID", ")", "return", "six", ".", "text_type", "(", "bios_firmware_version", ")", "except", "SNMPFailure", "as...
35.428571
0.001965
def compute_curl(self, vector_field): """Computes the curl of a vector field over the mesh. While the vector field is point-based, the curl will be cell-based. The approximation is based on .. math:: n\\cdot curl(F) = \\lim_{A\\to 0} |A|^{-1} <\\int_{dGamma}, F> dr; ...
[ "def", "compute_curl", "(", "self", ",", "vector_field", ")", ":", "# Compute the projection of A on the edge at each edge midpoint.", "# Take the average of `vector_field` at the endpoints to get the", "# approximate value at the edge midpoint.", "A", "=", "0.5", "*", "numpy", ".", ...
42.59375
0.001435
def AddArguments(cls, argument_group): """Adds command line arguments to an argument group. This function takes an argument parser or an argument group object and adds to it all the command line arguments this helper supports. Args: argument_group (argparse._ArgumentGroup|argparse.ArgumentParser...
[ "def", "AddArguments", "(", "cls", ",", "argument_group", ")", ":", "argument_group", ".", "add_argument", "(", "'--slice'", ",", "metavar", "=", "'DATE'", ",", "dest", "=", "'slice'", ",", "type", "=", "str", ",", "default", "=", "''", ",", "action", "=...
49.52381
0.000471
def should_trigger(self, dt): """ Composes the two rules with a lazy composer. """ return self.composer( self.first.should_trigger, self.second.should_trigger, dt )
[ "def", "should_trigger", "(", "self", ",", "dt", ")", ":", "return", "self", ".", "composer", "(", "self", ".", "first", ".", "should_trigger", ",", "self", ".", "second", ".", "should_trigger", ",", "dt", ")" ]
25.777778
0.008333
def save_archive(archive): """ Save `archive` into database and into proper indexes. Attr: archive (obj): Instance of the :class:`.DBArchive`. Returns: obj: :class:`.DBArchive` without data. Raises: InvalidType: When the `archive` is not instance of :class:`.DBArchive`. ...
[ "def", "save_archive", "(", "archive", ")", ":", "_assert_obj_type", "(", "archive", ",", "obj_type", "=", "DBArchive", ")", "_get_handler", "(", ")", ".", "store_object", "(", "archive", ")", "return", "archive", ".", "to_comm", "(", "light_request", "=", "...
29.7
0.001631
def create_default_directory_layout(root, NAME, VERSION, VENDOR, filename_set): """ Create the wix default target directory layout and return the innermost directory. We assume that the XML tree delivered in the root argument already contains the Product tag. Everything is put under the PFiles dir...
[ "def", "create_default_directory_layout", "(", "root", ",", "NAME", ",", "VERSION", ",", "VENDOR", ",", "filename_set", ")", ":", "doc", "=", "Document", "(", ")", "d1", "=", "doc", ".", "createElement", "(", "'Directory'", ")", "d1", ".", "attributes", "[...
38.878049
0.029376
def u24(self, name, value=None, align=None): """Add an unsigned 3 byte integer field to template. This is an convenience method that simply calls `Uint` keyword with predefined length.""" self.uint(3, name, value, align)
[ "def", "u24", "(", "self", ",", "name", ",", "value", "=", "None", ",", "align", "=", "None", ")", ":", "self", ".", "uint", "(", "3", ",", "name", ",", "value", ",", "align", ")" ]
48.2
0.012245
def save(obj, path=None, name=None, sep=_sep, deep=False, mode='npz', strip=None, compressed=False, verb=True, return_pfe=False): """ Save the ToFu object ToFu provides built-in saving and loading functions for ToFu objects. Specifying saving path ad name is optional (defaults recommended) The...
[ "def", "save", "(", "obj", ",", "path", "=", "None", ",", "name", "=", "None", ",", "sep", "=", "_sep", ",", "deep", "=", "False", ",", "mode", "=", "'npz'", ",", "strip", "=", "None", ",", "compressed", "=", "False", ",", "verb", "=", "True", ...
38.579545
0.002298
def new_class_from_gtype(gtype): """Create a new class for a gtype not in the gir. The caller is responsible for caching etc. """ if gtype.is_a(PGType.from_name("GObject")): parent = gtype.parent.pytype if parent is None or parent == PGType.from_name("void"): return ...
[ "def", "new_class_from_gtype", "(", "gtype", ")", ":", "if", "gtype", ".", "is_a", "(", "PGType", ".", "from_name", "(", "\"GObject\"", ")", ")", ":", "parent", "=", "gtype", ".", "parent", ".", "pytype", "if", "parent", "is", "None", "or", "parent", "...
31.842105
0.001605
def config(self): """uses "global config" for cfg""" if self._config: return self._config else: self._config = p_config.ProsperConfig(self.config_path) return self._config
[ "def", "config", "(", "self", ")", ":", "if", "self", ".", "_config", ":", "return", "self", ".", "_config", "else", ":", "self", ".", "_config", "=", "p_config", ".", "ProsperConfig", "(", "self", ".", "config_path", ")", "return", "self", ".", "_conf...
32.142857
0.008658
def p_rvalue(self, p): 'rvalue : expression' p[0] = Rvalue(p[1], lineno=p.lineno(1)) p.set_lineno(0, p.lineno(1))
[ "def", "p_rvalue", "(", "self", ",", "p", ")", ":", "p", "[", "0", "]", "=", "Rvalue", "(", "p", "[", "1", "]", ",", "lineno", "=", "p", ".", "lineno", "(", "1", ")", ")", "p", ".", "set_lineno", "(", "0", ",", "p", ".", "lineno", "(", "1...
33.5
0.014599
def getEstTraitCovar(self,term_i=None): """ Returns explicitly the estimated trait covariance matrix Args: term_i: index of the term we are interested in """ assert self.P>1, 'Trait covars not defined for single trait analysis' if term_i==None: ...
[ "def", "getEstTraitCovar", "(", "self", ",", "term_i", "=", "None", ")", ":", "assert", "self", ".", "P", ">", "1", ",", "'Trait covars not defined for single trait analysis'", "if", "term_i", "==", "None", ":", "RV", "=", "SP", ".", "zeros", "(", "(", "se...
37.1875
0.021311
def _normalize_slice(self, index, pipe=None): """Given a :obj:`slice` *index*, return a 4-tuple ``(start, stop, step, fowrward)``. The first three items can be used with the ``range`` function to retrieve the values associated with the slice; the last item indicates the direction. ...
[ "def", "_normalize_slice", "(", "self", ",", "index", ",", "pipe", "=", "None", ")", ":", "if", "index", ".", "step", "==", "0", ":", "raise", "ValueError", "pipe", "=", "self", ".", "redis", "if", "pipe", "is", "None", "else", "pipe", "len_self", "=...
32.941176
0.001735
def remove_terms(self,list_term_ids): """ Removes a list of terms from the layer @type list_term_ids: list @param list_term_ids: list of term identifiers to be removed """ nodes_to_remove = set() for term in self: if term.get_id() in list_term_ids: ...
[ "def", "remove_terms", "(", "self", ",", "list_term_ids", ")", ":", "nodes_to_remove", "=", "set", "(", ")", "for", "term", "in", "self", ":", "if", "term", ".", "get_id", "(", ")", "in", "list_term_ids", ":", "nodes_to_remove", ".", "add", "(", "term", ...
36.470588
0.009434
def cut_from_block(html_message): """Cuts div tag which wraps block starting with "From:".""" # handle the case when From: block is enclosed in some tag block = html_message.xpath( ("//*[starts-with(mg:text_content(), 'From:')]|" "//*[starts-with(mg:text_content(), 'Date:')]")) if bloc...
[ "def", "cut_from_block", "(", "html_message", ")", ":", "# handle the case when From: block is enclosed in some tag", "block", "=", "html_message", ".", "xpath", "(", "(", "\"//*[starts-with(mg:text_content(), 'From:')]|\"", "\"//*[starts-with(mg:text_content(), 'Date:')]\"", ")", ...
36.206897
0.000927
def line(self, x0, y0, x1, y1): """Draw a line using Xiaolin Wu's antialiasing technique""" # clean params x0, y0, x1, y1 = int(x0), int(y0), int(x1), int(y1) if y0 > y1: y0, y1, x0, x1 = y1, y0, x1, x0 dx = x1 - x0 if dx < 0: sx = -1 else:...
[ "def", "line", "(", "self", ",", "x0", ",", "y0", ",", "x1", ",", "y1", ")", ":", "# clean params", "x0", ",", "y0", ",", "x1", ",", "y1", "=", "int", "(", "x0", ")", ",", "int", "(", "y0", ")", ",", "int", "(", "x1", ")", ",", "int", "("...
30.403509
0.001118
def get_plugin_command(plugin_name, command_name, conn=None): """ get_specific_command function queries a specific CommandName :param plugin_name: <str> PluginName :param command_name: <str> CommandName :return: <dict> """ commands = RPX.table(plugin_name).filter( {COMMAND_NAME_KEY:...
[ "def", "get_plugin_command", "(", "plugin_name", ",", "command_name", ",", "conn", "=", "None", ")", ":", "commands", "=", "RPX", ".", "table", "(", "plugin_name", ")", ".", "filter", "(", "{", "COMMAND_NAME_KEY", ":", "command_name", "}", ")", ".", "run",...
31.5
0.002203
def NewFromYuv(y, u, v, alpha=1.0, wref=_DEFAULT_WREF): '''Create a new instance based on the specifed YUV values. Parameters: :y: The Y component value [0...1] :u: The U component value [-0.436...0.436] :v: The V component value [-0.615...0.615] :alpha: ...
[ "def", "NewFromYuv", "(", "y", ",", "u", ",", "v", ",", "alpha", "=", "1.0", ",", "wref", "=", "_DEFAULT_WREF", ")", ":", "return", "Color", "(", "Color", ".", "YuvToRgb", "(", "y", ",", "u", ",", "v", ")", ",", "'rgb'", ",", "alpha", ",", "wre...
29.4
0.001318
def convert_transpose(node, **kwargs): """Map MXNet's transpose operator attributes to onnx's Transpose operator and return the created node. """ name, input_nodes, attrs = get_inputs(node, kwargs) axes = attrs.get("axes", ()) if axes: axes = tuple(map(int, re.findall(r'\d+', axes))) ...
[ "def", "convert_transpose", "(", "node", ",", "*", "*", "kwargs", ")", ":", "name", ",", "input_nodes", ",", "attrs", "=", "get_inputs", "(", "node", ",", "kwargs", ")", "axes", "=", "attrs", ".", "get", "(", "\"axes\"", ",", "(", ")", ")", "if", "...
25.192308
0.001471
def html_job_status(job_name, job_type, refresh_interval, html_on_running, html_on_success): """create html representation of status of a job (long running operation). Args: job_name: the full name of the job. job_type: type of job. Can be 'local' or 'cloud'. refresh_interval: how often should the clie...
[ "def", "html_job_status", "(", "job_name", ",", "job_type", ",", "refresh_interval", ",", "html_on_running", ",", "html_on_success", ")", ":", "_HTML_TEMPLATE", "=", "\"\"\"\n <div class=\"jobstatus\" id=\"%s\">\n </div>\n <script>\n require(['datalab/job', 'datalab/ele...
43.875
0.009294
def neutralize_variable(self, variable_name): """ Neutralizes an OpenFisca variable existing in the tax and benefit system. A neutralized variable always returns its default value when computed. Trying to set inputs for a neutralized variable has no effect except raising a warning. ...
[ "def", "neutralize_variable", "(", "self", ",", "variable_name", ")", ":", "self", ".", "variables", "[", "variable_name", "]", "=", "get_neutralized_variable", "(", "self", ".", "get_variable", "(", "variable_name", ")", ")" ]
46.555556
0.01171
def validate_full_path(cls, full_path, **kwargs): """Helper method to return a full path from a full or partial path. If no domain, assumes user's account domain If the vault is "~", assumes personal vault. Valid vault paths include: domain:vault domain...
[ "def", "validate_full_path", "(", "cls", ",", "full_path", ",", "*", "*", "kwargs", ")", ":", "_client", "=", "kwargs", ".", "pop", "(", "'client'", ",", "None", ")", "or", "cls", ".", "_client", "or", "client", "full_path", "=", "full_path", ".", "str...
32.864407
0.001002
def get_prefix(multicodec): """ Returns prefix for a given multicodec :param str multicodec: multicodec codec name :return: the prefix for the given multicodec :rtype: byte :raises ValueError: if an invalid multicodec name is provided """ try: prefix = varint.encode(NAME_TABLE[m...
[ "def", "get_prefix", "(", "multicodec", ")", ":", "try", ":", "prefix", "=", "varint", ".", "encode", "(", "NAME_TABLE", "[", "multicodec", "]", ")", "except", "KeyError", ":", "raise", "ValueError", "(", "'{} multicodec is not supported.'", ".", "format", "("...
31.142857
0.002227
def extract_keywords(self, sentence, span_info=False): """Searches in the string for all keywords present in corpus. Keywords present are added to a list `keywords_extracted` and returned. Args: sentence (str): Line of text where we will search for keywords Returns: ...
[ "def", "extract_keywords", "(", "self", ",", "sentence", ",", "span_info", "=", "False", ")", ":", "keywords_extracted", "=", "[", "]", "if", "not", "sentence", ":", "# if sentence is empty or none just return empty list", "return", "keywords_extracted", "if", "not", ...
46.348624
0.001938
def load_cwl(fname): """Load and validate CWL file using cwltool """ logger.debug('Loading CWL file "{}"'.format(fname)) # Fetching, preprocessing and validating cwl # Older versions of cwltool if legacy_cwltool: try: (document_loader, workflowobj, uri) = fetch_document(fnam...
[ "def", "load_cwl", "(", "fname", ")", ":", "logger", ".", "debug", "(", "'Loading CWL file \"{}\"'", ".", "format", "(", "fname", ")", ")", "# Fetching, preprocessing and validating cwl", "# Older versions of cwltool", "if", "legacy_cwltool", ":", "try", ":", "(", "...
45.596154
0.000413
def _base_get_list(self, url, limit=None, *, query=None, order_by=None, batch=None): """ Returns a collection of drive items """ if limit is None or limit > self.protocol.max_top_value: batch = self.protocol.max_top_value params = {'$top': batch if batch else...
[ "def", "_base_get_list", "(", "self", ",", "url", ",", "limit", "=", "None", ",", "*", ",", "query", "=", "None", ",", "order_by", "=", "None", ",", "batch", "=", "None", ")", ":", "if", "limit", "is", "None", "or", "limit", ">", "self", ".", "pr...
34.875
0.002092
def get_url(self, version=None): """ Return the filename of the bundled bundle """ if self.fixed_bundle_url: return self.fixed_bundle_url return '%s.%s.%s' % (os.path.join(self.bundle_url_root, self.bundle_filename), version or self.get_version(), self.bundle_type)
[ "def", "get_url", "(", "self", ",", "version", "=", "None", ")", ":", "if", "self", ".", "fixed_bundle_url", ":", "return", "self", ".", "fixed_bundle_url", "return", "'%s.%s.%s'", "%", "(", "os", ".", "path", ".", "join", "(", "self", ".", "bundle_url_r...
44.428571
0.009464
def show_clusters(clusters, sample, covariances, means, figure = None, display = True): """! @brief Draws clusters and in case of two-dimensional dataset draws their ellipses. @param[in] clusters (list): Clusters that were allocated by the algorithm. @param[in] sample (list...
[ "def", "show_clusters", "(", "clusters", ",", "sample", ",", "covariances", ",", "means", ",", "figure", "=", "None", ",", "display", "=", "True", ")", ":", "visualizer", "=", "cluster_visualizer", "(", ")", "visualizer", ".", "append_clusters", "(", "cluste...
43.21875
0.016973
def map_to_precursors(seqs, names, loci, out_file, args): """map sequences to precursors with razers3""" with make_temp_directory() as temp: pre_fasta = os.path.join(temp, "pre.fa") seqs_fasta = os.path.join(temp, "seqs.fa") out_sam = os.path.join(temp, "out.sam") pre_fasta = get...
[ "def", "map_to_precursors", "(", "seqs", ",", "names", ",", "loci", ",", "out_file", ",", "args", ")", ":", "with", "make_temp_directory", "(", ")", "as", "temp", ":", "pre_fasta", "=", "os", ".", "path", ".", "join", "(", "temp", ",", "\"pre.fa\"", ")...
48.529412
0.002378
def use_isolated_vault_view(self): """Pass through to provider AuthorizationLookupSession.use_isolated_vault_view""" self._vault_view = ISOLATED # self._get_provider_session('authorization_lookup_session') # To make sure the session is tracked for session in self._get_provider_sessions()...
[ "def", "use_isolated_vault_view", "(", "self", ")", ":", "self", ".", "_vault_view", "=", "ISOLATED", "# self._get_provider_session('authorization_lookup_session') # To make sure the session is tracked", "for", "session", "in", "self", ".", "_get_provider_sessions", "(", ")", ...
48.444444
0.009009
def dispatch_url(self, url_string): """Dispatch the URL string to the target endpoint function. :param url_string: the origin URL string. :returns: the return value of calling dispatched function. """ url, url_adapter, query_args = self.parse_url(url_string) try: ...
[ "def", "dispatch_url", "(", "self", ",", "url_string", ")", ":", "url", ",", "url_adapter", ",", "query_args", "=", "self", ".", "parse_url", "(", "url_string", ")", "try", ":", "endpoint", ",", "kwargs", "=", "url_adapter", ".", "match", "(", ")", "exce...
37.045455
0.002392
def _longoptl(self): """Get a list of string representations of the options in long format.""" res = [] for o in self.options: nm = o.long if o.argName is not None: nm += "=" res.append(nm) return res
[ "def", "_longoptl", "(", "self", ")", ":", "res", "=", "[", "]", "for", "o", "in", "self", ".", "options", ":", "nm", "=", "o", ".", "long", "if", "o", ".", "argName", "is", "not", "None", ":", "nm", "+=", "\"=\"", "res", ".", "append", "(", ...
26
0.016529
def _make_matchers(self, crontab): ''' This constructs the full matcher struct. ''' crontab = _aliases.get(crontab, crontab) ct = crontab.split() if len(ct) == 5: ct.insert(0, '0') ct.append('*') elif len(ct) == 6: ct.insert(0, ...
[ "def", "_make_matchers", "(", "self", ",", "crontab", ")", ":", "crontab", "=", "_aliases", ".", "get", "(", "crontab", ",", "crontab", ")", "ct", "=", "crontab", ".", "split", "(", ")", "if", "len", "(", "ct", ")", "==", "5", ":", "ct", ".", "in...
31.764706
0.008993
def help(file=None): """ Print out syntax help for running astrodrizzle Parameters ---------- file : str (Default = None) If given, write out help to the filename specified by this parameter Any previously existing file with this name will be deleted before writing out the h...
[ "def", "help", "(", "file", "=", "None", ")", ":", "helpstr", "=", "getHelpAsString", "(", "docstring", "=", "True", ",", "show_ver", "=", "True", ")", "if", "file", "is", "None", ":", "print", "(", "helpstr", ")", "else", ":", "if", "os", ".", "pa...
27.9
0.010399
def node_name(self, value): """The node_name property. Args: value (string). the property value. """ if value == self._defaults['ai.internal.nodeName'] and 'ai.internal.nodeName' in self._values: del self._values['ai.internal.nodeName'] else: ...
[ "def", "node_name", "(", "self", ",", "value", ")", ":", "if", "value", "==", "self", ".", "_defaults", "[", "'ai.internal.nodeName'", "]", "and", "'ai.internal.nodeName'", "in", "self", ".", "_values", ":", "del", "self", ".", "_values", "[", "'ai.internal....
36.3
0.010753
def int_id(self): "int: This key's numeric id." id_or_name = self.id_or_name if id_or_name is not None and isinstance(id_or_name, int): return id_or_name return None
[ "def", "int_id", "(", "self", ")", ":", "id_or_name", "=", "self", ".", "id_or_name", "if", "id_or_name", "is", "not", "None", "and", "isinstance", "(", "id_or_name", ",", "int", ")", ":", "return", "id_or_name", "return", "None" ]
34
0.009569
def copy(self, graph): """ Returns a copy of the styleguide for the given graph. """ g = styleguide(graph) g.order = self.order dict.__init__(g, [(k, v) for k, v in self.iteritems()]) return g
[ "def", "copy", "(", "self", ",", "graph", ")", ":", "g", "=", "styleguide", "(", "graph", ")", "g", ".", "order", "=", "self", ".", "order", "dict", ".", "__init__", "(", "g", ",", "[", "(", "k", ",", "v", ")", "for", "k", ",", "v", "in", "...
33.428571
0.008333
def get_path(self): '''获取选择的路径, 如果没有选择, 就返回根目录''' model, tree_iter = self.selection.get_selected() if not tree_iter: return '/' else: return model[tree_iter][PATH_COL]
[ "def", "get_path", "(", "self", ")", ":", "model", ",", "tree_iter", "=", "self", ".", "selection", ".", "get_selected", "(", ")", "if", "not", "tree_iter", ":", "return", "'/'", "else", ":", "return", "model", "[", "tree_iter", "]", "[", "PATH_COL", "...
31
0.008969
def _GetUniqueFileShowNames(self, tvFileList): """ Return a list containing all unique show names from tvfile.TVFile object list. Parameters ---------- tvFileList : list List of tvfile.TVFile objects. Returns ---------- set The set of show names from the tvfile....
[ "def", "_GetUniqueFileShowNames", "(", "self", ",", "tvFileList", ")", ":", "showNameList", "=", "[", "tvFile", ".", "fileInfo", ".", "showName", "for", "tvFile", "in", "tvFileList", "]", "return", "(", "set", "(", "showNameList", ")", ")" ]
25
0.002268
def unpack_ihex(record): """Unpack given Intel HEX record into variables. """ # Minimum :SSAAAATTCC, where SS is size, AAAA is address, TT is # type and CC is crc. if len(record) < 11: raise Error("record '{}' too short".format(record)) if record[0] != ':': raise Error("record...
[ "def", "unpack_ihex", "(", "record", ")", ":", "# Minimum :SSAAAATTCC, where SS is size, AAAA is address, TT is", "# type and CC is crc.", "if", "len", "(", "record", ")", "<", "11", ":", "raise", "Error", "(", "\"record '{}' too short\"", ".", "format", "(", "record", ...
27.181818
0.001076
def barmatch2(data, tups, cutters, longbar, matchdict, fnum): """ cleaner barmatch func... """ ## how many reads to store before writing to disk waitchunk = int(1e6) ## pid name for this engine epid = os.getpid() ## counters for total reads, those with cutsite, and those that matched ...
[ "def", "barmatch2", "(", "data", ",", "tups", ",", "cutters", ",", "longbar", ",", "matchdict", ",", "fnum", ")", ":", "## how many reads to store before writing to disk", "waitchunk", "=", "int", "(", "1e6", ")", "## pid name for this engine", "epid", "=", "os", ...
34.257485
0.010022
def check_for_completion(self): """ Check once for completion of the job and return completion status and result if it has completed. If the job completed in error, an :exc:`~zhmcclient.HTTPError` exception is raised. Returns: : A tuple (status, result) with:...
[ "def", "check_for_completion", "(", "self", ")", ":", "job_result_obj", "=", "self", ".", "session", ".", "get", "(", "self", ".", "uri", ")", "job_status", "=", "job_result_obj", "[", "'status'", "]", "if", "job_status", "==", "'complete'", ":", "self", "...
40.895522
0.000713
def set_room_topic(self, room_id, topic, timestamp=None): """Perform PUT /rooms/$room_id/state/m.room.topic Args: room_id (str): The room ID topic (str): The new room topic timestamp (int): Set origin_server_ts (For application services only) """ body ...
[ "def", "set_room_topic", "(", "self", ",", "room_id", ",", "topic", ",", "timestamp", "=", "None", ")", ":", "body", "=", "{", "\"topic\"", ":", "topic", "}", "return", "self", ".", "send_state_event", "(", "room_id", ",", "\"m.room.topic\"", ",", "body", ...
39.909091
0.008909
def import_module(self, module=None, recursive=False, **params): """Create a child space from an module. Args: module: a module object or name of the module object. recursive: Not yet implemented. **params: arguments to pass to ``new_space`` Returns: ...
[ "def", "import_module", "(", "self", ",", "module", "=", "None", ",", "recursive", "=", "False", ",", "*", "*", "params", ")", ":", "if", "module", "is", "None", ":", "if", "\"module_\"", "in", "params", ":", "warnings", ".", "warn", "(", "\"Parameter ...
33.607143
0.002066
def to(self, fmt=None, filename=None): """ Outputs the molecule to a file or string. Args: fmt (str): Format to output to. Defaults to JSON unless filename is provided. If fmt is specifies, it overrides whatever the filename is. Options include "xyz",...
[ "def", "to", "(", "self", ",", "fmt", "=", "None", ",", "filename", "=", "None", ")", ":", "from", "pymatgen", ".", "io", ".", "xyz", "import", "XYZ", "from", "pymatgen", ".", "io", ".", "gaussian", "import", "GaussianInput", "from", "pymatgen", ".", ...
41.571429
0.000839
def getWeight(grph, nd1, nd2, weightString = "weight", returnType = int): """ A way of getting the weight of an edge with or without weight as a parameter returns a the value of the weight parameter converted to returnType if it is given or 1 (also converted) if not """ if not weightString: ...
[ "def", "getWeight", "(", "grph", ",", "nd1", ",", "nd2", ",", "weightString", "=", "\"weight\"", ",", "returnType", "=", "int", ")", ":", "if", "not", "weightString", ":", "return", "returnType", "(", "1", ")", "else", ":", "return", "returnType", "(", ...
44.888889
0.01699
def set_widgets(self): """Set widgets on the Summary tab.""" if self.parent.aggregation_layer: aggr = self.parent.aggregation_layer.name() else: aggr = self.tr('no aggregation') html = self.tr('Please ensure the following information ' 'is ...
[ "def", "set_widgets", "(", "self", ")", ":", "if", "self", ".", "parent", ".", "aggregation_layer", ":", "aggr", "=", "self", ".", "parent", ".", "aggregation_layer", ".", "name", "(", ")", "else", ":", "aggr", "=", "self", ".", "tr", "(", "'no aggrega...
41.193548
0.00153
def display(self): """ Displays an overview containing descriptive stats for the Series provided. """ print('Stats for %s from %s - %s' % (self.name, self.start, self.end)) if type(self.rf) is float: print('Annual risk-free rate considered: %s' % (fmtp(self.rf...
[ "def", "display", "(", "self", ")", ":", "print", "(", "'Stats for %s from %s - %s'", "%", "(", "self", ".", "name", ",", "self", ".", "start", ",", "self", ".", "end", ")", ")", "if", "type", "(", "self", ".", "rf", ")", "is", "float", ":", "print...
44.943396
0.000822
def _var_res_to_weights(self, var_res): """ Get model weights """ # transform the weights into our form motif_base_weights_raw = var_res["motif_base_weights"][0] motif_base_weights = np.swapaxes(motif_base_weights_raw, 0, 2) # get weights motif_weights = ...
[ "def", "_var_res_to_weights", "(", "self", ",", "var_res", ")", ":", "# transform the weights into our form", "motif_base_weights_raw", "=", "var_res", "[", "\"motif_base_weights\"", "]", "[", "0", "]", "motif_base_weights", "=", "np", ".", "swapaxes", "(", "motif_bas...
36.027027
0.002191
def scenario(weight=1, delay=0.0, name=None): """Decorator to register a function as a Molotov test. Options: - **weight** used by Molotov when the scenarii are randomly picked. The functions with the highest values are more likely to be picked. Integer, defaults to 1. This value is ignored wh...
[ "def", "scenario", "(", "weight", "=", "1", ",", "delay", "=", "0.0", ",", "name", "=", "None", ")", ":", "def", "_scenario", "(", "func", ",", "*", "args", ",", "*", "*", "kw", ")", ":", "_check_coroutine", "(", "func", ")", "if", "weight", ">",...
36.575758
0.000807
def listen_tta(self, target, timeout): """Listen as Type A Target. Waits to receive a SENS_REQ command at the bitrate set by **target.brty** and sends the **target.sens_res** response. Depending on the SENS_RES bytes, the Initiator then sends an RID_CMD (SENS_RES coded for a Typ...
[ "def", "listen_tta", "(", "self", ",", "target", ",", "timeout", ")", ":", "fname", "=", "\"listen_tta\"", "cname", "=", "self", ".", "__class__", ".", "__module__", "+", "'.'", "+", "self", ".", "__class__", ".", "__name__", "raise", "NotImplementedError", ...
39.695652
0.001069
def make_varname(tree): """ <left> tree </left> """ if tree.tag == 'identifier': return tree.attrib['name'] if tree.tag in ('string', 'boolean'): return tree.text if tree.tag == 'number': return tree.attrib['value'] if tree.tag in ('property', 'object'): re...
[ "def", "make_varname", "(", "tree", ")", ":", "if", "tree", ".", "tag", "==", "'identifier'", ":", "return", "tree", ".", "attrib", "[", "'name'", "]", "if", "tree", ".", "tag", "in", "(", "'string'", ",", "'boolean'", ")", ":", "return", "tree", "."...
27.62069
0.001206
def check_target_integrity(key, values, meta=False, all=False, parent=None): """ Checks the integrity of a specific target. Gets called multiple times from check_integrity() Args: The target name The dictionary values of that target A boolean representing whether it is a meta-ta...
[ "def", "check_target_integrity", "(", "key", ",", "values", ",", "meta", "=", "False", ",", "all", "=", "False", ",", "parent", "=", "None", ")", ":", "# logic to audit \"all\" target", "if", "all", ":", "if", "not", "values", ":", "print", "(", "\"Warning...
35.359375
0.00129
def _adjust_rate_aggressive(self, real_wave_mfcc, algo_parameters): """ RATEAGGRESSIVE """ self.log(u"Called _adjust_rate_aggressive") self._apply_rate(max_rate=algo_parameters[0], aggressive=True)
[ "def", "_adjust_rate_aggressive", "(", "self", ",", "real_wave_mfcc", ",", "algo_parameters", ")", ":", "self", ".", "log", "(", "u\"Called _adjust_rate_aggressive\"", ")", "self", ".", "_apply_rate", "(", "max_rate", "=", "algo_parameters", "[", "0", "]", ",", ...
38.666667
0.008439
def __parseResponse(self, result): """Parses the server response.""" response = [] for data in result['data'] : result_dict={} for k,v in data.items() : column = self.getOutputColumn(k) if column != None: type = column.g...
[ "def", "__parseResponse", "(", "self", ",", "result", ")", ":", "response", "=", "[", "]", "for", "data", "in", "result", "[", "'data'", "]", ":", "result_dict", "=", "{", "}", "for", "k", ",", "v", "in", "data", ".", "items", "(", ")", ":", "col...
42.7
0.016794
def fetch_offsets(zk, consumer_group, topics): """Fetch offsets for given topics of given consumer group. :param zk: Zookeeper client :param consumer_group: Consumer group id for given offsets :type consumer_group: int :rtype: dict(topic, dict(partition, offset)) """ source_offsets = defaul...
[ "def", "fetch_offsets", "(", "zk", ",", "consumer_group", ",", "topics", ")", ":", "source_offsets", "=", "defaultdict", "(", "dict", ")", "for", "topic", ",", "partitions", "in", "six", ".", "iteritems", "(", "topics", ")", ":", "for", "partition", "in", ...
36.9
0.001321
def bootstrap_executive_office_states(self, election): """ Create state page content exclusively for the U.S. president. """ content_type = ContentType.objects.get_for_model(election.race.office) for division in Division.objects.filter(level=self.STATE_LEVEL): PageCon...
[ "def", "bootstrap_executive_office_states", "(", "self", ",", "election", ")", ":", "content_type", "=", "ContentType", ".", "objects", ".", "get_for_model", "(", "election", ".", "race", ".", "office", ")", "for", "division", "in", "Division", ".", "objects", ...
40.977273
0.001083
def list_associated_storage_groups( self, full_properties=False, filter_args=None): """ Return the :term:`storage groups <storage group>` that are associated to this CPC. If the CPC does not support the "dpm-storage-management" feature, or does not have it enabled, a...
[ "def", "list_associated_storage_groups", "(", "self", ",", "full_properties", "=", "False", ",", "filter_args", "=", "None", ")", ":", "if", "filter_args", "is", "None", ":", "filter_args", "=", "{", "}", "else", ":", "filter_args", "=", "filter_args", ".", ...
33.571429
0.000919
def get_kinds(start=None, end=None): """Return all kinds in the specified range, for the current namespace. Args: start: only return kinds >= start if start is not None. end: only return kinds < end if end is not None. Returns: A list of kind names between the (optional) start and end values. """ ...
[ "def", "get_kinds", "(", "start", "=", "None", ",", "end", "=", "None", ")", ":", "q", "=", "Kind", ".", "query", "(", ")", "if", "start", "is", "not", "None", "and", "start", "!=", "''", ":", "q", "=", "q", ".", "filter", "(", "Kind", ".", "...
29.368421
0.012153
def foldx_dir(self): """str: FoldX folder""" if self.root_dir: return op.join(self.root_dir, self._foldx_dirname) else: log.warning('Root directory not set') return None
[ "def", "foldx_dir", "(", "self", ")", ":", "if", "self", ".", "root_dir", ":", "return", "op", ".", "join", "(", "self", ".", "root_dir", ",", "self", ".", "_foldx_dirname", ")", "else", ":", "log", ".", "warning", "(", "'Root directory not set'", ")", ...
31.857143
0.008734
def get_highest_version(versions): """ Returns highest available version for a package in a list of versions Uses pkg_resources to parse the versions @param versions: List of PyPI package versions @type versions: List of strings @returns: string of a PyPI package version """ sorted_v...
[ "def", "get_highest_version", "(", "versions", ")", ":", "sorted_versions", "=", "[", "]", "for", "ver", "in", "versions", ":", "sorted_versions", ".", "append", "(", "(", "pkg_resources", ".", "parse_version", "(", "ver", ")", ",", "ver", ")", ")", "sorte...
27.421053
0.001855
def store_config(config, suffix = None): ''' Store configuration args: config (list[dict]): configurations for each project ''' home = os.path.expanduser('~') if suffix is not None: config_path = os.path.join(home, '.transfer', suffix) else: config_path = os.path.joi...
[ "def", "store_config", "(", "config", ",", "suffix", "=", "None", ")", ":", "home", "=", "os", ".", "path", ".", "expanduser", "(", "'~'", ")", "if", "suffix", "is", "not", "None", ":", "config_path", "=", "os", ".", "path", ".", "join", "(", "home...
29.375
0.010309
def radial_symmetry(mesh): """ Check whether a mesh has rotational symmetry. Returns ----------- symmetry : None or str None No rotational symmetry 'radial' Symmetric around an axis 'spherical' Symmetric around a point axis : None or (3,) float Rota...
[ "def", "radial_symmetry", "(", "mesh", ")", ":", "# if not a volume this is meaningless", "if", "not", "mesh", ".", "is_volume", ":", "return", "None", ",", "None", ",", "None", "# the sorted order of the principal components of inertia (3,) float", "order", "=", "mesh", ...
39.169014
0.000351
def view_build(): """Page for viewing all releases in a build.""" build = g.build page_size = min(request.args.get('page_size', 10, type=int), 50) offset = request.args.get('offset', 0, type=int) ops = operations.BuildOps(build.id) has_next_page, candidate_list, stats_counts = ops.get_candidate...
[ "def", "view_build", "(", ")", ":", "build", "=", "g", ".", "build", "page_size", "=", "min", "(", "request", ".", "args", ".", "get", "(", "'page_size'", ",", "10", ",", "type", "=", "int", ")", ",", "50", ")", "offset", "=", "request", ".", "ar...
36.888889
0.000489
def dashboard_view(request, show_widgets=True, show_expired=False, ignore_dashboard_types=None, show_welcome=False): """Process and show the dashboard, which includes activities, events, and widgets.""" user = request.user announcements_admin = user.has_admin_permission("announcements") events_admin =...
[ "def", "dashboard_view", "(", "request", ",", "show_widgets", "=", "True", ",", "show_expired", "=", "False", ",", "ignore_dashboard_types", "=", "None", ",", "show_welcome", "=", "False", ")", ":", "user", "=", "request", ".", "user", "announcements_admin", "...
36.270492
0.00198
def readComponents(streamOrString, validate=False, transform=True, ignoreUnreadable=False, allowQP=False): """ Generate one Component at a time from a stream. """ if isinstance(streamOrString, basestring): stream = six.StringIO(streamOrString) else: stream = stream...
[ "def", "readComponents", "(", "streamOrString", ",", "validate", "=", "False", ",", "transform", "=", "True", ",", "ignoreUnreadable", "=", "False", ",", "allowQP", "=", "False", ")", ":", "if", "isinstance", "(", "streamOrString", ",", "basestring", ")", ":...
41.90411
0.000958
def math(data, operator=None, operator_name=None, axis=None): """Apply mathematical operation to each trial and channel individually. Parameters ---------- data : instance of DataTime, DataFreq, or DataTimeFreq operator : function or tuple of functions, optional function(s) to run on the d...
[ "def", "math", "(", "data", ",", "operator", "=", "None", ",", "operator_name", "=", "None", ",", "axis", "=", "None", ")", ":", "if", "operator", "is", "not", "None", "and", "operator_name", "is", "not", "None", ":", "raise", "TypeError", "(", "'Param...
32.512195
0.000728
def setup_dryx_logging(yaml_file): """ *setup dryx style python logging* **Key Arguments:** - ``level`` -- the level of logging required **Return:** - ``logger`` -- the console logger **Usage:** .. code-block:: python from fundamentals import logs ...
[ "def", "setup_dryx_logging", "(", "yaml_file", ")", ":", "import", "logging", "import", "logging", ".", "config", "import", "yaml", "# IMPORT CUSTOM HANDLER THAT ALLOWS GROUP WRITING", "handlers", ".", "GroupWriteRotatingFileHandler", "=", "GroupWriteRotatingFileHandler", "# ...
39.2
0.002488
def minimum_enclosing_circle(labels, indexes = None, hull_and_point_count = None): """Find the location of the minimum enclosing circle and its radius labels - a labels matrix indexes - an array giving the label indexes to be processed hull_and_point_count - convex_hul...
[ "def", "minimum_enclosing_circle", "(", "labels", ",", "indexes", "=", "None", ",", "hull_and_point_count", "=", "None", ")", ":", "if", "indexes", "is", "None", ":", "if", "hull_and_point_count", "is", "not", "None", ":", "indexes", "=", "np", ".", "array",...
43.98773
0.008728
def run(self, gin): """ Run GULP using the gin as input Args: gin: GULP input string Returns: gout: GULP output string """ with ScratchDir("."): p = subprocess.Popen( self._gulp_cmd, stdout=subprocess.PIPE, ...
[ "def", "run", "(", "self", ",", "gin", ")", ":", "with", "ScratchDir", "(", "\".\"", ")", ":", "p", "=", "subprocess", ".", "Popen", "(", "self", ".", "_gulp_cmd", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "stdin", "=", "subprocess", ".", ...
30.627907
0.002208
def cmd(self, fun, arg=None, pub_data=None, kwarg=None, print_event=True, full_return=False): ''' Execute a function .. code-block:: python >>> opts = salt.config.master_config('/etc/salt/master') >>> runner = salt.runner.RunnerClient(opts) >>> runner.cmd('j...
[ "def", "cmd", "(", "self", ",", "fun", ",", "arg", "=", "None", ",", "pub_data", "=", "None", ",", "kwarg", "=", "None", ",", "print_event", "=", "True", ",", "full_return", "=", "False", ")", ":", "if", "arg", "is", "None", ":", "arg", "=", "tup...
35.126984
0.001758
def _tls_mac_add(alg, c, write_seq_num): """ Compute the MAC using provided MAC alg instance over TLSCiphertext c using current write sequence number write_seq_num. Computed MAC is then appended to c.data and c.len is updated to reflect that change. It is the caller responsibility to increment the s...
[ "def", "_tls_mac_add", "(", "alg", ",", "c", ",", "write_seq_num", ")", ":", "write_seq_num", "=", "struct", ".", "pack", "(", "\"!Q\"", ",", "write_seq_num", ")", "h", "=", "alg", ".", "digest", "(", "write_seq_num", "+", "bytes", "(", "c", ")", ")", ...
44.166667
0.001848
def _get(self, timeout): """ Get a resource from the pool. If timeout is ``None`` waits indefinitely. :param timeout: Time in seconds to wait for a resource. :type timeout: int :return: A resource. :rtype: :class:`_ResourceTracker` :raises PoolEmptyError...
[ "def", "_get", "(", "self", ",", "timeout", ")", ":", "with", "self", ".", "_lock", ":", "if", "timeout", "is", "None", ":", "while", "self", ".", "empty", "(", ")", ":", "self", ".", "_not_empty", ".", "wait", "(", ")", "else", ":", "time_end", ...
33.533333
0.001932
def begin_connect(self, shape, cxn_pt_idx): """ **EXPERIMENTAL** - *The current implementation only works properly with rectangular shapes, such as pictures and rectangles. Use with other shape types may cause unexpected visual alignment of the connected end-point and could lead ...
[ "def", "begin_connect", "(", "self", ",", "shape", ",", "cxn_pt_idx", ")", ":", "self", ".", "_connect_begin_to", "(", "shape", ",", "cxn_pt_idx", ")", "self", ".", "_move_begin_to_cxn", "(", "shape", ",", "cxn_pt_idx", ")" ]
56.05
0.001754
def from_authorized_user_info(cls, info, scopes=None): """Creates a Credentials instance from parsed authorized user info. Args: info (Mapping[str, str]): The authorized user info in Google format. scopes (Sequence[str]): Optional list of scopes to include in the...
[ "def", "from_authorized_user_info", "(", "cls", ",", "info", ",", "scopes", "=", "None", ")", ":", "keys_needed", "=", "set", "(", "(", "'refresh_token'", ",", "'client_id'", ",", "'client_secret'", ")", ")", "missing", "=", "keys_needed", ".", "difference", ...
37.354839
0.001684
def _interpretPayload(functioncode, payload): r"""Generate a human readable description of a Modbus payload. Args: * functioncode (int): Function code * payload (str): The payload that should be interpreted. It should be a byte string. Returns: A descriptive string. For exampl...
[ "def", "_interpretPayload", "(", "functioncode", ",", "payload", ")", ":", "raise", "NotImplementedError", "(", ")", "output", "=", "''", "output", "+=", "'Modbus payload decoder\\n'", "output", "+=", "'Input payload (length {} characters): {!r} \\n'", ".", "format", "(...
30.821429
0.010112
def assert_angle_or_pixel(name, q): """ Check that ``q`` is either an angular or a pixel :class:`~astropy.units.Quantity`. """ if isinstance(q, u.Quantity): if q.unit.physical_type == 'angle' or q.unit == u.pixel: pass else: raise ValueError("{0} should have ...
[ "def", "assert_angle_or_pixel", "(", "name", ",", "q", ")", ":", "if", "isinstance", "(", "q", ",", "u", ".", "Quantity", ")", ":", "if", "q", ".", "unit", ".", "physical_type", "==", "'angle'", "or", "q", ".", "unit", "==", "u", ".", "pixel", ":",...
32.857143
0.002114
def cancelall(self): """ Cancel all orders of this bot """ if self.orders: return self.bitshares.cancel( [o["id"] for o in self.orders], account=self.account )
[ "def", "cancelall", "(", "self", ")", ":", "if", "self", ".", "orders", ":", "return", "self", ".", "bitshares", ".", "cancel", "(", "[", "o", "[", "\"id\"", "]", "for", "o", "in", "self", ".", "orders", "]", ",", "account", "=", "self", ".", "ac...
29
0.008368
def _add_tasks_to_taskpaper( self, pathToTaskpaperDoc, taskString ): """*add the tasks to a taskpaper document* **Key Arguments:** - ``pathToTaskpaperDoc`` -- the path to the taskpaper document to import the tasks into - ``taskString`` -- a string con...
[ "def", "_add_tasks_to_taskpaper", "(", "self", ",", "pathToTaskpaperDoc", ",", "taskString", ")", ":", "self", ".", "log", ".", "info", "(", "'starting the ``_add_tasks_to_taskpaper`` method'", ")", "exists", "=", "os", ".", "path", ".", "exists", "(", "pathToTask...
34.538462
0.002166
def allow(self, roles, methods, with_children=True): """This is a decorator function. You can allow roles to access the view func with it. An example:: @app.route('/website/setting', methods=['GET', 'POST']) @rbac.allow(['administrator', 'super_user'], ['GET', 'POST'])...
[ "def", "allow", "(", "self", ",", "roles", ",", "methods", ",", "with_children", "=", "True", ")", ":", "def", "decorator", "(", "view_func", ")", ":", "_methods", "=", "[", "m", ".", "upper", "(", ")", "for", "m", "in", "methods", "]", "for", "r",...
43.785714
0.002394
def get_document(project_id, knowledge_base_id, document_id): """Gets a Document. Args: project_id: The GCP project linked with the agent. knowledge_base_id: Id of the Knowledge base. document_id: Id of the Document.""" import dialogflow_v2beta1 as dialogflow client = dialogflow...
[ "def", "get_document", "(", "project_id", ",", "knowledge_base_id", ",", "document_id", ")", ":", "import", "dialogflow_v2beta1", "as", "dialogflow", "client", "=", "dialogflow", ".", "DocumentsClient", "(", ")", "document_path", "=", "client", ".", "document_path",...
43.142857
0.00108
def run(self, kpop, nreps, ipyclient=None, seed=12345, force=False, quiet=False, ): """ submits a job to run on the cluster and returns an asynchronous result object. K is the number of populations, randomseed if not set will be ...
[ "def", "run", "(", "self", ",", "kpop", ",", "nreps", ",", "ipyclient", "=", "None", ",", "seed", "=", "12345", ",", "force", "=", "False", ",", "quiet", "=", "False", ",", ")", ":", "## initiate starting seed", "np", ".", "random", ".", "seed", "(",...
32.698529
0.009385
def vpn_sites_configuration(self): """Instance depends on the API version: * 2018-04-01: :class:`VpnSitesConfigurationOperations<azure.mgmt.network.v2018_04_01.operations.VpnSitesConfigurationOperations>` """ api_version = self._get_api_version('vpn_sites_configuration') if a...
[ "def", "vpn_sites_configuration", "(", "self", ")", ":", "api_version", "=", "self", ".", "_get_api_version", "(", "'vpn_sites_configuration'", ")", "if", "api_version", "==", "'2018-04-01'", ":", "from", ".", "v2018_04_01", ".", "operations", "import", "VpnSitesCon...
62.545455
0.008596
def copy_mx_model_to(model_path, model_epoch, output_folder): """ Copy mxnet models to new path. :param model_path: Model path without -symbol.json and -%04d.params :param model_epoch: Epoch of the pretrained model :param output_folder: Output folder :return: New folder where the files are move...
[ "def", "copy_mx_model_to", "(", "model_path", ",", "model_epoch", ",", "output_folder", ")", ":", "target_path", "=", "os", ".", "path", ".", "join", "(", "output_folder", ",", "os", ".", "path", ".", "basename", "(", "model_path", ")", ")", "logger", ".",...
43.375
0.00141
def Miqueu(T, Tc, Vc, omega): r'''Calculates air-water surface tension using the methods of [1]_. .. math:: \sigma = k T_c \left( \frac{N_a}{V_c}\right)^{2/3} (4.35 + 4.14 \omega)t^{1.26}(1+0.19t^{0.5} - 0.487t) Parameters ---------- T : float Temperature of fluid [K] T...
[ "def", "Miqueu", "(", "T", ",", "Tc", ",", "Vc", ",", "omega", ")", ":", "Vc", "=", "Vc", "*", "1E6", "t", "=", "1.", "-", "T", "/", "Tc", "sigma", "=", "k", "*", "Tc", "*", "(", "N_A", "/", "Vc", ")", "**", "(", "2", "/", "3.", ")", ...
30.137255
0.00126
def run_estimate(unknown_gate, qnum, repetitions): """Construct the following phase estimator circuit and execute simulations. --------- ---H---------------------@------| |---M--- [m4]:lowest bit | | | ---H--------------...
[ "def", "run_estimate", "(", "unknown_gate", ",", "qnum", ",", "repetitions", ")", ":", "qubits", "=", "[", "None", "]", "*", "qnum", "for", "i", "in", "range", "(", "len", "(", "qubits", ")", ")", ":", "qubits", "[", "i", "]", "=", "cirq", ".", "...
40.909091
0.001447
def _rename_duplicate_tabs(self, current, name, path): """ Rename tabs whose title is the same as the name """ for i in range(self.count()): if self.widget(i)._tab_name == name and self.widget(i) != current: file_path = self.widget(i).file.path ...
[ "def", "_rename_duplicate_tabs", "(", "self", ",", "current", ",", "name", ",", "path", ")", ":", "for", "i", "in", "range", "(", "self", ".", "count", "(", ")", ")", ":", "if", "self", ".", "widget", "(", "i", ")", ".", "_tab_name", "==", "name", ...
42.2
0.002317
def cast(source, target): """Currently Literal to *Scalar implicit casts are allowed""" import ibis.expr.operations as ops # TODO: don't use ops here if not castable(source, target): raise com.IbisTypeError('Source is not castable to target type!') # currently it prevents column -> scalar imp...
[ "def", "cast", "(", "source", ",", "target", ")", ":", "import", "ibis", ".", "expr", ".", "operations", "as", "ops", "# TODO: don't use ops here", "if", "not", "castable", "(", "source", ",", "target", ")", ":", "raise", "com", ".", "IbisTypeError", "(", ...
37.6
0.00173
def get_bitcoin_virtual_transactions(blockchain_opts, first_block_height, last_block_height, tx_filter=None, spv_last_block=None, first_block_hash=None, **hints): """ Get the sequence of virtualchain transactions from the blockchain. Each transaction returned will be a `nulldata` transaction (i.e. the first...
[ "def", "get_bitcoin_virtual_transactions", "(", "blockchain_opts", ",", "first_block_height", ",", "last_block_height", ",", "tx_filter", "=", "None", ",", "spv_last_block", "=", "None", ",", "first_block_hash", "=", "None", ",", "*", "*", "hints", ")", ":", "head...
41.367925
0.009354
def decode_timeseries_row(self, tsrow, tsct, convert_timestamp=False): """ Decodes a TTB-encoded TsRow into a list :param tsrow: the TTB decoded TsRow to decode. :type tsrow: TTB dncoded row :param tsct: the TTB decoded column types (atoms). :type tsct: list :par...
[ "def", "decode_timeseries_row", "(", "self", ",", "tsrow", ",", "tsct", ",", "convert_timestamp", "=", "False", ")", ":", "row", "=", "[", "]", "for", "i", ",", "cell", "in", "enumerate", "(", "tsrow", ")", ":", "if", "cell", "is", "None", ":", "row"...
35.875
0.002262
def derivativeX(self,*args): ''' Returns the derivative of the function with respect to the X dimension. This is the first input whenever n_dims < 4 and the second input otherwise. ''' if self.n_dims >= 4: j = 1 else: j = 0 if self.i_dim ==...
[ "def", "derivativeX", "(", "self", ",", "*", "args", ")", ":", "if", "self", ".", "n_dims", ">=", "4", ":", "j", "=", "1", "else", ":", "j", "=", "0", "if", "self", ".", "i_dim", "==", "j", ":", "return", "np", ".", "ones_like", "(", "*", "ar...
31.538462
0.009479
def upload( state, host, hostname, filename, remote_filename=None, use_remote_sudo=False, ssh_keyscan=False, ssh_user=None, ): ''' Upload files to other servers using ``scp``. + hostname: hostname to upload to + filename: file to upload + remote_filename: where to upload the file to (de...
[ "def", "upload", "(", "state", ",", "host", ",", "hostname", ",", "filename", ",", "remote_filename", "=", "None", ",", "use_remote_sudo", "=", "False", ",", "ssh_keyscan", "=", "False", ",", "ssh_user", "=", "None", ",", ")", ":", "remote_filename", "=", ...
32.511111
0.001327
def ResolveHostnameToIP(host, port): """Resolves a hostname to an IP address.""" ip_addrs = socket.getaddrinfo(host, port, socket.AF_UNSPEC, 0, socket.IPPROTO_TCP) # getaddrinfo returns tuples (family, socktype, proto, canonname, sockaddr). # We are interested in sockaddr which i...
[ "def", "ResolveHostnameToIP", "(", "host", ",", "port", ")", ":", "ip_addrs", "=", "socket", ".", "getaddrinfo", "(", "host", ",", "port", ",", "socket", ".", "AF_UNSPEC", ",", "0", ",", "socket", ".", "IPPROTO_TCP", ")", "# getaddrinfo returns tuples (family,...
49.666667
0.017128
def get_mime_representation(self): """returns mime part that constitutes this attachment""" part = deepcopy(self.part) part.set_param('maxlinelen', '78', header='Content-Disposition') return part
[ "def", "get_mime_representation", "(", "self", ")", ":", "part", "=", "deepcopy", "(", "self", ".", "part", ")", "part", ".", "set_param", "(", "'maxlinelen'", ",", "'78'", ",", "header", "=", "'Content-Disposition'", ")", "return", "part" ]
44.6
0.008811
def add_position_pattern(self, m): """This method draws the position adjustment patterns onto the QR Code. All QR code versions larger than one require these special boxes called position adjustment patterns. """ #Version 1 does not have a position adjustment pattern if s...
[ "def", "add_position_pattern", "(", "self", ",", "m", ")", ":", "#Version 1 does not have a position adjustment pattern", "if", "self", ".", "version", "==", "1", ":", "return", "#Get the coordinates for where to place the boxes", "coordinates", "=", "tables", ".", "posit...
37.177778
0.008736
def fit(self, X, y, sample_weight=None): """Fit the Genetic Program according to X, y. Parameters ---------- X : array-like, shape = [n_samples, n_features] Training vectors, where n_samples is the number of samples and n_features is the number of features. ...
[ "def", "fit", "(", "self", ",", "X", ",", "y", ",", "sample_weight", "=", "None", ")", ":", "random_state", "=", "check_random_state", "(", "self", ".", "random_state", ")", "# Check arrays", "if", "isinstance", "(", "self", ",", "ClassifierMixin", ")", ":...
45.452532
0.000204
def create_dataset(self, group, chunk_size): """Initializes sparse specific datasets""" group.attrs['format'] = self.dformat group.attrs['dim'] = self.dim if chunk_size == 'auto': group.create_dataset( 'coordinates', (0, 2), dtype=np.float64, ...
[ "def", "create_dataset", "(", "self", ",", "group", ",", "chunk_size", ")", ":", "group", ".", "attrs", "[", "'format'", "]", "=", "self", ".", "dformat", "group", ".", "attrs", "[", "'dim'", "]", "=", "self", ".", "dim", "if", "chunk_size", "==", "'...
36.071429
0.001285
def start(self): """ Start the configfile change monitoring thread. """ fname = self.conf['file'] logging.info("Configfile watcher plugin: Starting to watch route spec " "file '%s' for changes..." % fname) # Initial content of file needs to be proce...
[ "def", "start", "(", "self", ")", ":", "fname", "=", "self", ".", "conf", "[", "'file'", "]", "logging", ".", "info", "(", "\"Configfile watcher plugin: Starting to watch route spec \"", "\"file '%s' for changes...\"", "%", "fname", ")", "# Initial content of file needs...
43.594595
0.00849
def _parse_tree(self, node): """ Parse a <review> object """ if 'date' in node.attrib: dt = dateutil.parser.parse(node.attrib['date']) self.date = int(dt.strftime("%s")) if 'id' in node.attrib: self.id = node.attrib['id'] if 'karma' in node.attrib: ...
[ "def", "_parse_tree", "(", "self", ",", "node", ")", ":", "if", "'date'", "in", "node", ".", "attrib", ":", "dt", "=", "dateutil", ".", "parser", ".", "parse", "(", "node", ".", "attrib", "[", "'date'", "]", ")", "self", ".", "date", "=", "int", ...
40.129032
0.00157