text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def get_case_groups(adapter, total_cases, institute_id=None, slice_query=None): """Return the information about case groups Args: store(adapter.MongoAdapter) total_cases(int): Total number of cases slice_query(str): Query to filter cases to obtain statistics for. Returns: c...
[ "def", "get_case_groups", "(", "adapter", ",", "total_cases", ",", "institute_id", "=", "None", ",", "slice_query", "=", "None", ")", ":", "# Create a group with all cases in the database", "cases", "=", "[", "{", "'status'", ":", "'all'", ",", "'count'", ":", "...
33.2
0.002195
def list_backups(path, limit=None): ''' .. versionadded:: 0.17.0 Lists the previous versions of a file backed up using Salt's :ref:`file state backup <file-state-backups>` system. path The path on the minion to check for backups limit Limit the number of results to the most rec...
[ "def", "list_backups", "(", "path", ",", "limit", "=", "None", ")", ":", "path", "=", "os", ".", "path", ".", "expanduser", "(", "path", ")", "try", ":", "limit", "=", "int", "(", "limit", ")", "except", "TypeError", ":", "pass", "except", "ValueErro...
32.304348
0.000435
def read_api_service_status(self, name, **kwargs): # noqa: E501 """read_api_service_status # noqa: E501 read status of the specified APIService # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True ...
[ "def", "read_api_service_status", "(", "self", ",", "name", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async_req'", ")", ":", "return", "self", ".", "re...
46.363636
0.001921
def _parse_ip_addr_show(raw_result): """ Parse the 'ip addr list dev' command raw output. :param str raw_result: os raw result string. :rtype: dict :return: The parsed result of the show interface command in a \ dictionary of the form: :: { 'os_index' : '0', ...
[ "def", "_parse_ip_addr_show", "(", "raw_result", ")", ":", "# does link exist?", "show_re", "=", "(", "r'\"(?P<dev>\\S+)\"\\s+does not exist'", ")", "re_result", "=", "search", "(", "show_re", ",", "raw_result", ")", "result", "=", "None", "if", "not", "(", "re_re...
29.515152
0.000497
def get_work_kind(self): """ We'll have a kind_slug like 'movies'. We need to translate that into a work `kind` like 'movie'. """ slugs_to_kinds = {v:k for k,v in Work.KIND_SLUGS.items()} return slugs_to_kinds.get(self.kind_slug, None)
[ "def", "get_work_kind", "(", "self", ")", ":", "slugs_to_kinds", "=", "{", "v", ":", "k", "for", "k", ",", "v", "in", "Work", ".", "KIND_SLUGS", ".", "items", "(", ")", "}", "return", "slugs_to_kinds", ".", "get", "(", "self", ".", "kind_slug", ",", ...
39.571429
0.014134
def textMerge(self, second): """Merge two text nodes into one """ if second is None: second__o = None else: second__o = second._o ret = libxml2mod.xmlTextMerge(self._o, second__o) if ret is None:raise treeError('xmlTextMerge() failed') __tmp = xmlNode(_obj=ret) re...
[ "def", "textMerge", "(", "self", ",", "second", ")", ":", "if", "second", "is", "None", ":", "second__o", "=", "None", "else", ":", "second__o", "=", "second", ".", "_o", "ret", "=", "libxml2mod", ".", "xmlTextMerge", "(", "self", ".", "_o", ",", "se...
40.375
0.018182
def list_group_members(self, group_url, max_results=0): ''' a method to retrieve a list of members for a meetup group :param group_url: string with meetup urlname for group :param max_results: [optional] integer with number of members to include :return: dictionary with list of m...
[ "def", "list_group_members", "(", "self", ",", "group_url", ",", "max_results", "=", "0", ")", ":", "# https://www.meetup.com/meetup_api/docs/:urlname/members/#list\r", "title", "=", "'%s.list_group_members'", "%", "self", ".", "__class__", ".", "__name__", "# validate in...
35.06383
0.002361
def mean_squared_logarithmic_error(pred:Tensor, targ:Tensor)->Rank0Tensor: "Mean squared logarithmic error between `pred` and `targ`." pred,targ = flatten_check(pred,targ) return F.mse_loss(torch.log(1 + pred), torch.log(1 + targ))
[ "def", "mean_squared_logarithmic_error", "(", "pred", ":", "Tensor", ",", "targ", ":", "Tensor", ")", "->", "Rank0Tensor", ":", "pred", ",", "targ", "=", "flatten_check", "(", "pred", ",", "targ", ")", "return", "F", ".", "mse_loss", "(", "torch", ".", "...
60
0.024691
def _parse_qstat_state(qstat_out, job_id): """Parse "state" column from `qstat` output for given job_id Returns state for the *first* job matching job_id. Returns 'u' if `qstat` output is empty or job_id is not found. """ if qstat_out.strip() == '': return 'u' lines = qstat_out.split('...
[ "def", "_parse_qstat_state", "(", "qstat_out", ",", "job_id", ")", ":", "if", "qstat_out", ".", "strip", "(", ")", "==", "''", ":", "return", "'u'", "lines", "=", "qstat_out", ".", "split", "(", "'\\n'", ")", "# skip past header", "while", "not", "lines", ...
30.631579
0.001667
def integrate_scanpy(adatas, **kwargs): """Integrate a list of `scanpy.api.AnnData`. Parameters ---------- adatas : `list` of `scanpy.api.AnnData` Data sets to integrate. kwargs : `dict` See documentation for the `integrate()` method for a full list of parameters to use for ...
[ "def", "integrate_scanpy", "(", "adatas", ",", "*", "*", "kwargs", ")", ":", "datasets_dimred", ",", "genes", "=", "integrate", "(", "[", "adata", ".", "X", "for", "adata", "in", "adatas", "]", ",", "[", "adata", ".", "var_names", ".", "values", "for",...
26.541667
0.001515
def _read2(self, length=None, use_compression=None, project=None, **kwargs): ''' :param length: Maximum number of bytes to be read :type length: integer :param project: project to use as context for this download (may affect which billing account is billed for this download)....
[ "def", "_read2", "(", "self", ",", "length", "=", "None", ",", "use_compression", "=", "None", ",", "project", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "_file_length", "==", "None", ":", "desc", "=", "self", ".", "describe",...
46.480519
0.002462
def _filter_ignored(self, entries, selector=None): """Given an opaque entry list, filter any ignored entries. :param entries: A list or generator that produces entries to filter. :param selector: A function that computes a path for an entry relative to the root of the ProjectTree, or None to use iden...
[ "def", "_filter_ignored", "(", "self", ",", "entries", ",", "selector", "=", "None", ")", ":", "selector", "=", "selector", "or", "(", "lambda", "x", ":", "x", ")", "prefixed_entries", "=", "[", "(", "self", ".", "_append_slash_if_dir_path", "(", "selector...
55.25
0.008902
def create_state_multi_precision(self, index, weight): """Creates auxiliary state for a given weight, including FP32 high precision copy if original weight is FP16. This method is provided to perform automatic mixed precision training for optimizers that do not support it themselves. ...
[ "def", "create_state_multi_precision", "(", "self", ",", "index", ",", "weight", ")", ":", "weight_master_copy", "=", "None", "if", "self", ".", "multi_precision", "and", "weight", ".", "dtype", "==", "numpy", ".", "float16", ":", "weight_master_copy", "=", "w...
41.482759
0.002437
def line_oriented(cls, line_oriented_options, console): """Given Goal.Options and a Console, yields functions for writing to stdout and stderr, respectively. The passed options instance will generally be the `Goal.Options` of a `LineOriented` `Goal`. """ if type(line_oriented_options) != cls.Options: ...
[ "def", "line_oriented", "(", "cls", ",", "line_oriented_options", ",", "console", ")", ":", "if", "type", "(", "line_oriented_options", ")", "!=", "cls", ".", "Options", ":", "raise", "AssertionError", "(", "'Expected Options for `{}`, got: {}'", ".", "format", "(...
36.692308
0.015322
def stats(self, node_id=None, params=None): """ The Cluster Stats API allows to retrieve statistics from a cluster wide perspective. The API returns basic index metrics and information about the current nodes that form the cluster. `<http://www.elastic.co/guide/en/elasticsearch/r...
[ "def", "stats", "(", "self", ",", "node_id", "=", "None", ",", "params", "=", "None", ")", ":", "url", "=", "'/_cluster/stats'", "if", "node_id", ":", "url", "=", "_make_path", "(", "'_cluster/stats/nodes'", ",", "node_id", ")", "return", "self", ".", "t...
51.111111
0.002134
def remove(self, interval): """ Returns self after removing the interval and balancing. If interval is not present, raise ValueError. """ # since this is a list, called methods can set this to [1], # making it true done = [] return self.remove_interval_he...
[ "def", "remove", "(", "self", ",", "interval", ")", ":", "# since this is a list, called methods can set this to [1],", "# making it true", "done", "=", "[", "]", "return", "self", ".", "remove_interval_helper", "(", "interval", ",", "done", ",", "should_raise_error", ...
35.6
0.008219
def where(self, custom_restrictions=[], **restrictions): """ Analog to SQL "WHERE". Does not perform a query until `select` is called. Returns a repo object. Options selected through keyword arguments are assumed to use == unles the value is a list, tuple, or dictionary. List or ...
[ "def", "where", "(", "self", ",", "custom_restrictions", "=", "[", "]", ",", "*", "*", "restrictions", ")", ":", "# Generate the SQL pieces and the relevant values", "standard_names", ",", "standard_values", "=", "self", ".", "_standard_items", "(", "restrictions", ...
49.392857
0.001418
def convert(input_file_name, **kwargs): """Convert CSV file to HTML table""" delimiter = kwargs["delimiter"] or "," quotechar = kwargs["quotechar"] or "|" if six.PY2: delimiter = delimiter.encode("utf-8") quotechar = quotechar.encode("utf-8") # Read CSV and form a header and rows l...
[ "def", "convert", "(", "input_file_name", ",", "*", "*", "kwargs", ")", ":", "delimiter", "=", "kwargs", "[", "\"delimiter\"", "]", "or", "\",\"", "quotechar", "=", "kwargs", "[", "\"quotechar\"", "]", "or", "\"|\"", "if", "six", ".", "PY2", ":", "delimi...
33.30303
0.000884
def plot_one_month(x, y, xlabel=None, ylabel=None, title=None, ylim=None): """时间跨度为一月。 major tick = every days """ plt.close("all") fig = plt.figure(figsize=(20, 10)) ax = fig.add_subplot(111) ax.plot(x, y) days = DayLocator(range(365)) daysFmt = DateFormatter("%Y-%m-...
[ "def", "plot_one_month", "(", "x", ",", "y", ",", "xlabel", "=", "None", ",", "ylabel", "=", "None", ",", "title", "=", "None", ",", "ylim", "=", "None", ")", ":", "plt", ".", "close", "(", "\"all\"", ")", "fig", "=", "plt", ".", "figure", "(", ...
21.227273
0.018424
def abort(http_status_code, exc=None, **kwargs): """Raise a HTTPException for the given http_status_code. Attach any keyword arguments to the exception for later processing. From Flask-Restful. See NOTICE file for license information. """ try: sanic.exceptions.abort(http_status_code, exc) ...
[ "def", "abort", "(", "http_status_code", ",", "exc", "=", "None", ",", "*", "*", "kwargs", ")", ":", "try", ":", "sanic", ".", "exceptions", ".", "abort", "(", "http_status_code", ",", "exc", ")", "except", "sanic", ".", "exceptions", ".", "SanicExceptio...
35.333333
0.002299
def enable_glut(self, app=None): """ Enable event loop integration with GLUT. Parameters ---------- app : ignored Ignored, it's only a placeholder to keep the call signature of all gui activation methods consistent, which simplifies the logic of supp...
[ "def", "enable_glut", "(", "self", ",", "app", "=", "None", ")", ":", "import", "OpenGL", ".", "GLUT", "as", "glut", "# @UnresolvedImport", "from", "pydev_ipython", ".", "inputhookglut", "import", "glut_display_mode", ",", "glut_close", ",", "glut_display", ",",...
39.96
0.002443
def isns_isns_vrf_isns_discovery_domain_isns_discovery_domain_name(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") isns = ET.SubElement(config, "isns", xmlns="urn:brocade.com:mgmt:brocade-isns") isns_vrf = ET.SubElement(isns, "isns-vrf") isns_vrf...
[ "def", "isns_isns_vrf_isns_discovery_domain_isns_discovery_domain_name", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "isns", "=", "ET", ".", "SubElement", "(", "config", ",", "\"isns\"", ",", "xm...
56.785714
0.008663
def from_computed_structure_entry(entry, miller_index, label=None, adsorbates=None, clean_entry=None, **kwargs): """ Returns SlabEntry from a ComputedStructureEntry """ return SlabEntry(entry.structure, entry.energy, miller_index, label=label, ...
[ "def", "from_computed_structure_entry", "(", "entry", ",", "miller_index", ",", "label", "=", "None", ",", "adsorbates", "=", "None", ",", "clean_entry", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "SlabEntry", "(", "entry", ".", "structure", ...
55.714286
0.015152
def handle_json_wrapper_GET(self, handler, parsed_params): """Call handler and output the return value in JSON.""" schedule = self.server.schedule result = handler(parsed_params) content = ResultEncoder().encode(result) self.send_response(200) self.send_header('Content-Type', 'text/plain') s...
[ "def", "handle_json_wrapper_GET", "(", "self", ",", "handler", ",", "parsed_params", ")", ":", "schedule", "=", "self", ".", "server", ".", "schedule", "result", "=", "handler", "(", "parsed_params", ")", "content", "=", "ResultEncoder", "(", ")", ".", "enco...
41.6
0.002353
def draw_box(cb, x0, y0, w, h, fg=colors.default_fg, bg=colors.default_bg, h_seps=[], v_seps=[]): """ Draws a box in the given terminal. :type cb: cursebox.CurseBox """ w -= 1 h -= 1 corners = [(x0, y0), (x0 + w, y0), (x0, y0 + h), (x0 + w, y0 + h)] fg = fg() bg = bg() for i, c...
[ "def", "draw_box", "(", "cb", ",", "x0", ",", "y0", ",", "w", ",", "h", ",", "fg", "=", "colors", ".", "default_fg", ",", "bg", "=", "colors", ".", "default_bg", ",", "h_seps", "=", "[", "]", ",", "v_seps", "=", "[", "]", ")", ":", "w", "-=",...
31.034483
0.002155
def _add_parser_arguments_git(self, subparsers): """Create a sub-parsers for git subcommands. """ subparsers.add_parser( "git-clone", help="Clone all defined data repositories if they dont exist.") subparsers.add_parser( "git-push", help="...
[ "def", "_add_parser_arguments_git", "(", "self", ",", "subparsers", ")", ":", "subparsers", ".", "add_parser", "(", "\"git-clone\"", ",", "help", "=", "\"Clone all defined data repositories if they dont exist.\"", ")", "subparsers", ".", "add_parser", "(", "\"git-push\"",...
31.107143
0.002227
def parse(self, fd): """very simple parser - but why would we want it to be complex?""" def resolve_args(args): # FIXME break this out, it's in common with the templating stuff elsewhere root = self.sections[0] val_dict = dict(('<' + t + '>', u) for (t, u) in root.ge...
[ "def", "parse", "(", "self", ",", "fd", ")", ":", "def", "resolve_args", "(", "args", ")", ":", "# FIXME break this out, it's in common with the templating stuff elsewhere", "root", "=", "self", ".", "sections", "[", "0", "]", "val_dict", "=", "dict", "(", "(", ...
40.49635
0.001935
def flair(self, name, text, css_class): """Sets flair for `user` in this subreddit (POST). Calls :meth:`narwal.Reddit.flairlist`. :param name: name of the user :param text: flair text to assign :param css_class: CSS class to assign to flair text """ return self....
[ "def", "flair", "(", "self", ",", "name", ",", "text", ",", "css_class", ")", ":", "return", "self", ".", "_reddit", ".", "flair", "(", "self", ".", "display_name", ",", "name", ",", "text", ",", "css_class", ")" ]
46
0.010667
def forget(self, key): """ Remove an item from the cache. :param key: The cache key :type key: str :rtype: bool """ return bool(self._redis.delete(self._prefix + key))
[ "def", "forget", "(", "self", ",", "key", ")", ":", "return", "bool", "(", "self", ".", "_redis", ".", "delete", "(", "self", ".", "_prefix", "+", "key", ")", ")" ]
21.6
0.008889
def fit(self, X=None, u=None, s = None): """Fit X into an embedded space. Inputs ---------- X : array, shape (n_samples, n_features) u,s,v : svd decomposition of X (optional) Assigns ---------- embedding : array-like, shape (n_samples, n_components) ...
[ "def", "fit", "(", "self", ",", "X", "=", "None", ",", "u", "=", "None", ",", "s", "=", "None", ")", ":", "X", "=", "X", ".", "copy", "(", ")", "if", "self", ".", "mode", "is", "'parallel'", ":", "Xall", "=", "X", ".", "copy", "(", ")", "...
37.4
0.008188
def set_dict_value(dictionary, keys, value): """ Set a value in a (nested) dictionary by defining a list of keys. .. note:: Side-effects This function does not make a copy of dictionary, but directly edits it. Parameters ---------- dictionary : dict keys : List[...
[ "def", "set_dict_value", "(", "dictionary", ",", "keys", ",", "value", ")", ":", "orig", "=", "dictionary", "for", "key", "in", "keys", "[", ":", "-", "1", "]", ":", "dictionary", "=", "dictionary", ".", "setdefault", "(", "key", ",", "{", "}", ")", ...
23.533333
0.001361
def norm_vector(vector): """! @brief Calculates norm of an input vector that is known as a vector length. @param[in] vector (list): The input vector whose length is calculated. @return (double) vector norm known as vector length. """ length = 0.0 for component ...
[ "def", "norm_vector", "(", "vector", ")", ":", "length", "=", "0.0", "for", "component", "in", "vector", ":", "length", "+=", "component", "*", "component", "length", "=", "length", "**", "0.5", "return", "length" ]
24.352941
0.016279
def inputtemplates(self): """Return all input templates as a list (of InputTemplate instances)""" l = [] for profile in self.profiles: l += profile.input return l
[ "def", "inputtemplates", "(", "self", ")", ":", "l", "=", "[", "]", "for", "profile", "in", "self", ".", "profiles", ":", "l", "+=", "profile", ".", "input", "return", "l" ]
33.5
0.019417
def xorg(name): ''' Set the keyboard layout for XOrg layout The keyboard layout to use ''' ret = {'name': name, 'changes': {}, 'result': None, 'comment': ''} if __salt__['keyboard.get_x']() == name: ret['result'] = True ret['comment'] = '...
[ "def", "xorg", "(", "name", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'changes'", ":", "{", "}", ",", "'result'", ":", "None", ",", "'comment'", ":", "''", "}", "if", "__salt__", "[", "'keyboard.get_x'", "]", "(", ")", "==", "name", ...
29.296296
0.001224
def walk(self, pattern=None, errors='strict'): """ D.walk() -> iterator over files and subdirs, recursively. The iterator yields path objects naming each child item of this directory and its descendants. This requires that D.isdir(). This performs a depth-first traversal of th...
[ "def", "walk", "(", "self", ",", "pattern", "=", "None", ",", "errors", "=", "'strict'", ")", ":", "if", "errors", "not", "in", "(", "'strict'", ",", "'warn'", ",", "'ignore'", ")", ":", "raise", "ValueError", "(", "\"invalid errors parameter\"", ")", "t...
35.326923
0.001059
def links(self, base_link, current_page) -> dict: """ Return JSON paginate links """ max_pages = self.max_pages - 1 if \ self.max_pages > 0 else self.max_pages base_link = '/%s' % (base_link.strip("/")) self_page = current_page prev = current_page - 1 if current...
[ "def", "links", "(", "self", ",", "base_link", ",", "current_page", ")", "->", "dict", ":", "max_pages", "=", "self", ".", "max_pages", "-", "1", "if", "self", ".", "max_pages", ">", "0", "else", "self", ".", "max_pages", "base_link", "=", "'/%s'", "%"...
46.571429
0.002004
def _implicit_solver(self): """Invertes and solves the matrix problem for diffusion matrix and temperature T. The method is called by the :func:`~climlab.process.implicit.ImplicitProcess._compute()` function of the :class:`~climlab.process.implicit.ImplicitProcess` class and ...
[ "def", "_implicit_solver", "(", "self", ")", ":", "#if self.update_diffusivity:", "# Time-stepping the diffusion is just inverting this matrix problem:", "newstate", "=", "{", "}", "for", "varname", ",", "value", "in", "self", ".", "state", ".", "items", "(", ")", ":"...
46.64
0.00126
def identify_denonavr_receivers(): """ Identify DenonAVR using SSDP and SCPD queries. Returns a list of dictionaries which includes all discovered Denon AVR devices with keys "host", "modelName", "friendlyName", "presentationURL". """ # Sending SSDP broadcast message to get devices devices ...
[ "def", "identify_denonavr_receivers", "(", ")", ":", "# Sending SSDP broadcast message to get devices", "devices", "=", "send_ssdp_broadcast", "(", ")", "# Check which responding device is a DenonAVR device and prepare output", "receivers", "=", "[", "]", "for", "device", "in", ...
30.952381
0.001493
def get_weather(test=False): """ Returns weather reports from the dataset. """ if _Constants._TEST or test: rows = _Constants._DATABASE.execute("SELECT data FROM weather LIMIT {hardware}".format( hardware=_Constants._HARDWARE)) data = [r[0] for r in rows] data = ...
[ "def", "get_weather", "(", "test", "=", "False", ")", ":", "if", "_Constants", ".", "_TEST", "or", "test", ":", "rows", "=", "_Constants", ".", "_DATABASE", ".", "execute", "(", "\"SELECT data FROM weather LIMIT {hardware}\"", ".", "format", "(", "hardware", "...
34.85
0.00838
def p_duration_duration_unit(self, p): 'duration : DURATION_UNIT' logger.debug('duration = 1 of duration unit %s', p[1]) p[0] = Duration.from_quantity_unit(1, p[1])
[ "def", "p_duration_duration_unit", "(", "self", ",", "p", ")", ":", "logger", ".", "debug", "(", "'duration = 1 of duration unit %s'", ",", "p", "[", "1", "]", ")", "p", "[", "0", "]", "=", "Duration", ".", "from_quantity_unit", "(", "1", ",", "p", "[", ...
46.25
0.010638
async def close_wallet(handle: int) -> None: """ Closes opened wallet and frees allocated resources. :param handle: wallet handle returned by indy_open_wallet. :return: Error code """ logger = logging.getLogger(__name__) logger.debug("close_wallet: >>> handle: %i", handle) if not hasa...
[ "async", "def", "close_wallet", "(", "handle", ":", "int", ")", "->", "None", ":", "logger", "=", "logging", ".", "getLogger", "(", "__name__", ")", "logger", ".", "debug", "(", "\"close_wallet: >>> handle: %i\"", ",", "handle", ")", "if", "not", "hasattr", ...
28.363636
0.00155
def build_not_found(cls, errors=None): """Utility method to build a HTTP 404 Resource Error response""" errors = [errors] if not isinstance(errors, list) else errors return cls(Status.NOT_FOUND, errors)
[ "def", "build_not_found", "(", "cls", ",", "errors", "=", "None", ")", ":", "errors", "=", "[", "errors", "]", "if", "not", "isinstance", "(", "errors", ",", "list", ")", "else", "errors", "return", "cls", "(", "Status", ".", "NOT_FOUND", ",", "errors"...
55.75
0.00885
def term_from_uri(uri): """Removes prepended URI information from terms.""" if uri is None: return None # This insures that if we get a Literal with an integer value (as we # do for modification positions), it will get converted to a string, # not an integer. if isinstance(uri, rdflib.Li...
[ "def", "term_from_uri", "(", "uri", ")", ":", "if", "uri", "is", "None", ":", "return", "None", "# This insures that if we get a Literal with an integer value (as we", "# do for modification positions), it will get converted to a string,", "# not an integer.", "if", "isinstance", ...
42.266667
0.000771
def cumsum(self, axis=0, *args, **kwargs): """ Cumulative sum of non-NA/null values. When performing the cumulative summation, any non-NA/null values will be skipped. The resulting SparseArray will preserve the locations of NaN values, but the fill value will be `np.nan` regardl...
[ "def", "cumsum", "(", "self", ",", "axis", "=", "0", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "nv", ".", "validate_cumsum", "(", "args", ",", "kwargs", ")", "if", "axis", "is", "not", "None", "and", "axis", ">=", "self", ".", "ndim", ...
35.892857
0.001938
def children(self): """ Children matches. """ if self._children is None: self._children = Matches(None, self.input_string) return self._children
[ "def", "children", "(", "self", ")", ":", "if", "self", ".", "_children", "is", "None", ":", "self", ".", "_children", "=", "Matches", "(", "None", ",", "self", ".", "input_string", ")", "return", "self", ".", "_children" ]
27.142857
0.010204
def add_volume(self,colorchange=True,column=None,name='',str='{name}',**kwargs): """ Add 'volume' study to QuantFigure.studies Parameters: colorchange : bool If True then each volume bar will have a fill color depending on if 'base' had a positive or negative change compared to the previous value...
[ "def", "add_volume", "(", "self", ",", "colorchange", "=", "True", ",", "column", "=", "None", ",", "name", "=", "''", ",", "str", "=", "'{name}'", ",", "*", "*", "kwargs", ")", ":", "if", "not", "column", ":", "column", "=", "self", ".", "_d", "...
32.73913
0.055448
def create_command( principal, permissions, endpoint_plus_path, notify_email, notify_message ): """ Executor for `globus endpoint permission create` """ if not principal: raise click.UsageError("A security principal is required for this command") endpoint_id, path = endpoint_plus_path ...
[ "def", "create_command", "(", "principal", ",", "permissions", ",", "endpoint_plus_path", ",", "notify_email", ",", "notify_message", ")", ":", "if", "not", "principal", ":", "raise", "click", ".", "UsageError", "(", "\"A security principal is required for this command\...
30.477273
0.001445
def create(cls, term, *ranges): """Instantiate the indexed sum while applying simplification rules""" if not isinstance(term, Scalar): term = ScalarValue.create(term) return super().create(term, *ranges)
[ "def", "create", "(", "cls", ",", "term", ",", "*", "ranges", ")", ":", "if", "not", "isinstance", "(", "term", ",", "Scalar", ")", ":", "term", "=", "ScalarValue", ".", "create", "(", "term", ")", "return", "super", "(", ")", ".", "create", "(", ...
47
0.008368
def get_weather(self, time, max_hour=6): """Get the current weather data from met.no.""" if self.data is None: return {} ordered_entries = [] for time_entry in self.data['product']['time']: valid_from = parse_datetime(time_entry['@from']) valid_to = p...
[ "def", "get_weather", "(", "self", ",", "time", ",", "max_hour", "=", "6", ")", ":", "if", "self", ".", "data", "is", "None", ":", "return", "{", "}", "ordered_entries", "=", "[", "]", "for", "time_entry", "in", "self", ".", "data", "[", "'product'",...
39.666667
0.001491
def get_user(request): """ Returns the user model instance associated with the given request session. If no user is retrieved an instance of `MojAnonymousUser` is returned. """ user = None try: user_id = request.session[SESSION_KEY] token = request.session[AUTH_TOKEN_SESSION_KEY]...
[ "def", "get_user", "(", "request", ")", ":", "user", "=", "None", "try", ":", "user_id", "=", "request", ".", "session", "[", "SESSION_KEY", "]", "token", "=", "request", ".", "session", "[", "AUTH_TOKEN_SESSION_KEY", "]", "user_data", "=", "request", ".",...
38.862069
0.000866
def promote(self): """ Mark object as alive, so it won't be collected during next run of the garbage collector. """ if self.expiry is not None: self.promoted = self.time_module.time() + self.expiry
[ "def", "promote", "(", "self", ")", ":", "if", "self", ".", "expiry", "is", "not", "None", ":", "self", ".", "promoted", "=", "self", ".", "time_module", ".", "time", "(", ")", "+", "self", ".", "expiry" ]
39.333333
0.008299
def delete_database(self, server_name, name): ''' Deletes an Azure SQL Database. server_name: Name of the server where the database is located. name: Name of the database to delete. ''' return self._perform_delete(self._get_databases_path(server_n...
[ "def", "delete_database", "(", "self", ",", "server_name", ",", "name", ")", ":", "return", "self", ".", "_perform_delete", "(", "self", ".", "_get_databases_path", "(", "server_name", ",", "name", ")", ")" ]
32.2
0.009063
def add_xtalographic_info(data_api, struct_inflator): """ Add the crystallographic data to the structure. :param data_api the interface to the decoded data :param struct_inflator the interface to put the data into the client object""" if data_api.unit_cell == None and data_api.space_group is not None: ...
[ "def", "add_xtalographic_info", "(", "data_api", ",", "struct_inflator", ")", ":", "if", "data_api", ".", "unit_cell", "==", "None", "and", "data_api", ".", "space_group", "is", "not", "None", ":", "struct_inflator", ".", "set_xtal_info", "(", "data_api", ".", ...
60.125
0.008188
def tonnetz(y=None, sr=22050, chroma=None): '''Computes the tonal centroid features (tonnetz), following the method of [1]_. .. [1] Harte, C., Sandler, M., & Gasser, M. (2006). "Detecting Harmonic Change in Musical Audio." In Proceedings of the 1st ACM Workshop on Audio and Music Comp...
[ "def", "tonnetz", "(", "y", "=", "None", ",", "sr", "=", "22050", ",", "chroma", "=", "None", ")", ":", "if", "y", "is", "None", "and", "chroma", "is", "None", ":", "raise", "ParameterError", "(", "'Either the audio samples or the chromagram must be '", "'pa...
29.68
0.000652
def spharm_lm(l, m, theta, phi, normalization='4pi', kind='real', csphase=1, degrees=True): """ Compute the spherical harmonic function for a specific degree and order. Usage ----- ylm = spharm (l, m, theta, phi, [normalization, kind, csphase, degrees]) Returns ------- yl...
[ "def", "spharm_lm", "(", "l", ",", "m", ",", "theta", ",", "phi", ",", "normalization", "=", "'4pi'", ",", "kind", "=", "'real'", ",", "csphase", "=", "1", ",", "degrees", "=", "True", ")", ":", "if", "l", "<", "0", ":", "raise", "ValueError", "(...
37.732824
0.000591
def weighted_choice(seq, cdf): """ Select a random element from a sequence, given cumulative probabilities of selection. See ``compute_fitness_cdf`` function for obtaining cumulative probabilities. seq: sequence to select from cdf: sequence with 1 cumulative probability value in [0, 1] f...
[ "def", "weighted_choice", "(", "seq", ",", "cdf", ")", ":", "assert", "len", "(", "seq", ")", "==", "len", "(", "cdf", ")", "rand", "=", "random", ".", "random", "(", ")", "for", "i", ",", "e", "in", "enumerate", "(", "seq", ")", ":", "cp", "="...
28.75
0.015152
def _union_in_blocks(contours, block_size): """ Generator which yields a valid shape for each block_size multiple of input contours. This merges together the contours for each block before yielding them. """ n_contours = len(contours) for i in range(0, n_contours, block_size): j = m...
[ "def", "_union_in_blocks", "(", "contours", ",", "block_size", ")", ":", "n_contours", "=", "len", "(", "contours", ")", "for", "i", "in", "range", "(", "0", ",", "n_contours", ",", "block_size", ")", ":", "j", "=", "min", "(", "i", "+", "block_size", ...
29.818182
0.001477
def parse_date_range(date, alt_end_date=None): """ Parse input `date` string in free-text format for four-digit long groups. Args: date (str): Input containing years. Returns: tuple: ``(from, to)`` as four-digit strings. """ NOT_ENDED = "9999" all_years = re.findall(r"\d{4}...
[ "def", "parse_date_range", "(", "date", ",", "alt_end_date", "=", "None", ")", ":", "NOT_ENDED", "=", "\"9999\"", "all_years", "=", "re", ".", "findall", "(", "r\"\\d{4}\"", ",", "date", ")", "if", "alt_end_date", ":", "NOT_ENDED", "=", "alt_end_date", "if",...
22.869565
0.001825
def sync(self): """Retrieve areas from ElkM1""" self.elk.send(cs_encode()) self.get_descriptions(TextDescriptions.OUTPUT.value)
[ "def", "sync", "(", "self", ")", ":", "self", ".", "elk", ".", "send", "(", "cs_encode", "(", ")", ")", "self", ".", "get_descriptions", "(", "TextDescriptions", ".", "OUTPUT", ".", "value", ")" ]
37
0.013245
def random_split(self, weights): """ Random split imageframes according to weights :param weights: weights for each ImageFrame :return: """ jvalues = self.image_frame.random_split(weights) return [ImageFrame(jvalue) for jvalue in jvalues]
[ "def", "random_split", "(", "self", ",", "weights", ")", ":", "jvalues", "=", "self", ".", "image_frame", ".", "random_split", "(", "weights", ")", "return", "[", "ImageFrame", "(", "jvalue", ")", "for", "jvalue", "in", "jvalues", "]" ]
36.125
0.013514
def main(): """Entry point for the application script""" if len(sys.argv) >= 2: cmd = sys.argv[1] if cmd == "help": print_usage() else: if cmd == "mensa": print_menu("Mensa") elif cmd == "bistro": print_menu("Bistro") ...
[ "def", "main", "(", ")", ":", "if", "len", "(", "sys", ".", "argv", ")", ">=", "2", ":", "cmd", "=", "sys", ".", "argv", "[", "1", "]", "if", "cmd", "==", "\"help\"", ":", "print_usage", "(", ")", "else", ":", "if", "cmd", "==", "\"mensa\"", ...
31.481481
0.001142
def append(self, record): """ Adds the passed +record+ to satisfy the query. Only intended to be used in conjunction with associations (i.e. do not use if self.record is None). Intended use case (DO THIS): post.comments.append(comment) NOT THIS: Query(...
[ "def", "append", "(", "self", ",", "record", ")", ":", "if", "self", ".", "record", ":", "self", ".", "_validate_record", "(", "record", ")", "if", "self", ".", "join_args", ":", "# As always, the related record is created when the primary", "# record is saved", "...
46.36
0.000845
def join_wrapped_lines(lines): """ Join one or multiple lines that wrapped. Returns the reconstructed line. Takes into account proper spacing between the lines (see STRIP_SPACE_CHARS). """ if len(lines) == 1: return lines[0] joined = lines[0] for line in lines[1:]: if jo...
[ "def", "join_wrapped_lines", "(", "lines", ")", ":", "if", "len", "(", "lines", ")", "==", "1", ":", "return", "lines", "[", "0", "]", "joined", "=", "lines", "[", "0", "]", "for", "line", "in", "lines", "[", "1", ":", "]", ":", "if", "joined", ...
25.388889
0.00211
def sphrec(r, colat, lon): """ Convert from spherical coordinates to rectangular coordinates. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/sphrec_c.html :param r: Distance of a point from the origin. :type r: float :param colat: Angle of the point from the positive Z-axis. :type...
[ "def", "sphrec", "(", "r", ",", "colat", ",", "lon", ")", ":", "r", "=", "ctypes", ".", "c_double", "(", "r", ")", "colat", "=", "ctypes", ".", "c_double", "(", "colat", ")", "lon", "=", "ctypes", ".", "c_double", "(", "lon", ")", "rectan", "=", ...
34.142857
0.001357
def uniform_binned(self, name=None): """ Return a new histogram with constant width bins along all axes by using the bin indices as the bin edges of the new histogram. """ if self.GetDimension() == 1: new_hist = Hist( self.GetNbinsX(), 0, self.GetNbins...
[ "def", "uniform_binned", "(", "self", ",", "name", "=", "None", ")", ":", "if", "self", ".", "GetDimension", "(", ")", "==", "1", ":", "new_hist", "=", "Hist", "(", "self", ".", "GetNbinsX", "(", ")", ",", "0", ",", "self", ".", "GetNbinsX", "(", ...
40.851852
0.001771
def cluster_two_diamonds(): "Start with wrong number of clusters." start_centers = [[0.8, 0.2]] template_clustering(start_centers, FCPS_SAMPLES.SAMPLE_TWO_DIAMONDS, criterion = splitting_type.BAYESIAN_INFORMATION_CRITERION) template_clustering(start_centers, FCPS_SAMPLES.SAMPLE_TWO_DIAMONDS, criteri...
[ "def", "cluster_two_diamonds", "(", ")", ":", "start_centers", "=", "[", "[", "0.8", ",", "0.2", "]", "]", "template_clustering", "(", "start_centers", ",", "FCPS_SAMPLES", ".", "SAMPLE_TWO_DIAMONDS", ",", "criterion", "=", "splitting_type", ".", "BAYESIAN_INFORMA...
74.6
0.018568
def principal_axis_system(self): """ Returns a chemical shielding tensor aligned to the principle axis system so that only the 3 diagnol components are non-zero """ return ChemicalShielding(np.diag(np.sort(np.linalg.eigvals(self))))
[ "def", "principal_axis_system", "(", "self", ")", ":", "return", "ChemicalShielding", "(", "np", ".", "diag", "(", "np", ".", "sort", "(", "np", ".", "linalg", ".", "eigvals", "(", "self", ")", ")", ")", ")" ]
44.5
0.011029
def doVerify(self): """Process the form submission, initating OpenID verification. """ # First, make sure that the user entered something openid_url = self.query.get('openid_identifier') if not openid_url: self.render( 'Enter an OpenID Identifier to v...
[ "def", "doVerify", "(", "self", ")", ":", "# First, make sure that the user entered something", "openid_url", "=", "self", ".", "query", ".", "get", "(", "'openid_identifier'", ")", "if", "not", "openid_url", ":", "self", ".", "render", "(", "'Enter an OpenID Identi...
41.083333
0.000792
def setCheckedRecords( self, records ): """ Sets the checked off records to the list of inputed records. :param records | [<orb.Table>, ..] """ QApplication.sendPostedEvents(self, -1) indexes = [] for i in range(self.count()): ...
[ "def", "setCheckedRecords", "(", "self", ",", "records", ")", ":", "QApplication", ".", "sendPostedEvents", "(", "self", ",", "-", "1", ")", "indexes", "=", "[", "]", "for", "i", "in", "range", "(", "self", ".", "count", "(", ")", ")", ":", "record",...
31.666667
0.014315
def reset(self): """ Drops index table. """ query = """ DROP TABLE identifier_index; """ self.backend.library.database.connection.execute(query)
[ "def", "reset", "(", "self", ")", ":", "query", "=", "\"\"\"\n DROP TABLE identifier_index;\n \"\"\"", "self", ".", "backend", ".", "library", ".", "database", ".", "connection", ".", "execute", "(", "query", ")" ]
30.5
0.010638
def _parse_samples_header(self, io_bytes): """ _parse_samples_header: binary data in XBee IO data format -> (int, [int ...], [int ...], int, int) _parse_samples_header will read the first three bytes of the binary data given and will return the number of samples ...
[ "def", "_parse_samples_header", "(", "self", ",", "io_bytes", ")", ":", "header_size", "=", "3", "# number of samples (always 1?) is the first byte", "sample_count", "=", "byteToInt", "(", "io_bytes", "[", "0", "]", ")", "# part of byte 1 and byte 2 are the DIO mask ( 9 bit...
33.205128
0.0015
def portal_touch_up(self, touch): """Try to create a portal between the spots the user chose.""" try: # If the touch ended upon a spot, and there isn't # already a portal between the origin and this # destination, create one. destspot = next(self.spots_at(...
[ "def", "portal_touch_up", "(", "self", ",", "touch", ")", ":", "try", ":", "# If the touch ended upon a spot, and there isn't", "# already a portal between the origin and this", "# destination, create one.", "destspot", "=", "next", "(", "self", ".", "spots_at", "(", "*", ...
38.744186
0.001171
def tree(height=3, is_perfect=False): """Generate a random binary tree and return its root node. :param height: Height of the tree (default: 3, range: 0 - 9 inclusive). :type height: int :param is_perfect: If set to True (default: False), a perfect binary tree with all levels filled is returned...
[ "def", "tree", "(", "height", "=", "3", ",", "is_perfect", "=", "False", ")", ":", "_validate_tree_height", "(", "height", ")", "values", "=", "_generate_random_node_values", "(", "height", ")", "if", "is_perfect", ":", "return", "build", "(", "values", ")",...
26.319444
0.000509
def set_mode(path, mode): ''' Set the mode of a file This just calls get_mode, which returns None because we don't use mode on Windows Args: path: The path to the file or directory mode: The mode (not used) Returns: None CLI Example: .. code-block:: bash ...
[ "def", "set_mode", "(", "path", ",", "mode", ")", ":", "func_name", "=", "'{0}.set_mode'", ".", "format", "(", "__virtualname__", ")", "if", "__opts__", ".", "get", "(", "'fun'", ",", "''", ")", "==", "func_name", ":", "log", ".", "info", "(", "'The fu...
25.481481
0.001401
def query_status(self): '''Query the hub for the status of this command''' try: data = self.api_iface._api_get(self.link) self._update_details(data) except APIError as e: print("API error: ") for key,value in e.data.iteritems: print...
[ "def", "query_status", "(", "self", ")", ":", "try", ":", "data", "=", "self", ".", "api_iface", ".", "_api_get", "(", "self", ".", "link", ")", "self", ".", "_update_details", "(", "data", ")", "except", "APIError", "as", "e", ":", "print", "(", "\"...
38
0.008571
def setup_app_scope(name, scope): """activate plugins accordingly to config""" # load plugins plugins = [] for plugin_name, active in get('settings').get('rw.plugins', {}).items(): plugin = __import__(plugin_name) plugin_path = plugin_name.split('.')[1:] + ['plugin'] for sub in ...
[ "def", "setup_app_scope", "(", "name", ",", "scope", ")", ":", "# load plugins", "plugins", "=", "[", "]", "for", "plugin_name", ",", "active", "in", "get", "(", "'settings'", ")", ".", "get", "(", "'rw.plugins'", ",", "{", "}", ")", ".", "items", "(",...
33.571429
0.00207
def _dataset_info(dataset): """Return information about dataset as a dict.""" info = {} info["uri"] = dataset.uri info["uuid"] = dataset.uuid # Computer and human readable size of dataset. tot_size = sum([dataset.item_properties(i)["size_in_bytes"] for i in dataset.identifi...
[ "def", "_dataset_info", "(", "dataset", ")", ":", "info", "=", "{", "}", "info", "[", "\"uri\"", "]", "=", "dataset", ".", "uri", "info", "[", "\"uuid\"", "]", "=", "dataset", ".", "uuid", "# Computer and human readable size of dataset.", "tot_size", "=", "s...
30
0.001404
def write_membership(self,filename): """ Write a catalog file of the likelihood region including membership properties. Parameters: ----------- filename : output filename Returns: -------- None """ # Column names n...
[ "def", "write_membership", "(", "self", ",", "filename", ")", ":", "# Column names", "name_objid", "=", "self", ".", "config", "[", "'catalog'", "]", "[", "'objid_field'", "]", "name_mag_1", "=", "self", ".", "config", "[", "'catalog'", "]", "[", "'mag_1_fie...
39.116667
0.013716
def Preserve(self): """This tells the XML Reader to preserve the current node. The caller must also use xmlTextReaderCurrentDoc() to keep an handle on the resulting document once parsing has finished """ ret = libxml2mod.xmlTextReaderPreserve(self._o) if ret is None:raise tr...
[ "def", "Preserve", "(", "self", ")", ":", "ret", "=", "libxml2mod", ".", "xmlTextReaderPreserve", "(", "self", ".", "_o", ")", "if", "ret", "is", "None", ":", "raise", "treeError", "(", "'xmlTextReaderPreserve() failed'", ")", "__tmp", "=", "xmlNode", "(", ...
51.125
0.009615
def cmd(send, msg, _): """Generates a meaning for the specified acronym. Syntax: {command} <acronym> """ if not msg: send("What acronym?") return words = get_list() letters = [c for c in msg.lower() if c in string.ascii_lowercase] output = " ".join([choice(words[c]) for c i...
[ "def", "cmd", "(", "send", ",", "msg", ",", "_", ")", ":", "if", "not", "msg", ":", "send", "(", "\"What acronym?\"", ")", "return", "words", "=", "get_list", "(", ")", "letters", "=", "[", "c", "for", "c", "in", "msg", ".", "lower", "(", ")", ...
27.125
0.002227
def get_tag_context(name, state): """ Given a tag name, return its associated value as defined in the current context stack. """ new_contexts = 0 ctm = None while True: try: ctx_key, name = name.split('.', 1) ctm = state.context.get(ctx_key) except Val...
[ "def", "get_tag_context", "(", "name", ",", "state", ")", ":", "new_contexts", "=", "0", "ctm", "=", "None", "while", "True", ":", "try", ":", "ctx_key", ",", "name", "=", "name", ".", "split", "(", "'.'", ",", "1", ")", "ctm", "=", "state", ".", ...
23.090909
0.00189
def make_file(self, host): """创建文件""" url = self.file_url(host) body = ','.join([status['ctx'] for status in self.blockStatus]) self.upload_progress_recorder.delete_upload_record(self.file_name, self.key) return self.post(url, body)
[ "def", "make_file", "(", "self", ",", "host", ")", ":", "url", "=", "self", ".", "file_url", "(", "host", ")", "body", "=", "','", ".", "join", "(", "[", "status", "[", "'ctx'", "]", "for", "status", "in", "self", ".", "blockStatus", "]", ")", "s...
44.5
0.011029
def read_output_config (self): """Read configuration options in section "output".""" section = "output" from ..logger import LoggerClasses for c in LoggerClasses: key = c.LoggerName if self.has_section(key): for opt in self.options(key): ...
[ "def", "read_output_config", "(", "self", ")", ":", "section", "=", "\"output\"", "from", ".", ".", "logger", "import", "LoggerClasses", "for", "c", "in", "LoggerClasses", ":", "key", "=", "c", ".", "LoggerName", "if", "self", ".", "has_section", "(", "key...
48.292683
0.001485
def iter(self, offset=0, count=None, pagesize=None, **kwargs): """Iterates over the collection. This method is equivalent to the :meth:`list` method, but it returns an iterator and can load a certain number of entities at a time from the server. :param offset: The index of the ...
[ "def", "iter", "(", "self", ",", "offset", "=", "0", ",", "count", "=", "None", ",", "pagesize", "=", "None", ",", "*", "*", "kwargs", ")", ":", "assert", "pagesize", "is", "None", "or", "pagesize", ">", "0", "if", "count", "is", "None", ":", "co...
38.921569
0.001966
def get_field_description(f): """Get the type description of a GRPC Message field.""" type_name = get_field_type(f) if type_name == 'MESSAGE' and \ {sf.name for sf in f.message_type.fields} == {'key', 'value'}: return 'map<string, string>' elif type_name == 'MESSAGE': return ...
[ "def", "get_field_description", "(", "f", ")", ":", "type_name", "=", "get_field_type", "(", "f", ")", "if", "type_name", "==", "'MESSAGE'", "and", "{", "sf", ".", "name", "for", "sf", "in", "f", ".", "message_type", ".", "fields", "}", "==", "{", "'ke...
36.916667
0.002203
def save(self): """ Saves the settings contents """ content = self.dumps() fileutils.save_text_to_file(content, self.file_path)
[ "def", "save", "(", "self", ")", ":", "content", "=", "self", ".", "dumps", "(", ")", "fileutils", ".", "save_text_to_file", "(", "content", ",", "self", ".", "file_path", ")" ]
37
0.013245
def users_request_create(self, data, **kwargs): "https://developer.zendesk.com/rest_api/docs/core/users#request-user-create" api_path = "/api/v2/users/request_create.json" return self.call(api_path, method="POST", data=data, **kwargs)
[ "def", "users_request_create", "(", "self", ",", "data", ",", "*", "*", "kwargs", ")", ":", "api_path", "=", "\"/api/v2/users/request_create.json\"", "return", "self", ".", "call", "(", "api_path", ",", "method", "=", "\"POST\"", ",", "data", "=", "data", ",...
63.75
0.011628
def _get_service_account_info(self): """Retrieve json dict from service account file.""" with open(self.service_account_file, 'r') as f: info = json.load(f) self.service_account_email = info.get('client_email') if not self.service_account_email: raise GCECloudExc...
[ "def", "_get_service_account_info", "(", "self", ")", ":", "with", "open", "(", "self", ".", "service_account_file", ",", "'r'", ")", "as", "f", ":", "info", "=", "json", ".", "load", "(", "f", ")", "self", ".", "service_account_email", "=", "info", ".",...
43.45
0.002252
def next(self): """ Next CapitainsCtsPassage (Interactive CapitainsCtsPassage) """ if self.nextId is not None: return super(CapitainsCtsPassage, self).getTextualNode(subreference=self.nextId)
[ "def", "next", "(", "self", ")", ":", "if", "self", ".", "nextId", "is", "not", "None", ":", "return", "super", "(", "CapitainsCtsPassage", ",", "self", ")", ".", "getTextualNode", "(", "subreference", "=", "self", ".", "nextId", ")" ]
44.6
0.013216
def plot_vxz(self, colorbar=True, cb_orientation='vertical', cb_label=None, ax=None, show=True, fname=None, **kwargs): """ Plot the Vxz component of the tensor. Usage ----- x.plot_vxz([tick_interval, xlabel, ylabel, ax, colorbar, cb_orientati...
[ "def", "plot_vxz", "(", "self", ",", "colorbar", "=", "True", ",", "cb_orientation", "=", "'vertical'", ",", "cb_label", "=", "None", ",", "ax", "=", "None", ",", "show", "=", "True", ",", "fname", "=", "None", ",", "*", "*", "kwargs", ")", ":", "i...
40.641509
0.00136
def _getextra(self): ''' Get the extra data of this struct. ''' current = self while hasattr(current, '_sub'): current = current._sub return getattr(current, '_extra', None)
[ "def", "_getextra", "(", "self", ")", ":", "current", "=", "self", "while", "hasattr", "(", "current", ",", "'_sub'", ")", ":", "current", "=", "current", ".", "_sub", "return", "getattr", "(", "current", ",", "'_extra'", ",", "None", ")" ]
28.25
0.008584
def _lemmatize_token(self, token, best_guess=True, return_frequencies=False): """Lemmatize a single token. If best_guess is true, then take the most frequent lemma when a form has multiple possible lemmatizations. If the form is not found, just return it. If best_guess is false, then always return the full ...
[ "def", "_lemmatize_token", "(", "self", ",", "token", ",", "best_guess", "=", "True", ",", "return_frequencies", "=", "False", ")", ":", "lemmas", "=", "self", ".", "lemma_dict", ".", "get", "(", "token", ".", "lower", "(", ")", ",", "None", ")", "if",...
36.2
0.033369
def render(self, context, instance, placeholder): ''' Allows this plugin to use templates designed for a list of locations. ''' context = super(LocationPlugin,self).render(context,instance,placeholder) context['location_list'] = [instance.location,] return context
[ "def", "render", "(", "self", ",", "context", ",", "instance", ",", "placeholder", ")", ":", "context", "=", "super", "(", "LocationPlugin", ",", "self", ")", ".", "render", "(", "context", ",", "instance", ",", "placeholder", ")", "context", "[", "'loca...
59.2
0.026667
def tune_pair(self, pair): """Tune a pair of images.""" self._save_bm_state() self.pair = pair self.update_disparity_map()
[ "def", "tune_pair", "(", "self", ",", "pair", ")", ":", "self", ".", "_save_bm_state", "(", ")", "self", ".", "pair", "=", "pair", "self", ".", "update_disparity_map", "(", ")" ]
30
0.012987
def start(self, n): """Start n engines by profile or profile_dir.""" self.n = n return super(MPIEngineSetLauncher, self).start(n)
[ "def", "start", "(", "self", ",", "n", ")", ":", "self", ".", "n", "=", "n", "return", "super", "(", "MPIEngineSetLauncher", ",", "self", ")", ".", "start", "(", "n", ")" ]
37.5
0.013072
def get_cache_key(user_or_username, size, prefix): """ Returns a cache key consisten of a username and image size. """ if isinstance(user_or_username, get_user_model()): user_or_username = get_username(user_or_username) key = six.u('%s_%s_%s') % (prefix, user_or_username, size) return si...
[ "def", "get_cache_key", "(", "user_or_username", ",", "size", ",", "prefix", ")", ":", "if", "isinstance", "(", "user_or_username", ",", "get_user_model", "(", ")", ")", ":", "user_or_username", "=", "get_username", "(", "user_or_username", ")", "key", "=", "s...
46.555556
0.002342
async def send_help(self, *args): """send_help(entity=<bot>) |coro| Shows the help command for the specified entity if given. The entity can be a command or a cog. If no entity is given, then it'll show help for the entire bot. If the entity is a string, then ...
[ "async", "def", "send_help", "(", "self", ",", "*", "args", ")", ":", "from", ".", "core", "import", "Group", ",", "Command", "bot", "=", "self", ".", "bot", "cmd", "=", "bot", ".", "help_command", "if", "cmd", "is", "None", ":", "return", "None", ...
29.102941
0.001466
async def set_digital_latch(self, command): """ This method sets the a digital latch for a given digital pin, the threshold type, and latching threshold. :param command:{"method": "set_digital_latch", "params": [PIN, THRESHOLD (0 or 1)]} :returns:{"method": digital_latch_data_reply", "pa...
[ "async", "def", "set_digital_latch", "(", "self", ",", "command", ")", ":", "pin", "=", "int", "(", "command", "[", "0", "]", ")", "threshold_value", "=", "int", "(", "command", "[", "1", "]", ")", "await", "self", ".", "core", ".", "set_digital_latch"...
60
0.010949
def command_repo_list(self): """Repositories list """ if len(self.args) == 1 and self.args[0] == "repo-list": RepoList().repos() else: usage("")
[ "def", "command_repo_list", "(", "self", ")", ":", "if", "len", "(", "self", ".", "args", ")", "==", "1", "and", "self", ".", "args", "[", "0", "]", "==", "\"repo-list\"", ":", "RepoList", "(", ")", ".", "repos", "(", ")", "else", ":", "usage", "...
27.714286
0.01
def redo(self, channel, image): """Add an entry with image modification info.""" chname = channel.name if image is None: # shouldn't happen, but let's play it safe return imname = image.get('name', 'none') iminfo = channel.get_image_info(imname) t...
[ "def", "redo", "(", "self", ",", "channel", ",", "image", ")", ":", "chname", "=", "channel", ".", "name", "if", "image", "is", "None", ":", "# shouldn't happen, but let's play it safe", "return", "imname", "=", "image", ".", "get", "(", "'name'", ",", "'n...
39.777778
0.001818