text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def schedule_forced_host_check(self, host, check_time): """Schedule a forced check on a host Format of the line that triggers function call:: SCHEDULE_FORCED_HOST_CHECK;<host_name>;<check_time> :param host: host to check :type host: alignak.object.host.Host :param check...
[ "def", "schedule_forced_host_check", "(", "self", ",", "host", ",", "check_time", ")", ":", "host", ".", "schedule", "(", "self", ".", "daemon", ".", "hosts", ",", "self", ".", "daemon", ".", "services", ",", "self", ".", "daemon", ".", "timeperiods", ",...
42.176471
17.294118
def toggle_tbstyle(self, button): """Toogle the ToolButtonStyle of the given button between :data:`ToolButtonIconOnly` and :data:`ToolButtonTextBesideIcon` :param button: a tool button :type button: :class:`QtGui.QToolButton` :returns: None :rtype: None :raises: None ...
[ "def", "toggle_tbstyle", "(", "self", ",", "button", ")", ":", "old", "=", "button", ".", "toolButtonStyle", "(", ")", "if", "old", "==", "QtCore", ".", "Qt", ".", "ToolButtonIconOnly", ":", "new", "=", "QtCore", ".", "Qt", ".", "ToolButtonTextBesideIcon",...
36.933333
11.466667
def _get_prioritized_parameters(plugins_dict, is_using_default_value_map, prefer_default=True): """ :type plugins_dict: dict(plugin_name => plugin_params) :param plugin_dict: mapping of plugin name to all plugin params :type is_using_default_value_map: dict(str => bool) :param is_using_default_valu...
[ "def", "_get_prioritized_parameters", "(", "plugins_dict", ",", "is_using_default_value_map", ",", "prefer_default", "=", "True", ")", ":", "for", "plugin_name", ",", "plugin_params", "in", "plugins_dict", ".", "items", "(", ")", ":", "for", "param_name", ",", "pa...
52.647059
27.235294
def quit(self): """Run the "are you sure" dialog for quitting Guake """ # Stop an open "close tab" dialog from obstructing a quit response = self.run() == Gtk.ResponseType.YES self.destroy() # Keep Guake focussed after dismissing tab-close prompt # if tab == -1: ...
[ "def", "quit", "(", "self", ")", ":", "# Stop an open \"close tab\" dialog from obstructing a quit", "response", "=", "self", ".", "run", "(", ")", "==", "Gtk", ".", "ResponseType", ".", "YES", "self", ".", "destroy", "(", ")", "# Keep Guake focussed after dismissin...
36.9
14.3
def delete_external_feed_courses(self, course_id, external_feed_id): """ Delete an external feed. Deletes the external feed. """ path = {} data = {} params = {} # REQUIRED - PATH - course_id """ID""" path["course_id"] = course...
[ "def", "delete_external_feed_courses", "(", "self", ",", "course_id", ",", "external_feed_id", ")", ":", "path", "=", "{", "}", "data", "=", "{", "}", "params", "=", "{", "}", "# REQUIRED - PATH - course_id\r", "\"\"\"ID\"\"\"", "path", "[", "\"course_id\"", "]"...
39.3
28
def info(self, name, args): """Interfaces with the info dumpers (DBGFInfo). This feature is not implemented in the 4.0.0 release but it may show up in a dot release. in name of type str The name of the info item. in args of type str Arguments to...
[ "def", "info", "(", "self", ",", "name", ",", "args", ")", ":", "if", "not", "isinstance", "(", "name", ",", "basestring", ")", ":", "raise", "TypeError", "(", "\"name can only be an instance of type basestring\"", ")", "if", "not", "isinstance", "(", "args", ...
31.826087
18.347826
def remove_tags(self, tags): """ Add tags to a server. Accepts tags as strings or Tag objects. """ if self.cloud_manager.remove_tags(self, tags): new_tags = [tag for tag in self.tags if tag not in tags] object.__setattr__(self, 'tags', new_tags)
[ "def", "remove_tags", "(", "self", ",", "tags", ")", ":", "if", "self", ".", "cloud_manager", ".", "remove_tags", "(", "self", ",", "tags", ")", ":", "new_tags", "=", "[", "tag", "for", "tag", "in", "self", ".", "tags", "if", "tag", "not", "in", "t...
42.142857
13.857143
def p_partselect_plus(self, p): 'partselect : identifier LBRACKET expression PLUSCOLON expression RBRACKET' p[0] = Partselect(p[1], p[3], Plus( p[3], p[5], lineno=p.lineno(1)), lineno=p.lineno(1)) p.set_lineno(0, p.lineno(1))
[ "def", "p_partselect_plus", "(", "self", ",", "p", ")", ":", "p", "[", "0", "]", "=", "Partselect", "(", "p", "[", "1", "]", ",", "p", "[", "3", "]", ",", "Plus", "(", "p", "[", "3", "]", ",", "p", "[", "5", "]", ",", "lineno", "=", "p", ...
51.4
16.6
def purge(packages, fatal=False): """Purge one or more packages.""" cmd = ['yum', '--assumeyes', 'remove'] if isinstance(packages, six.string_types): cmd.append(packages) else: cmd.extend(packages) log("Purging {}".format(packages)) _run_yum_command(cmd, fatal)
[ "def", "purge", "(", "packages", ",", "fatal", "=", "False", ")", ":", "cmd", "=", "[", "'yum'", ",", "'--assumeyes'", ",", "'remove'", "]", "if", "isinstance", "(", "packages", ",", "six", ".", "string_types", ")", ":", "cmd", ".", "append", "(", "p...
32.555556
8.888889
def new_instance(settings): """ MAKE A PYTHON INSTANCE `settings` HAS ALL THE `kwargs`, PLUS `class` ATTRIBUTE TO INDICATE THE CLASS TO CREATE """ settings = set_default({}, settings) if not settings["class"]: Log.error("Expecting 'class' attribute with fully qualified class name") ...
[ "def", "new_instance", "(", "settings", ")", ":", "settings", "=", "set_default", "(", "{", "}", ",", "settings", ")", "if", "not", "settings", "[", "\"class\"", "]", ":", "Log", ".", "error", "(", "\"Expecting 'class' attribute with fully qualified class name\"",...
32.387097
22.322581
def _wrlog_details_illegal_gaf(self, fout_err, err_cnts): """Print details regarding illegal GAF lines seen to a log file.""" # fout_err = "{}.log".format(fin_gaf) gaf_base = os.path.basename(fout_err) with open(fout_err, 'w') as prt: prt.write("ILLEGAL GAF ERROR SUMMARY:\n\n...
[ "def", "_wrlog_details_illegal_gaf", "(", "self", ",", "fout_err", ",", "err_cnts", ")", ":", "# fout_err = \"{}.log\".format(fin_gaf)", "gaf_base", "=", "os", ".", "path", ".", "basename", "(", "fout_err", ")", "with", "open", "(", "fout_err", ",", "'w'", ")", ...
51.571429
13.428571
def create_symbol(self, type_, **kwargs): """ Banana banana """ unique_name = kwargs.get('unique_name') if not unique_name: unique_name = kwargs.get('display_name') kwargs['unique_name'] = unique_name filename = kwargs.get('filename') if f...
[ "def", "create_symbol", "(", "self", ",", "type_", ",", "*", "*", "kwargs", ")", ":", "unique_name", "=", "kwargs", ".", "get", "(", "'unique_name'", ")", "if", "not", "unique_name", ":", "unique_name", "=", "kwargs", ".", "get", "(", "'display_name'", "...
35.375
17.975
def convert_aa_code(x): """Converts between 3-letter and 1-letter amino acid codes.""" if len(x) == 1: return amino_acid_codes[x.upper()] elif len(x) == 3: return inverse_aa_codes[x.upper()] else: raise ValueError("Can only convert 1-letter or 3-letter amino acid codes, " ...
[ "def", "convert_aa_code", "(", "x", ")", ":", "if", "len", "(", "x", ")", "==", "1", ":", "return", "amino_acid_codes", "[", "x", ".", "upper", "(", ")", "]", "elif", "len", "(", "x", ")", "==", "3", ":", "return", "inverse_aa_codes", "[", "x", "...
38.111111
15.222222
def ensure_dir(path): """Ensure directory exists. Args: path(str): dir path """ dirpath = os.path.dirname(path) if dirpath and not os.path.exists(dirpath): os.makedirs(dirpath)
[ "def", "ensure_dir", "(", "path", ")", ":", "dirpath", "=", "os", ".", "path", ".", "dirname", "(", "path", ")", "if", "dirpath", "and", "not", "os", ".", "path", ".", "exists", "(", "dirpath", ")", ":", "os", ".", "makedirs", "(", "dirpath", ")" ]
20.5
16.7
def get_cache(self, namespace, query_hash, length, start, end): """Get a cached value for the specified date range and query""" query = 'SELECT start, value FROM gauged_cache WHERE namespace = ? ' \ 'AND hash = ? AND length = ? AND start BETWEEN ? AND ?' cursor = self.cursor ...
[ "def", "get_cache", "(", "self", ",", "namespace", ",", "query_hash", ",", "length", ",", "start", ",", "end", ")", ":", "query", "=", "'SELECT start, value FROM gauged_cache WHERE namespace = ? '", "'AND hash = ? AND length = ? AND start BETWEEN ? AND ?'", "cursor", "=", ...
60
19.285714
def steadystate(A, max_iter=100): """ Empirically determine the steady state probabilities from a stochastic matrix """ P = np.linalg.matrix_power(A, max_iter) # Determine the unique rows in A v = [] for i in range(len(P)): if not np.any([np.allclose(P[i], vi, ) for vi in v]): ...
[ "def", "steadystate", "(", "A", ",", "max_iter", "=", "100", ")", ":", "P", "=", "np", ".", "linalg", ".", "matrix_power", "(", "A", ",", "max_iter", ")", "# Determine the unique rows in A", "v", "=", "[", "]", "for", "i", "in", "range", "(", "len", ...
28.461538
16.461538
def uavionix_adsb_out_dynamic_encode(self, utcTime, gpsLat, gpsLon, gpsAlt, gpsFix, numSats, baroAltMSL, accuracyHor, accuracyVert, accuracyVel, velVert, velNS, VelEW, emergencyStatus, state, squawk): ''' Dynamic data used to generate ADS-B out transponder data (send at 5Hz) ...
[ "def", "uavionix_adsb_out_dynamic_encode", "(", "self", ",", "utcTime", ",", "gpsLat", ",", "gpsLon", ",", "gpsAlt", ",", "gpsFix", ",", "numSats", ",", "baroAltMSL", ",", "accuracyHor", ",", "accuracyVert", ",", "accuracyVel", ",", "velVert", ",", "velNS", ",...
106.347826
76.956522
def retry_count(self): """ Amount of retried test cases in this list. :return: integer """ retries = len([i for i, result in enumerate(self.data) if result.retries_left > 0]) return retries
[ "def", "retry_count", "(", "self", ")", ":", "retries", "=", "len", "(", "[", "i", "for", "i", ",", "result", "in", "enumerate", "(", "self", ".", "data", ")", "if", "result", ".", "retries_left", ">", "0", "]", ")", "return", "retries" ]
28.875
19.125
def safe_join(directory, filename): """Safely join `directory` and `filename`. Example usage:: @app.route('/wiki/<path:filename>') def wiki_page(filename): filename = safe_join(app.config['WIKI_FOLDER'], filename) with open(filename, 'rb') as fd: content...
[ "def", "safe_join", "(", "directory", ",", "filename", ")", ":", "filename", "=", "posixpath", ".", "normpath", "(", "filename", ")", "for", "sep", "in", "_os_alt_seps", ":", "if", "sep", "in", "filename", ":", "raise", "NotFound", "(", ")", "if", "os", ...
35.52
15
def future(self): """Returns all outlets that are or will be active.""" qs = self.get_queryset() return qs.filter( models.Q(end_date__isnull=True) | models.Q(end_date__gte=now().date()) )
[ "def", "future", "(", "self", ")", ":", "qs", "=", "self", ".", "get_queryset", "(", ")", "return", "qs", ".", "filter", "(", "models", ".", "Q", "(", "end_date__isnull", "=", "True", ")", "|", "models", ".", "Q", "(", "end_date__gte", "=", "now", ...
33.857143
12.857143
def get_purged_review_history_for(brain_or_object): """Returns the review history for the object passed in, but filtered with the actions and states that match with the workflow currently bound to the object plus those actions that are None (for initial state) """ history = review_history_cache.get(...
[ "def", "get_purged_review_history_for", "(", "brain_or_object", ")", ":", "history", "=", "review_history_cache", ".", "get", "(", "api", ".", "get_uid", "(", "brain_or_object", ")", ",", "[", "]", ")", "# Boil out those actions not supported by object's current workflow"...
49.47619
26.095238
def extract_smiles(s): """Return a list of SMILES identifiers extracted from the string.""" # TODO: This still gets a lot of false positives. smiles = [] for t in s.split(): if len(t) > 2 and SMILES_RE.match(t) and not t.endswith('.') and bracket_level(t) == 0: smiles.append(t) r...
[ "def", "extract_smiles", "(", "s", ")", ":", "# TODO: This still gets a lot of false positives.", "smiles", "=", "[", "]", "for", "t", "in", "s", ".", "split", "(", ")", ":", "if", "len", "(", "t", ")", ">", "2", "and", "SMILES_RE", ".", "match", "(", ...
40.625
20.375
def put(self, filepath): """ Change the group or permissions of the specified file. Action must be specified when calling this method. """ action = self.get_body_argument('action') if action['action'] == 'update_group': newgrp = action['group'] tr...
[ "def", "put", "(", "self", ",", "filepath", ")", ":", "action", "=", "self", ".", "get_body_argument", "(", "'action'", ")", "if", "action", "[", "'action'", "]", "==", "'update_group'", ":", "newgrp", "=", "action", "[", "'group'", "]", "try", ":", "s...
39.304348
15.826087
def pack(self): """ Pack the structure data into a string """ data = [] for field in self.__fields__: (vtype, vlen) = self.__fields_types__[field] if vtype == 'char': # string data.append(getattr(self, field)) elif isinstance(vt...
[ "def", "pack", "(", "self", ")", ":", "data", "=", "[", "]", "for", "field", "in", "self", ".", "__fields__", ":", "(", "vtype", ",", "vlen", ")", "=", "self", ".", "__fields_types__", "[", "field", "]", "if", "vtype", "==", "'char'", ":", "# strin...
38.857143
8.514286
def _ExpandArtifactGroupSource(self, source, requested): """Recursively expands an artifact group source.""" artifact_list = [] if "names" in source.attributes: artifact_list = source.attributes["names"] for artifact_name in artifact_list: if artifact_name in self.processed_artifacts: ...
[ "def", "_ExpandArtifactGroupSource", "(", "self", ",", "source", ",", "requested", ")", ":", "artifact_list", "=", "[", "]", "if", "\"names\"", "in", "source", ".", "attributes", ":", "artifact_list", "=", "source", ".", "attributes", "[", "\"names\"", "]", ...
45.090909
13.909091
def set_knowledge_category(self, grade_id): """Sets the knowledge category. arg: grade_id (osid.id.Id): the new knowledge category raise: InvalidArgument - ``grade_id`` is invalid raise: NoAccess - ``grade_id`` cannot be modified raise: NullArgument - ``grade_id`` is ``nul...
[ "def", "set_knowledge_category", "(", "self", ",", "grade_id", ")", ":", "# Implemented from template for osid.resource.ResourceForm.set_avatar_template", "if", "self", ".", "get_knowledge_category_metadata", "(", ")", ".", "is_read_only", "(", ")", ":", "raise", "errors", ...
45.3125
17.8125
def delete(self, *args, **kwargs): """ Executes an HTTP DELETE. :Parameters: - `args`: Non-keyword arguments - `kwargs`: Keyword arguments """ return self.session.delete(*args, **self.get_kwargs(**kwargs))
[ "def", "delete", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "session", ".", "delete", "(", "*", "args", ",", "*", "*", "self", ".", "get_kwargs", "(", "*", "*", "kwargs", ")", ")" ]
28.888889
11.777778
def position(self): ''' Return the current position of the boat. :returns: current position :rtype: Point ''' content = self._cached_boat lat, lon = content.get('position') return Point(lat, lon)
[ "def", "position", "(", "self", ")", ":", "content", "=", "self", ".", "_cached_boat", "lat", ",", "lon", "=", "content", ".", "get", "(", "'position'", ")", "return", "Point", "(", "lat", ",", "lon", ")" ]
25.1
16.9
def cookiecutter( template, checkout=None, no_input=False, extra_context=None, replay=False, overwrite_if_exists=False, output_dir='.', config_file=None, default_config=False, password=None): """ Run Cookiecutter just as if using it from the command line. :param template: A director...
[ "def", "cookiecutter", "(", "template", ",", "checkout", "=", "None", ",", "no_input", "=", "False", ",", "extra_context", "=", "None", ",", "replay", "=", "False", ",", "overwrite_if_exists", "=", "False", ",", "output_dir", "=", "'.'", ",", "config_file", ...
35.727273
22.532468
def _nfw_func(self, x): """ Classic NFW function in terms of arctanh and arctan :param x: r/Rs :return: """ c = 0.000001 if isinstance(x, np.ndarray): x[np.where(x<c)] = c nfwvals = np.ones_like(x) inds1 = np.where(x < 1) ...
[ "def", "_nfw_func", "(", "self", ",", "x", ")", ":", "c", "=", "0.000001", "if", "isinstance", "(", "x", ",", "np", ".", "ndarray", ")", ":", "x", "[", "np", ".", "where", "(", "x", "<", "c", ")", "]", "=", "c", "nfwvals", "=", "np", ".", "...
30.964286
22.178571
def _start_connection_setup(self): """Start the connection setup by refreshing the TOCs""" logger.info('We are connected[%s], request connection setup', self.link_uri) self.platform.fetch_platform_informations(self._platform_info_fetched)
[ "def", "_start_connection_setup", "(", "self", ")", ":", "logger", ".", "info", "(", "'We are connected[%s], request connection setup'", ",", "self", ".", "link_uri", ")", "self", ".", "platform", ".", "fetch_platform_informations", "(", "self", ".", "_platform_info_f...
55.6
15.8
def _generate(self, source, name, filename, defer_init=False): """Internal hook that can be overridden to hook a different generate method in. .. versionadded:: 2.5 """ return generate(source, self, name, filename, defer_init=defer_init)
[ "def", "_generate", "(", "self", ",", "source", ",", "name", ",", "filename", ",", "defer_init", "=", "False", ")", ":", "return", "generate", "(", "source", ",", "self", ",", "name", ",", "filename", ",", "defer_init", "=", "defer_init", ")" ]
38.857143
18.714286
def target_socket(self, config): """ This method overrides :meth:`.WNetworkNativeTransport.target_socket` method. Do the same thing as basic method do, but also checks that the result address is IPv4 address. :param config: beacon configuration :return: WIPV4SocketInfo """ target = WNetworkNativeTransport....
[ "def", "target_socket", "(", "self", ",", "config", ")", ":", "target", "=", "WNetworkNativeTransport", ".", "target_socket", "(", "self", ",", "config", ")", "if", "isinstance", "(", "target", ".", "address", "(", ")", ",", "WIPV4Address", ")", "is", "Fal...
43.090909
16.909091
def _update_zone(self, zone, status=None): """ Updates a zones status. :param zone: zone number :type zone: int :param status: zone status :type status: int :raises: IndexError """ if not zone in self._zones: raise IndexError('Zone do...
[ "def", "_update_zone", "(", "self", ",", "zone", ",", "status", "=", "None", ")", ":", "if", "not", "zone", "in", "self", ".", "_zones", ":", "raise", "IndexError", "(", "'Zone does not exist and cannot be updated: %d'", ",", "zone", ")", "old_status", "=", ...
28.241379
15.965517
def context_exists(self, name): """Check if a given context exists.""" contexts = self.data['contexts'] for context in contexts: if context['name'] == name: return True return False
[ "def", "context_exists", "(", "self", ",", "name", ")", ":", "contexts", "=", "self", ".", "data", "[", "'contexts'", "]", "for", "context", "in", "contexts", ":", "if", "context", "[", "'name'", "]", "==", "name", ":", "return", "True", "return", "Fal...
33.571429
7.285714
def s_res(self, components=None): """ Get apparent power in kVA at line(s) and transformer(s). Parameters ---------- components : :obj:`list` List of string representatives of :class:`~.grid.components.Line` or :class:`~.grid.components.Transformer`. If n...
[ "def", "s_res", "(", "self", ",", "components", "=", "None", ")", ":", "if", "components", "is", "None", ":", "return", "self", ".", "apparent_power", "else", ":", "not_included", "=", "[", "_", "for", "_", "in", "components", "if", "_", "not", "in", ...
36.827586
21.586207
def iter_init_append(self) : "creates a Message.AppendIter for appending arguments to the Message." iter = self.AppendIter(None) dbus.dbus_message_iter_init_append(self._dbobj, iter._dbobj) return \ iter
[ "def", "iter_init_append", "(", "self", ")", ":", "iter", "=", "self", ".", "AppendIter", "(", "None", ")", "dbus", ".", "dbus_message_iter_init_append", "(", "self", ".", "_dbobj", ",", "iter", ".", "_dbobj", ")", "return", "iter" ]
40.333333
21.666667
def add_filter(self, filter_, frequencies=None, dB=True, analog=False, sample_rate=None, **kwargs): """Add a linear time-invariant filter to this BodePlot Parameters ---------- filter_ : `~scipy.signal.lti`, `tuple` the filter to plot, either as a `~scipy....
[ "def", "add_filter", "(", "self", ",", "filter_", ",", "frequencies", "=", "None", ",", "dB", "=", "True", ",", "analog", "=", "False", ",", "sample_rate", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "not", "analog", ":", "if", "not", "sa...
35.172414
19.568966
def load_json_body(handler): """ Automatically deserialize event bodies with json.loads. Automatically returns a 400 BAD REQUEST if there is an error while parsing. Usage:: >>> from lambda_decorators import load_json_body >>> @load_json_body ... def handler(event, context): .....
[ "def", "load_json_body", "(", "handler", ")", ":", "@", "wraps", "(", "handler", ")", "def", "wrapper", "(", "event", ",", "context", ")", ":", "if", "isinstance", "(", "event", ".", "get", "(", "'body'", ")", ",", "str", ")", ":", "try", ":", "eve...
29.428571
20.357143
def wind_bft(ms): "Convert wind from metres per second to Beaufort scale" if ms is None: return None for bft in range(len(_bft_threshold)): if ms < _bft_threshold[bft]: return bft return len(_bft_threshold)
[ "def", "wind_bft", "(", "ms", ")", ":", "if", "ms", "is", "None", ":", "return", "None", "for", "bft", "in", "range", "(", "len", "(", "_bft_threshold", ")", ")", ":", "if", "ms", "<", "_bft_threshold", "[", "bft", "]", ":", "return", "bft", "retur...
30.375
14.875
def euclidean(src, tar, qval=2, normalized=False, alphabet=None): """Return the Euclidean distance between two strings. This is a wrapper for :py:meth:`Euclidean.dist_abs`. Parameters ---------- src : str Source string (or QGrams/Counter objects) for comparison tar : str Target...
[ "def", "euclidean", "(", "src", ",", "tar", ",", "qval", "=", "2", ",", "normalized", "=", "False", ",", "alphabet", "=", "None", ")", ":", "return", "Euclidean", "(", ")", ".", "dist_abs", "(", "src", ",", "tar", ",", "qval", ",", "normalized", ",...
26.428571
21.571429
def _collapse_cursor(self, parts): """ Act on any CursorMoveUp commands by deleting preceding tokens """ final_parts = [] for part in parts: # Throw out empty string tokens ("") if not part: continue # Go back, deleting every token in the la...
[ "def", "_collapse_cursor", "(", "self", ",", "parts", ")", ":", "final_parts", "=", "[", "]", "for", "part", "in", "parts", ":", "# Throw out empty string tokens (\"\")", "if", "not", "part", ":", "continue", "# Go back, deleting every token in the last 'line'", "if",...
27.708333
19.583333
def reassemble_options(payload): ''' Reassemble partial options to options, returns a list of dhcp_option DHCP options are basically `|tag|length|value|` structure. When an option is longer than 255 bytes, it can be splitted into multiple structures with the same tag. The splitted structures mu...
[ "def", "reassemble_options", "(", "payload", ")", ":", "options", "=", "[", "]", "option_indices", "=", "{", "}", "def", "process_option_list", "(", "partials", ")", ":", "for", "p", "in", "partials", ":", "if", "p", ".", "tag", "==", "OPTION_END", ":", ...
40.642857
16.738095
def _dump_multipoint(obj, decimals): """ Dump a GeoJSON-like MultiPoint object to WKT. Input parameters and return value are the MULTIPOINT equivalent to :func:`_dump_point`. """ coords = obj['coordinates'] mp = 'MULTIPOINT (%s)' points = (' '.join(_round_and_pad(c, decimals) ...
[ "def", "_dump_multipoint", "(", "obj", ",", "decimals", ")", ":", "coords", "=", "obj", "[", "'coordinates'", "]", "mp", "=", "'MULTIPOINT (%s)'", "points", "=", "(", "' '", ".", "join", "(", "_round_and_pad", "(", "c", ",", "decimals", ")", "for", "c", ...
31.4
12.866667
def get_client(config_file=None, apikey=None, username=None, userpass=None, service_url=None, verify_ssl_certs=None, select_first=None): """Configure the API service and creates a new instance of client. :param str config_file: absolute path to configuration file :param str apikey: apikey fr...
[ "def", "get_client", "(", "config_file", "=", "None", ",", "apikey", "=", "None", ",", "username", "=", "None", ",", "userpass", "=", "None", ",", "service_url", "=", "None", ",", "verify_ssl_certs", "=", "None", ",", "select_first", "=", "None", ")", ":...
42.72973
17.675676
async def get_types(self): """Gets all available types. This function is a coroutine. Return Type: `list`""" async with aiohttp.ClientSession() as session: async with session.get('https://api.weeb.sh/images/types', headers=self.__headers) as resp: if resp.st...
[ "async", "def", "get_types", "(", "self", ")", ":", "async", "with", "aiohttp", ".", "ClientSession", "(", ")", "as", "session", ":", "async", "with", "session", ".", "get", "(", "'https://api.weeb.sh/images/types'", ",", "headers", "=", "self", ".", "__head...
38.916667
19.75
def nhapDaiHan(self, cucSo, gioiTinh): """Nhap dai han Args: cucSo (TYPE): Description gioiTinh (TYPE): Description Returns: TYPE: Description """ for cung in self.thapNhiCung: khoangCach = khoangCachCung(cung.cungSo, self.cungMen...
[ "def", "nhapDaiHan", "(", "self", ",", "cucSo", ",", "gioiTinh", ")", ":", "for", "cung", "in", "self", ".", "thapNhiCung", ":", "khoangCach", "=", "khoangCachCung", "(", "cung", ".", "cungSo", ",", "self", ".", "cungMenh", ",", "gioiTinh", ")", "cung", ...
27.714286
15.428571
def getbranchesurl(idbranch, *args, **kwargs): """Request Branches URL. If idbranch is set, you'll get a response adequate for a MambuBranch object. If not set, you'll get a response adequate for a MambuBranches object. See mambubranch module and pydoc for further information. Currently implemente...
[ "def", "getbranchesurl", "(", "idbranch", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "getparams", "=", "[", "]", "if", "kwargs", ":", "try", ":", "if", "kwargs", "[", "\"fullDetails\"", "]", "==", "True", ":", "getparams", ".", "append", "(...
33.666667
23.805556
def matchImpObjStrs(fdefs,imp_obj_strs,cdefs): '''returns imp_funcs, a dictionary with filepath keys that contains lists of function definition nodes that were imported using from __ import __ style syntax. also returns imp_classes, which is the same for class definition nodes.''' imp_funcs=dict(...
[ "def", "matchImpObjStrs", "(", "fdefs", ",", "imp_obj_strs", ",", "cdefs", ")", ":", "imp_funcs", "=", "dict", "(", ")", "imp_classes", "=", "dict", "(", ")", "for", "source", "in", "imp_obj_strs", ":", "if", "not", "imp_obj_strs", "[", "source", "]", ":...
42.705882
14.705882
def make_dict(name, keys, **kwargs): """ Creates a dictionary-like mapping class that uses perfect hashing. ``name`` is the proper class name of the returned class. See ``hash_parameters()`` for documentation on all arguments after ``name``. >>> MyDict = make_dict('MyDict', '+-<>[],.', to_int=o...
[ "def", "make_dict", "(", "name", ",", "keys", ",", "*", "*", "kwargs", ")", ":", "hash_func", "=", "make_hash", "(", "keys", ",", "*", "*", "kwargs", ")", "slots", "=", "hash_func", ".", "slots", "# Create a docstring that at least describes where the class came...
30.9
19.133333
def softDeactivate(rh): """ Deactivate a virtual machine by first shutting down Linux and then log it off. Input: Request Handle with the following properties: function - 'POWERVM' subfunction - 'SOFTOFF' userid - userid of the virtual machine parm...
[ "def", "softDeactivate", "(", "rh", ")", ":", "rh", ".", "printSysLog", "(", "\"Enter powerVM.softDeactivate, userid: \"", "+", "rh", ".", "userid", ")", "strCmd", "=", "\"echo 'ping'\"", "iucvResults", "=", "execCmdThruIUCV", "(", "rh", ",", "rh", ".", "userid"...
38.115385
18.423077
def mdot(*args): """Computes a matrix product of multiple ndarrays This is a convenience function to avoid constructs such as np.dot(A, np.dot(B, np.dot(C, D))) and instead use mdot(A, B, C, D). Parameters ---------- *args : an arbitrarily long list of ndarrays that must be compatible for mult...
[ "def", "mdot", "(", "*", "args", ")", ":", "if", "len", "(", "args", ")", "<", "1", ":", "raise", "ValueError", "(", "'need at least one argument'", ")", "elif", "len", "(", "args", ")", "==", "1", ":", "return", "args", "[", "0", "]", "elif", "len...
32.684211
22.368421
def findViewWithAttributeThatMatches(self, attr, regex, root="ROOT"): ''' Finds the list of Views with the specified attribute matching regex ''' return self.__findViewWithAttributeInTreeThatMatches(attr, regex, root)
[ "def", "findViewWithAttributeThatMatches", "(", "self", ",", "attr", ",", "regex", ",", "root", "=", "\"ROOT\"", ")", ":", "return", "self", ".", "__findViewWithAttributeInTreeThatMatches", "(", "attr", ",", "regex", ",", "root", ")" ]
36
31.714286
def write_data(self, buf): """Send data to the device. If the write fails for any reason, an :obj:`IOError` exception is raised. :param buf: the data to send. :type buf: list(int) :return: success status. :rtype: bool """ bmRequestType = usb....
[ "def", "write_data", "(", "self", ",", "buf", ")", ":", "bmRequestType", "=", "usb", ".", "util", ".", "build_request_type", "(", "usb", ".", "util", ".", "ENDPOINT_OUT", ",", "usb", ".", "util", ".", "CTRL_TYPE_CLASS", ",", "usb", ".", "util", ".", "C...
27.241379
17.793103
def mobile(self): """ Access the mobile :returns: twilio.rest.api.v2010.account.incoming_phone_number.mobile.MobileList :rtype: twilio.rest.api.v2010.account.incoming_phone_number.mobile.MobileList """ if self._mobile is None: self._mobile = MobileList(self._...
[ "def", "mobile", "(", "self", ")", ":", "if", "self", ".", "_mobile", "is", "None", ":", "self", ".", "_mobile", "=", "MobileList", "(", "self", ".", "_version", ",", "account_sid", "=", "self", ".", "_solution", "[", "'account_sid'", "]", ",", ")", ...
39.2
24.8
def remove(self, block_id): """Remove a Processing Block from the queue. Args: block_id (str): """ with self._mutex: entry = self._block_map[block_id] self._queue.remove(entry)
[ "def", "remove", "(", "self", ",", "block_id", ")", ":", "with", "self", ".", "_mutex", ":", "entry", "=", "self", ".", "_block_map", "[", "block_id", "]", "self", ".", "_queue", ".", "remove", "(", "entry", ")" ]
26.333333
12.888889
def color(self, key): """ Returns the color value for the given key for this console. :param key | <unicode> :return <QtGui.QColor> """ if type(key) == int: key = self.LoggingMap.get(key, ('NotSet', ''))[0] name = n...
[ "def", "color", "(", "self", ",", "key", ")", ":", "if", "type", "(", "key", ")", "==", "int", ":", "key", "=", "self", ".", "LoggingMap", ".", "get", "(", "key", ",", "(", "'NotSet'", ",", "''", ")", ")", "[", "0", "]", "name", "=", "natives...
31.75
13.083333
def get_common(self, filename): ''' Process lists of common name words ''' word_list = [] words = open(filename) for word in words.readlines(): word_list.append(word.strip()) return word_list
[ "def", "get_common", "(", "self", ",", "filename", ")", ":", "word_list", "=", "[", "]", "words", "=", "open", "(", "filename", ")", "for", "word", "in", "words", ".", "readlines", "(", ")", ":", "word_list", ".", "append", "(", "word", ".", "strip",...
33.857143
9.571429
def update(self, *args, **kwargs): """ update() method will *recursively* update nested dict: >>> d=Dict({'a':{'b':{'c':3,'d':4},'h':4}}) >>> d.update({'a':{'b':{'c':'888'}}}) >>> d {'a': {'b': {'c': '888', 'd': 4}, 'h': 4}} please use update_dict() ...
[ "def", "update", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "for", "arg", "in", "args", ":", "if", "not", "arg", ":", "continue", "elif", "isinstance", "(", "arg", ",", "dict", ")", ":", "for", "k", ",", "v", "in", "arg",...
37.137931
16.068966
def stop(name, vmid=None, call=None): ''' Stop a node ("pulling the plug"). CLI Example: .. code-block:: bash salt-cloud -a stop mymachine ''' if call != 'action': raise SaltCloudSystemExit( 'The stop action must be called with -a or --action.' ) if no...
[ "def", "stop", "(", "name", ",", "vmid", "=", "None", ",", "call", "=", "None", ")", ":", "if", "call", "!=", "'action'", ":", "raise", "SaltCloudSystemExit", "(", "'The stop action must be called with -a or --action.'", ")", "if", "not", "set_vm_status", "(", ...
26.590909
23.863636
def _profiles_index(self): """ read profiles.index and make hash array Notes ----- sets the attributes. log_ind : hash array that returns profile.data or log.data file number from model number. model : the models for which profile.data or log.data is ...
[ "def", "_profiles_index", "(", "self", ")", ":", "prof_ind_name", "=", "self", ".", "prof_ind_name", "f", "=", "open", "(", "self", ".", "sldir", "+", "'/'", "+", "prof_ind_name", ",", "'r'", ")", "line", "=", "f", ".", "readline", "(", ")", "numlines"...
25.228571
20.142857
def render(sls_data, saltenv='base', sls='', **kws): ''' Accepts YAML_EX as a string or as a file object and runs it through the YAML_EX parser. :rtype: A Python data structure ''' with warnings.catch_warnings(record=True) as warn_list: data = deserialize(sls_data) or {} for it...
[ "def", "render", "(", "sls_data", ",", "saltenv", "=", "'base'", ",", "sls", "=", "''", ",", "*", "*", "kws", ")", ":", "with", "warnings", ".", "catch_warnings", "(", "record", "=", "True", ")", "as", "warn_list", ":", "data", "=", "deserialize", "(...
28.631579
24.210526
def retryable_writes_supported(self): """Checks if this server supports retryable writes.""" return ( self._ls_timeout_minutes is not None and self._server_type in (SERVER_TYPE.Mongos, SERVER_TYPE.RSPrimary))
[ "def", "retryable_writes_supported", "(", "self", ")", ":", "return", "(", "self", ".", "_ls_timeout_minutes", "is", "not", "None", "and", "self", ".", "_server_type", "in", "(", "SERVER_TYPE", ".", "Mongos", ",", "SERVER_TYPE", ".", "RSPrimary", ")", ")" ]
48.8
15.2
def sentence_texts(self): """The list of texts representing ``sentences`` layer elements.""" if not self.is_tagged(SENTENCES): self.tokenize_sentences() return self.texts(SENTENCES)
[ "def", "sentence_texts", "(", "self", ")", ":", "if", "not", "self", ".", "is_tagged", "(", "SENTENCES", ")", ":", "self", ".", "tokenize_sentences", "(", ")", "return", "self", ".", "texts", "(", "SENTENCES", ")" ]
42.6
4.6
def set(self, section, option, value=None): """Set an option. Args: section (str): section name option (str): option name value (str): value, default None """ try: section = self.__getitem__(section) except KeyError: ra...
[ "def", "set", "(", "self", ",", "section", ",", "option", ",", "value", "=", "None", ")", ":", "try", ":", "section", "=", "self", ".", "__getitem__", "(", "section", ")", "except", "KeyError", ":", "raise", "NoSectionError", "(", "section", ")", "from...
29.111111
11.444444
def FormatException(self, e, output): """Append HTML version of e to list output.""" d = e.GetDictToFormat() for k in ('file_name', 'feedname', 'column_name'): if k in d.keys(): d[k] = '<code>%s</code>' % d[k] if 'url' in d.keys(): d['url'] = '<a href="%(url)s">%(url)s</a>' % d ...
[ "def", "FormatException", "(", "self", ",", "e", ",", "output", ")", ":", "d", "=", "e", ".", "GetDictToFormat", "(", ")", "for", "k", "in", "(", "'file_name'", ",", "'feedname'", ",", "'column_name'", ")", ":", "if", "k", "in", "d", ".", "keys", "...
38.452381
14.309524
def sorted_bits(self) -> List[Tuple[str, int]]: """Return list of bit items sorted by position.""" return sorted(self.bit.items(), key=lambda x: x[1])
[ "def", "sorted_bits", "(", "self", ")", "->", "List", "[", "Tuple", "[", "str", ",", "int", "]", "]", ":", "return", "sorted", "(", "self", ".", "bit", ".", "items", "(", ")", ",", "key", "=", "lambda", "x", ":", "x", "[", "1", "]", ")" ]
54.666667
8.666667
def resample_spline(points, smooth=.001, count=None, degree=3): """ Resample a path in space, smoothing along a b-spline. Parameters ----------- points: (n, dimension) float, points in space smooth: float, smoothing amount count: number of samples in output degree: int, degree of splin...
[ "def", "resample_spline", "(", "points", ",", "smooth", "=", ".001", ",", "count", "=", "None", ",", "degree", "=", "3", ")", ":", "from", "scipy", ".", "interpolate", "import", "splprep", ",", "splev", "if", "count", "is", "None", ":", "count", "=", ...
28.258065
17.612903
def delete_one(self, mongo_collection, filter_doc, mongo_db=None, **kwargs): """ Deletes a single document in a mongo collection. https://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.delete_one :param mongo_collection: The name of the collecti...
[ "def", "delete_one", "(", "self", ",", "mongo_collection", ",", "filter_doc", ",", "mongo_db", "=", "None", ",", "*", "*", "kwargs", ")", ":", "collection", "=", "self", ".", "get_collection", "(", "mongo_collection", ",", "mongo_db", "=", "mongo_db", ")", ...
45.882353
26.705882
def _autofill_spec_record(record): """ Returns an astropy table with columns auto-filled from FITS header Parameters ---------- record: astropy.io.fits.table.table.Row The spectrum table row to scrape Returns ------- record: astropy.io.fits.table.table.Row The spectrum ...
[ "def", "_autofill_spec_record", "(", "record", ")", ":", "try", ":", "record", "[", "'filename'", "]", "=", "os", ".", "path", ".", "basename", "(", "record", "[", "'spectrum'", "]", ")", "if", "record", "[", "'spectrum'", "]", ".", "endswith", "(", "'...
48.392857
26.946429
def _draw(self, size=1, **kwargs): """Draws random samples without applying physical constrains. """ # draw masses try: mass1 = kwargs['mass1'] except KeyError: mass1 = self.mass1_distr.rvs(size=size)['mass1'] try: mass2 = kwargs['mass2...
[ "def", "_draw", "(", "self", ",", "size", "=", "1", ",", "*", "*", "kwargs", ")", ":", "# draw masses", "try", ":", "mass1", "=", "kwargs", "[", "'mass1'", "]", "except", "KeyError", ":", "mass1", "=", "self", ".", "mass1_distr", ".", "rvs", "(", "...
31.36
15.16
def get_id_constraints(pkname, pkey): """Returns primary key consraints. :pkname: if a string, returns a dict with pkname=pkey. pkname and pkey must be enumerables of matching length. """ if isinstance(pkname, str): return {pkname: pkey} else: return dict(zip(pkname, pkey))
[ "def", "get_id_constraints", "(", "pkname", ",", "pkey", ")", ":", "if", "isinstance", "(", "pkname", ",", "str", ")", ":", "return", "{", "pkname", ":", "pkey", "}", "else", ":", "return", "dict", "(", "zip", "(", "pkname", ",", "pkey", ")", ")" ]
28.6
18.5
def stat_article_detail_list(self, page=1, start_date=str(date.today()+timedelta(days=-30)), end_date=str(date.today())): """ 获取图文分析数据 返回JSON示例 :: { "hasMore": true, // 说明是否可以增加 page 页码来获取数据 "data": [ { "i...
[ "def", "stat_article_detail_list", "(", "self", ",", "page", "=", "1", ",", "start_date", "=", "str", "(", "date", ".", "today", "(", ")", "+", "timedelta", "(", "days", "=", "-", "30", ")", ")", ",", "end_date", "=", "str", "(", "date", ".", "toda...
119.192661
95.119266
def confdate(self): """Date range of the conference the abstract belongs to represented by two tuples in the form (YYYY, MM, DD). """ date = self._confevent.get('confdate', {}) if len(date) > 0: start = {k: int(v) for k, v in date['startdate'].items()} end...
[ "def", "confdate", "(", "self", ")", ":", "date", "=", "self", ".", "_confevent", ".", "get", "(", "'confdate'", ",", "{", "}", ")", "if", "len", "(", "date", ")", ">", "0", ":", "start", "=", "{", "k", ":", "int", "(", "v", ")", "for", "k", ...
47.25
17.25
def __package_dependencies(dist_dir, additional_reqs, silent): """ Installs the app's dependencies from pip and packages them (as zip), to be submitted to spark. Parameters ---------- dist_dir (str): Path to directory where the packaged libs shall be located additional_reqs (str): Path to a req...
[ "def", "__package_dependencies", "(", "dist_dir", ",", "additional_reqs", ",", "silent", ")", ":", "logging", ".", "info", "(", "'Packaging dependencies'", ")", "libs_dir", "=", "os", ".", "path", ".", "join", "(", "dist_dir", ",", "'libs'", ")", "if", "not"...
35.384615
21.076923
def get_pyocd_flash_algo(self, blocksize, ram_region): """! @brief Return a dictionary representing a pyOCD flash algorithm, or None. The most interesting operation this method performs is dynamically allocating memory for the flash algo from a given RAM region. Note that the .data and ...
[ "def", "get_pyocd_flash_algo", "(", "self", ",", "blocksize", ",", "ram_region", ")", ":", "instructions", "=", "self", ".", "_FLASH_BLOB_HEADER", "+", "byte_list_to_u32le_list", "(", "self", ".", "algo_data", ")", "offset", "=", "0", "# Stack", "offset", "+=", ...
37.434783
21.594203
def step(self, thumb=False): """Executes a single step. Steps even if there is a breakpoint. Args: self (JLink): the ``JLink`` instance thumb (bool): boolean indicating if to step in thumb mode Returns: ``None`` Raises: JLinkException: ...
[ "def", "step", "(", "self", ",", "thumb", "=", "False", ")", ":", "method", "=", "self", ".", "_dll", ".", "JLINKARM_Step", "if", "thumb", ":", "method", "=", "self", ".", "_dll", ".", "JLINKARM_StepComposite", "res", "=", "method", "(", ")", "if", "...
23.833333
21.791667
def write_plot(plot, filename, width=DEFAULT_PAGE_WIDTH, height=DEFAULT_PAGE_HEIGHT, unit=DEFAULT_PAGE_UNIT): """Writes a plot SVG to a file. Args: plot (list): a list of layers to plot filename (str): the name of the file to write width (float): the width of the output SVG heig...
[ "def", "write_plot", "(", "plot", ",", "filename", ",", "width", "=", "DEFAULT_PAGE_WIDTH", ",", "height", "=", "DEFAULT_PAGE_HEIGHT", ",", "unit", "=", "DEFAULT_PAGE_UNIT", ")", ":", "svg", "=", "plot_to_svg", "(", "plot", ",", "width", ",", "height", ",", ...
40.461538
16.461538
def common_srun_options(cls, campaign): """Get options to be given to all srun commands :rtype: list of string """ default = dict(campaign.process.get('srun') or {}) default.update(output='slurm-%N-%t.stdout', error='slurm-%N-%t.error') return default
[ "def", "common_srun_options", "(", "cls", ",", "campaign", ")", ":", "default", "=", "dict", "(", "campaign", ".", "process", ".", "get", "(", "'srun'", ")", "or", "{", "}", ")", "default", ".", "update", "(", "output", "=", "'slurm-%N-%t.stdout'", ",", ...
36.625
15.625
def _initialize_from_model(self, model): """ Loads a model from """ for name, value in model.__dict__.items(): if name in self._properties: setattr(self, name, value)
[ "def", "_initialize_from_model", "(", "self", ",", "model", ")", ":", "for", "name", ",", "value", "in", "model", ".", "__dict__", ".", "items", "(", ")", ":", "if", "name", "in", "self", ".", "_properties", ":", "setattr", "(", "self", ",", "name", ...
31.428571
3.714286
def translate_reaction(reaction, metabolite_mapping): """ Return a mapping from KEGG compound identifiers to coefficients. Parameters ---------- reaction : cobra.Reaction The reaction whose metabolites are to be translated. metabolite_mapping : dict An existing mapping from cobr...
[ "def", "translate_reaction", "(", "reaction", ",", "metabolite_mapping", ")", ":", "# Transport reactions where the same metabolite occurs in different", "# compartments should have been filtered out but just to be sure, we add", "# coefficients in the mapping.", "stoichiometry", "=", "def...
35.466667
21.733333
def degToDms(dec, isLatitude=True): """Convert the dec, in degrees, to an (sign,D,M,S) tuple. D and M are integer, and sign and S are float. """ if isLatitude: assert dec <= 90, WCSError("DEC (%f) > 90.0" % (dec)) assert dec >= -90, WCSError("DEC (%f) < -90.0" % (dec)) if dec < 0.0:...
[ "def", "degToDms", "(", "dec", ",", "isLatitude", "=", "True", ")", ":", "if", "isLatitude", ":", "assert", "dec", "<=", "90", ",", "WCSError", "(", "\"DEC (%f) > 90.0\"", "%", "(", "dec", ")", ")", "assert", "dec", ">=", "-", "90", ",", "WCSError", ...
31.208333
17.958333
def _register_info(self): """Register local methods in the Workbench Information system""" # Stores information on Workbench commands and signatures for name, meth in inspect.getmembers(self, predicate=inspect.isroutine): if not name.startswith('_') and name != 'run': ...
[ "def", "_register_info", "(", "self", ")", ":", "# Stores information on Workbench commands and signatures", "for", "name", ",", "meth", "in", "inspect", ".", "getmembers", "(", "self", ",", "predicate", "=", "inspect", ".", "isroutine", ")", ":", "if", "not", "...
70.8
36.666667
def original_lesk(context_sentence: str, ambiguous_word: str, dictionary=None, from_cache=True) -> "wn.Synset": """ This function is the implementation of the original Lesk algorithm (1986). It requires a dictionary which contains the definition of the different sense of each word. See http://dl.acm.org...
[ "def", "original_lesk", "(", "context_sentence", ":", "str", ",", "ambiguous_word", ":", "str", ",", "dictionary", "=", "None", ",", "from_cache", "=", "True", ")", "->", "\"wn.Synset\"", ":", "ambiguous_word", "=", "lemmatize", "(", "ambiguous_word", ")", "if...
48
28.235294
def cache(ctx, clear_subliminal): """Cache management.""" if clear_subliminal: for file in glob.glob(os.path.join(ctx.parent.params['cache_dir'], cache_file) + '*'): os.remove(file) click.echo('Subliminal\'s cache cleared.') else: click.echo('Nothing done.')
[ "def", "cache", "(", "ctx", ",", "clear_subliminal", ")", ":", "if", "clear_subliminal", ":", "for", "file", "in", "glob", ".", "glob", "(", "os", ".", "path", ".", "join", "(", "ctx", ".", "parent", ".", "params", "[", "'cache_dir'", "]", ",", "cach...
37.375
17
def patched_contractfunction_estimateGas(self, transaction=None, block_identifier=None): """Temporary workaround until next web3.py release (5.X.X)""" if transaction is None: estimate_gas_transaction = {} else: estimate_gas_transaction = dict(**transaction) if 'data' in estimate_gas_tra...
[ "def", "patched_contractfunction_estimateGas", "(", "self", ",", "transaction", "=", "None", ",", "block_identifier", "=", "None", ")", ":", "if", "transaction", "is", "None", ":", "estimate_gas_transaction", "=", "{", "}", "else", ":", "estimate_gas_transaction", ...
35.051282
21.076923
def backup_file(filename): """ create a backup of the file desired """ if not os.path.exists(filename): return BACKUP_SUFFIX = ".sprinter.bak" backup_filename = filename + BACKUP_SUFFIX shutil.copyfile(filename, backup_filename)
[ "def", "backup_file", "(", "filename", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "filename", ")", ":", "return", "BACKUP_SUFFIX", "=", "\".sprinter.bak\"", "backup_filename", "=", "filename", "+", "BACKUP_SUFFIX", "shutil", ".", "copyfile",...
27.777778
15.666667
def _page(self, text, html=False): """ Displays text using the pager if it exceeds the height of the viewport. Parameters: ----------- html : bool, optional (default False) If set, the text will be interpreted as HTML instead of plain text. """ line_h...
[ "def", "_page", "(", "self", ",", "text", ",", "html", "=", "False", ")", ":", "line_height", "=", "QtGui", ".", "QFontMetrics", "(", "self", ".", "font", ")", ".", "height", "(", ")", "minlines", "=", "self", ".", "_control", ".", "viewport", "(", ...
39.794118
16.794118
def _save_to_database(url, property_name, data): """ Store `data` under `property_name` in the `url` key in REST API DB. Args: url (obj): URL of the resource to which `property_name` will be stored. property_name (str): Name of the property under which the `data` will be stored....
[ "def", "_save_to_database", "(", "url", ",", "property_name", ",", "data", ")", ":", "data", "=", "json", ".", "dumps", "(", "[", "d", ".", "to_dict", "(", ")", "if", "hasattr", "(", "d", ",", "\"to_dict\"", ")", "else", "d", "for", "d", "in", "dat...
25.285714
21.628571
def industry_name(self): """ [str] 国民经济行业分类名称(股票专用) """ try: return self.__dict__["industry_name"] except (KeyError, ValueError): raise AttributeError( "Instrument(order_book_id={}) has no attribute 'industry_name' ".format(self.order_book_...
[ "def", "industry_name", "(", "self", ")", ":", "try", ":", "return", "self", ".", "__dict__", "[", "\"industry_name\"", "]", "except", "(", "KeyError", ",", "ValueError", ")", ":", "raise", "AttributeError", "(", "\"Instrument(order_book_id={}) has no attribute 'ind...
32.8
16.6
def _get_outputs(self): """ Return a dict of the terraform outputs. :return: dict of terraform outputs :rtype: dict """ if self.tf_version >= (0, 7, 0): logger.debug('Running: terraform output') res = self._run_tf('output', cmd_args=['-json']) ...
[ "def", "_get_outputs", "(", "self", ")", ":", "if", "self", ".", "tf_version", ">=", "(", "0", ",", "7", ",", "0", ")", ":", "logger", ".", "debug", "(", "'Running: terraform output'", ")", "res", "=", "self", ".", "_run_tf", "(", "'output'", ",", "c...
33.166667
11.033333
def get_node(self): """return etree Element representing this slide""" # already added title, text frames # add animation chunks if self.animations: anim_par = el("anim:par", attrib={"presentation:node-type": "timing-root"}) self._page.append(anim_par) ...
[ "def", "get_node", "(", "self", ")", ":", "# already added title, text frames", "# add animation chunks", "if", "self", ".", "animations", ":", "anim_par", "=", "el", "(", "\"anim:par\"", ",", "attrib", "=", "{", "\"presentation:node-type\"", ":", "\"timing-root\"", ...
39.714286
15.714286
def write_to_file(self, filename): """ Write the configuration to a file. Use the correct order of values. """ fid = open(filename, 'w') for key in self.key_order: if(key == -1): fid.write('\n') else: fid.write('{0}\n'.format(self[...
[ "def", "write_to_file", "(", "self", ",", "filename", ")", ":", "fid", "=", "open", "(", "filename", ",", "'w'", ")", "for", "key", "in", "self", ".", "key_order", ":", "if", "(", "key", "==", "-", "1", ")", ":", "fid", ".", "write", "(", "'\\n'"...
28
14.833333
def ask_user(d): """Wrap sphinx.quickstart.ask_user, and add additional questions.""" # Print welcome message msg = bold('Welcome to the Hieroglyph %s quickstart utility.') % ( version(), ) print(msg) msg = """ This will ask questions for creating a Hieroglyph project, and then ask some...
[ "def", "ask_user", "(", "d", ")", ":", "# Print welcome message", "msg", "=", "bold", "(", "'Welcome to the Hieroglyph %s quickstart utility.'", ")", "%", "(", "version", "(", ")", ",", ")", "print", "(", "msg", ")", "msg", "=", "\"\"\"\nThis will ask questions fo...
24.754098
22.737705
def decode(self, r, nostrip=False, k=None, erasures_pos=None, only_erasures=False, return_string=True): '''Given a received string or byte array or list r of values between 0 and gf2_charac, attempts to decode it. If it's a valid codeword, or if there are no more than (n-k)/2 errors, the repaire...
[ "def", "decode", "(", "self", ",", "r", ",", "nostrip", "=", "False", ",", "k", "=", "None", ",", "erasures_pos", "=", "None", ",", "only_erasures", "=", "False", ",", "return_string", "=", "True", ")", ":", "n", "=", "self", ".", "n", "if", "not",...
71.637097
51.604839
def _build_pub_key_auth(self, context, nonce, auth_token, public_key): """ [MS-CSSP] 3.1.5 Processing Events and Sequencing Rules - Step 3 https://msdn.microsoft.com/en-us/library/cc226791.aspx This step sends the final SPNEGO token to the server if required and computes the val...
[ "def", "_build_pub_key_auth", "(", "self", ",", "context", ",", "nonce", ",", "auth_token", ",", "public_key", ")", ":", "ts_request", "=", "TSRequest", "(", ")", "if", "auth_token", "is", "not", "None", ":", "nego_token", "=", "NegoToken", "(", ")", "nego...
39.893617
22.276596
def addIndexOnAttribute(self, attributeName): ''' addIndexOnAttribute - Add an index for an arbitrary attribute. This will be used by the getElementsByAttr function. You should do this prior to parsing, or call reindex. Otherwise it will be blank. "name" and "id" will have no effect....
[ "def", "addIndexOnAttribute", "(", "self", ",", "attributeName", ")", ":", "attributeName", "=", "attributeName", ".", "lower", "(", ")", "self", ".", "_otherAttributeIndexes", "[", "attributeName", "]", "=", "{", "}", "def", "_otherIndexFunction", "(", "self", ...
52.421053
34.947368
def windows_from_blocksize(self, blocksize_xy=512): """Create rasterio.windows.Window instances with given size which fully cover the raster. Arguments: blocksize_xy {int or list of two int} -- Size of the window. If one integer is given it defines the width and height of th...
[ "def", "windows_from_blocksize", "(", "self", ",", "blocksize_xy", "=", "512", ")", ":", "meta", "=", "self", ".", "_get_template_for_given_resolution", "(", "self", ".", "dst_res", ",", "\"meta\"", ")", "width", "=", "meta", "[", "\"width\"", "]", "height", ...
50.1
29.4
def read_last_checkpoint(self): """Read the last checkpoint from the oplog progress dictionary. """ # In versions of mongo-connector 2.3 and before, # we used the repr of the # oplog collection as keys in the oplog_progress dictionary. # In versions thereafter, we use the...
[ "def", "read_last_checkpoint", "(", "self", ")", ":", "# In versions of mongo-connector 2.3 and before,", "# we used the repr of the", "# oplog collection as keys in the oplog_progress dictionary.", "# In versions thereafter, we use the replica set name. For backwards", "# compatibility, we chec...
36.961538
15.5
def localDeformationVsBPS(dnaRef, bpRef, dnaProbe, bpProbe, parameter, err_type='std', bp_range=True, merge_bp=1, merge_method='mean', masked=False, tool='gmx analyze'): """To calculate deformation of local parameters in probe DNA with respect to a reference DNA as a function of the bp/s. ...
[ "def", "localDeformationVsBPS", "(", "dnaRef", ",", "bpRef", ",", "dnaProbe", ",", "bpProbe", ",", "parameter", ",", "err_type", "=", "'std'", ",", "bp_range", "=", "True", ",", "merge_bp", "=", "1", ",", "merge_method", "=", "'mean'", ",", "masked", "=", ...
44.961165
33.563107