text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def media_artist(self): """Artist of current playing media (Music track only).""" try: artists = self.session['NowPlayingItem']['Artists'] if len(artists) > 1: return artists[0] else: return artists except KeyError: ...
[ "def", "media_artist", "(", "self", ")", ":", "try", ":", "artists", "=", "self", ".", "session", "[", "'NowPlayingItem'", "]", "[", "'Artists'", "]", "if", "len", "(", "artists", ")", ">", "1", ":", "return", "artists", "[", "0", "]", "else", ":", ...
32.2
14.9
def add_device(self, name, protocol, model=None, **parameters): """Add a new device. :return: a :class:`Device` or :class:`DeviceGroup` instance. """ device = Device(self.lib.tdAddDevice(), lib=self.lib) try: device.name = name device.protocol = protocol ...
[ "def", "add_device", "(", "self", ",", "name", ",", "protocol", ",", "model", "=", "None", ",", "*", "*", "parameters", ")", ":", "device", "=", "Device", "(", "self", ".", "lib", ".", "tdAddDevice", "(", ")", ",", "lib", "=", "self", ".", "lib", ...
33.321429
17.857143
def eval(expr, parser='pandas', engine=None, truediv=True, local_dict=None, global_dict=None, resolvers=(), level=0, target=None, inplace=False): """Evaluate a Python expression as a string using various backends. The following arithmetic operations are supported: ``+``, ``-``, ``*``, ``/...
[ "def", "eval", "(", "expr", ",", "parser", "=", "'pandas'", ",", "engine", "=", "None", ",", "truediv", "=", "True", ",", "local_dict", "=", "None", ",", "global_dict", "=", "None", ",", "resolvers", "=", "(", ")", ",", "level", "=", "0", ",", "tar...
41.255102
23.316327
def resolve_revision(self, dest, url, rev_options): """ Resolve a revision to a new RevOptions object with the SHA1 of the branch, tag, or ref if found. Args: rev_options: a RevOptions object. """ rev = rev_options.arg_rev sha, is_branch = self.get_revi...
[ "def", "resolve_revision", "(", "self", ",", "dest", ",", "url", ",", "rev_options", ")", ":", "rev", "=", "rev_options", ".", "arg_rev", "sha", ",", "is_branch", "=", "self", ".", "get_revision_sha", "(", "dest", ",", "rev", ")", "if", "sha", "is", "n...
32.210526
19.736842
def GetFileEntryByPathSpec(self, path_spec): """Retrieves a file entry for a path specification. Args: path_spec (PathSpec): a path specification. Returns: CPIOFileEntry: a file entry or None if not available. """ location = getattr(path_spec, 'location', None) if (location is Non...
[ "def", "GetFileEntryByPathSpec", "(", "self", ",", "path_spec", ")", ":", "location", "=", "getattr", "(", "path_spec", ",", "'location'", ",", "None", ")", "if", "(", "location", "is", "None", "or", "not", "location", ".", "startswith", "(", "self", ".", ...
29.892857
19.535714
def predict(x, P, F=1, Q=0, u=0, B=1, alpha=1.): """ Predict next state (prior) using the Kalman filter state propagation equations. Parameters ---------- x : numpy.array State estimate vector P : numpy.array Covariance matrix F : numpy.array() State Transitio...
[ "def", "predict", "(", "x", ",", "P", ",", "F", "=", "1", ",", "Q", "=", "0", ",", "u", "=", "0", ",", "B", "=", "1", ",", "alpha", "=", "1.", ")", ":", "if", "np", ".", "isscalar", "(", "F", ")", ":", "F", "=", "np", ".", "array", "(...
24.176471
22.647059
def ec2_fab(service, args): """ Run Fabric commands against EC2 instances """ instance_ids = args.instances instances = service.list(elb=args.elb, instance_ids=instance_ids) hosts = service.resolve_hosts(instances) fab.env.hosts = hosts fab.env.key_filename = settings.get('SSH', 'KEY_FI...
[ "def", "ec2_fab", "(", "service", ",", "args", ")", ":", "instance_ids", "=", "args", ".", "instances", "instances", "=", "service", ".", "list", "(", "elb", "=", "args", ".", "elb", ",", "instance_ids", "=", "instance_ids", ")", "hosts", "=", "service",...
33.586207
16
def unset_refresh_cookies(response): """ takes a flask response object, and configures it to unset (delete) the refresh token from the response cookies. if `jwt_csrf_in_cookies` (see :ref:`configuration options`) is `true`, this will also remove the refresh csrf double submit value from the response...
[ "def", "unset_refresh_cookies", "(", "response", ")", ":", "if", "not", "config", ".", "jwt_in_cookies", ":", "raise", "RuntimeWarning", "(", "\"unset_refresh_cookies() called without \"", "\"'JWT_TOKEN_LOCATION' configured to use cookies\"", ")", "response", ".", "set_cookie...
46.354839
18.225806
def parse_args(): """Parse the command line arguments.""" parser = argparse.ArgumentParser( description='Check kafka current status', ) parser.add_argument( "--cluster-type", "-t", dest='cluster_type', required=True, help='Type of cluster', default...
[ "def", "parse_args", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "'Check kafka current status'", ",", ")", "parser", ".", "add_argument", "(", "\"--cluster-type\"", ",", "\"-t\"", ",", "dest", "=", "'cluster_type'", ...
31.388889
20.763889
def get_par_contribution(self,parlist_dict=None,include_prior_results=False): """get a dataframe the prior and posterior uncertainty reduction as a result of some parameter becoming perfectly known Parameters ---------- parlist_dict : dict a nested dictionary-list of...
[ "def", "get_par_contribution", "(", "self", ",", "parlist_dict", "=", "None", ",", "include_prior_results", "=", "False", ")", ":", "self", ".", "log", "(", "\"calculating contribution from parameters\"", ")", "if", "parlist_dict", "is", "None", ":", "parlist_dict",...
43.725
21.4125
def save_object(self, obj): """ Save object to disk as JSON. Generally shouldn't be called directly. """ obj.pre_save(self.jurisdiction.jurisdiction_id) filename = '{0}_{1}.json'.format(obj._type, obj._id).replace('/', '-') self.info('save %s %s as %s',...
[ "def", "save_object", "(", "self", ",", "obj", ")", ":", "obj", ".", "pre_save", "(", "self", ".", "jurisdiction", ".", "jurisdiction_id", ")", "filename", "=", "'{0}_{1}.json'", ".", "format", "(", "obj", ".", "_type", ",", "obj", ".", "_id", ")", "."...
34.096774
22.225806
def render_mail_template(subject_template, body_template, context): """ Renders both the subject and body templates in the given context. Returns a tuple (subject, body) of the result. """ try: subject = strip_spaces(render_to_string(subject_template, context)) body = render_to_strin...
[ "def", "render_mail_template", "(", "subject_template", ",", "body_template", ",", "context", ")", ":", "try", ":", "subject", "=", "strip_spaces", "(", "render_to_string", "(", "subject_template", ",", "context", ")", ")", "body", "=", "render_to_string", "(", ...
32.166667
21.666667
def _class_type(klass, ancestors=None): """return a ClassDef node type to differ metaclass and exception from 'regular' classes """ # XXX we have to store ancestors in case we have an ancestor loop if klass._type is not None: return klass._type if _is_metaclass(klass): klass._typ...
[ "def", "_class_type", "(", "klass", ",", "ancestors", "=", "None", ")", ":", "# XXX we have to store ancestors in case we have an ancestor loop", "if", "klass", ".", "_type", "is", "not", "None", ":", "return", "klass", ".", "_type", "if", "_is_metaclass", "(", "k...
36.28125
11.375
def configure_environment(self, last_trade, benchmark, timezone): ''' Prepare benchmark loader and trading context ''' if last_trade.tzinfo is None: last_trade = pytz.utc.localize(last_trade) # Setup the trading calendar from market informations self.benchmark = benchmark ...
[ "def", "configure_environment", "(", "self", ",", "last_trade", ",", "benchmark", ",", "timezone", ")", ":", "if", "last_trade", ".", "tzinfo", "is", "None", ":", "last_trade", "=", "pytz", ".", "utc", ".", "localize", "(", "last_trade", ")", "# Setup the tr...
39.583333
16.916667
def xpathNextAncestorOrSelf(self, ctxt): """Traversal function for the "ancestor-or-self" direction he ancestor-or-self axis contains the context node and ancestors of the context node in reverse document order; thus the context node is the first node on the axis, and the...
[ "def", "xpathNextAncestorOrSelf", "(", "self", ",", "ctxt", ")", ":", "if", "ctxt", "is", "None", ":", "ctxt__o", "=", "None", "else", ":", "ctxt__o", "=", "ctxt", ".", "_o", "ret", "=", "libxml2mod", ".", "xmlXPathNextAncestorOrSelf", "(", "ctxt__o", ",",...
53.076923
15.307692
def GET_close_server(self) -> None: """Stop and close the *HydPy* server.""" def _close_server(): self.server.shutdown() self.server.server_close() shutter = threading.Thread(target=_close_server) shutter.deamon = True shutter.start()
[ "def", "GET_close_server", "(", "self", ")", "->", "None", ":", "def", "_close_server", "(", ")", ":", "self", ".", "server", ".", "shutdown", "(", ")", "self", ".", "server", ".", "server_close", "(", ")", "shutter", "=", "threading", ".", "Thread", "...
36.375
8.625
def train(self, cloud=None, batch=False, api_key=None, version=None, **kwargs): """ This is the basic training endpoint. Given an existing dataset this endpoint will train a model. Inputs api_key (optional) - String: Your API key, required only if the key has not been declared ...
[ "def", "train", "(", "self", ",", "cloud", "=", "None", ",", "batch", "=", "False", ",", "api_key", "=", "None", ",", "version", "=", "None", ",", "*", "*", "kwargs", ")", ":", "url_params", "=", "{", "\"batch\"", ":", "batch", ",", "\"api_key\"", ...
65.785714
39.357143
def equation_of_time(day): """Compute the equation of time for the given date. Uses formula described at https://en.wikipedia.org/wiki/Equation_of_time#Alternative_calculation :param day: The datetime.date to compute the equation of time for :returns: The angle, in radians, of the Equation of Time...
[ "def", "equation_of_time", "(", "day", ")", ":", "day_of_year", "=", "day", ".", "toordinal", "(", ")", "-", "date", "(", "day", ".", "year", ",", "1", ",", "1", ")", ".", "toordinal", "(", ")", "# pylint: disable=invalid-name", "#", "# Distance Earth move...
31.756098
25.707317
def fetch_samples(proj, selector_attribute=None, selector_include=None, selector_exclude=None): """ Collect samples of particular protocol(s). Protocols can't be both positively selected for and negatively selected against. That is, it makes no sense and is not allowed to specify both selector_incl...
[ "def", "fetch_samples", "(", "proj", ",", "selector_attribute", "=", "None", ",", "selector_include", "=", "None", ",", "selector_exclude", "=", "None", ")", ":", "if", "selector_attribute", "is", "None", "or", "(", "not", "selector_include", "and", "not", "se...
51.389831
27.186441
def CheckLibWithHeader(context, libs, header, language, call = None, autoadd = 1): # ToDo: accept path for library. Support system header files. """ Another (more sophisticated) test for a library. Checks, if library and header is available for language (may be 'C' or 'CXX'). ...
[ "def", "CheckLibWithHeader", "(", "context", ",", "libs", ",", "header", ",", "language", ",", "call", "=", "None", ",", "autoadd", "=", "1", ")", ":", "# ToDo: accept path for library. Support system header files.", "prog_prefix", ",", "dummy", "=", "createIncludes...
37.863636
19.045455
def sync_accounts(self, accounts_data, clear = False, password=None, cb = None): """ Load all of the accounts from the account section of the config into the database. :param accounts_data: :param password: :return: """ # Map common values into the accou...
[ "def", "sync_accounts", "(", "self", ",", "accounts_data", ",", "clear", "=", "False", ",", "password", "=", "None", ",", "cb", "=", "None", ")", ":", "# Map common values into the accounts records", "all_accounts", "=", "self", ".", "accounts", "kmap", "=", "...
26.804348
20.673913
def seqingroups(groups,seq): 'helper for contigsub. takes the list of lists returned by groupelts and an array to check.\ returns (groupindex,indexingroup,matchlen) of longest match or None if no match' if not (groups and seq): return None bestmatch=None,None,0 if any(len(g)<2 for g in groups): raise Val...
[ "def", "seqingroups", "(", "groups", ",", "seq", ")", ":", "if", "not", "(", "groups", "and", "seq", ")", ":", "return", "None", "bestmatch", "=", "None", ",", "None", ",", "0", "if", "any", "(", "len", "(", "g", ")", "<", "2", "for", "g", "in"...
50.7
22.9
def error(self, msg, *args, **kwargs) -> Task: # type: ignore """ Log msg with severity 'ERROR'. To pass exception information, use the keyword argument exc_info with a true value, e.g. await logger.error("Houston, we have a major problem", exc_info=1) """ retu...
[ "def", "error", "(", "self", ",", "msg", ",", "*", "args", ",", "*", "*", "kwargs", ")", "->", "Task", ":", "# type: ignore", "return", "self", ".", "_make_log_task", "(", "logging", ".", "ERROR", ",", "msg", ",", "args", ",", "*", "*", "kwargs", "...
36.9
21.9
def table_row(self, content): """Rendering a table row. Like ``<tr>``. :param content: content of current table row. """ contents = content.splitlines() if not contents: return '' clist = ['* ' + contents[0]] if len(contents) > 1: for c in...
[ "def", "table_row", "(", "self", ",", "content", ")", ":", "contents", "=", "content", ".", "splitlines", "(", ")", "if", "not", "contents", ":", "return", "''", "clist", "=", "[", "'* '", "+", "contents", "[", "0", "]", "]", "if", "len", "(", "con...
30.769231
9.615385
def list_related(self, request, pk=None, field_name=None): """Fetch related object(s), as if sideloaded (used to support link objects). This method gets mapped to `/<resource>/<pk>/<field_name>/` by DynamicRouter for all DynamicRelationField fields. Generally, this method probab...
[ "def", "list_related", "(", "self", ",", "request", ",", "pk", "=", "None", ",", "field_name", "=", "None", ")", ":", "# Explicitly disable support filtering. Applying filters to this", "# endpoint would require us to pass through sideload filters, which", "# can have unintended ...
43.416667
22.516667
async def close(self): """ Closes connection and resets pool """ if self._pool is not None and not isinstance(self.connection, aioredis.Redis): self._pool.close() await self._pool.wait_closed() self._pool = None
[ "async", "def", "close", "(", "self", ")", ":", "if", "self", ".", "_pool", "is", "not", "None", "and", "not", "isinstance", "(", "self", ".", "connection", ",", "aioredis", ".", "Redis", ")", ":", "self", ".", "_pool", ".", "close", "(", ")", "awa...
33.5
11.5
def safe_get(self, section, key): """ Attempt to get a configuration value from a certain section in a ``cfg`` object but returning None if not found. Avoids the need to be doing try/except {ConfigParser Exceptions} every time. """ try: #Use full parent functi...
[ "def", "safe_get", "(", "self", ",", "section", ",", "key", ")", ":", "try", ":", "#Use full parent function so we can replace it in the class", "# if desired", "return", "configparser", ".", "RawConfigParser", ".", "get", "(", "self", ",", "section", ",", "key", ...
42.692308
17.615385
def create_asset_class(self, item: AssetClass): """ Inserts the record """ session = self.open_session() session.add(item) session.commit()
[ "def", "create_asset_class", "(", "self", ",", "item", ":", "AssetClass", ")", ":", "session", "=", "self", ".", "open_session", "(", ")", "session", ".", "add", "(", "item", ")", "session", ".", "commit", "(", ")" ]
33.4
8.2
def create( self, name, description="", whitelisted_container_task_types=None, whitelisted_executable_task_types=None, ): """Create a task whitelist. Args: name (str): The name of the task whitelist. description (str, optional): A desc...
[ "def", "create", "(", "self", ",", "name", ",", "description", "=", "\"\"", ",", "whitelisted_container_task_types", "=", "None", ",", "whitelisted_executable_task_types", "=", "None", ",", ")", ":", "# Translate whitelists None to [] if necessary", "if", "whitelisted_c...
37.48
21.32
def plot_correlation_heatmap(self): """ Return HTML for correlation heatmap """ data = None corr_type = None correlation_type = getattr(config, 'rna_seqc' ,{}).get('default_correlation', 'spearman') if self.rna_seqc_spearman is not None and correlation_type != 'pearson': ...
[ "def", "plot_correlation_heatmap", "(", "self", ")", ":", "data", "=", "None", "corr_type", "=", "None", "correlation_type", "=", "getattr", "(", "config", ",", "'rna_seqc'", ",", "{", "}", ")", ".", "get", "(", "'default_correlation'", ",", "'spearman'", ")...
43.809524
17.380952
def get_system_offset(): """Get system's timezone offset using built-in library time. For the Timezone constants (altzone, daylight, timezone, and tzname), the value is determined by the timezone rules in effect at module load time or the last time tzset() is called and may be incorrect for times in th...
[ "def", "get_system_offset", "(", ")", ":", "import", "time", "if", "time", ".", "daylight", "and", "time", ".", "localtime", "(", ")", ".", "tm_isdst", ">", "0", ":", "return", "-", "time", ".", "altzone", "else", ":", "return", "-", "time", ".", "ti...
38.928571
24.571429
def Psat(self, T, polish=False): r'''Generic method to calculate vapor pressure for a specified `T`. From Tc to 0.32Tc, uses a 10th order polynomial of the following form: .. math:: \ln\frac{P_r}{T_r} = \sum_{k=0}^{10} C_k\left(\frac{\alpha}{T_r} -1\righ...
[ "def", "Psat", "(", "self", ",", "T", ",", "polish", "=", "False", ")", ":", "alpha", "=", "self", ".", "a_alpha_and_derivatives", "(", "T", ",", "full", "=", "False", ")", "/", "self", ".", "a", "Tr", "=", "T", "/", "self", ".", "Tc", "x", "="...
37.884058
24.492754
def render_field(dictionary, field, prepend=None, append=None, quotes=False, **opts): ''' Render a field found under the ``field`` level of the hierarchy in the ``dictionary`` object. This is useful to render a field in...
[ "def", "render_field", "(", "dictionary", ",", "field", ",", "prepend", "=", "None", ",", "append", "=", "None", ",", "quotes", "=", "False", ",", "*", "*", "opts", ")", ":", "value", "=", "traverse", "(", "dictionary", ",", "field", ")", "if", "valu...
32.141026
24.705128
def get_extension_reports(self, publisher_name, extension_name, days=None, count=None, after_date=None): """GetExtensionReports. [Preview API] Returns extension reports :param str publisher_name: Name of the publisher who published the extension :param str extension_name: Name of the ext...
[ "def", "get_extension_reports", "(", "self", ",", "publisher_name", ",", "extension_name", ",", "days", "=", "None", ",", "count", "=", "None", ",", "after_date", "=", "None", ")", ":", "route_values", "=", "{", "}", "if", "publisher_name", "is", "not", "N...
59.5
26.357143
def _should_proxy(self, attr): """ Determines whether `attr` should be looked up on the proxied object, or the proxy itself. """ if attr in type(self).__notproxied__: return False if _oga(self, "__notproxied__") is True: return False retur...
[ "def", "_should_proxy", "(", "self", ",", "attr", ")", ":", "if", "attr", "in", "type", "(", "self", ")", ".", "__notproxied__", ":", "return", "False", "if", "_oga", "(", "self", ",", "\"__notproxied__\"", ")", "is", "True", ":", "return", "False", "r...
28.727273
15.454545
def create(self, instance, parameters, existing=True): """Create an instance Args: instance (AtlasServiceInstance.Instance): Existing or New instance parameters (dict): Parameters for the instance Keyword Arguments: existing (bool): True ...
[ "def", "create", "(", "self", ",", "instance", ",", "parameters", ",", "existing", "=", "True", ")", ":", "return", "self", ".", "service_instance", ".", "create", "(", "instance", ",", "parameters", ",", "existing", ")" ]
37.071429
22.357143
def _get_object_as_soft(self): """Get object as SOFT formatted string.""" soft = [] if self.database is not None: soft.append(self.database._get_object_as_soft()) soft += ["^%s = %s" % (self.geotype, self.name), self._get_metadata_as_string()] for gsm...
[ "def", "_get_object_as_soft", "(", "self", ")", ":", "soft", "=", "[", "]", "if", "self", ".", "database", "is", "not", "None", ":", "soft", ".", "append", "(", "self", ".", "database", ".", "_get_object_as_soft", "(", ")", ")", "soft", "+=", "[", "\...
39.230769
11.692308
def update_from_response(self, response): """ Update the state of the Table object based on the response data received from Amazon DynamoDB. """ if 'Table' in response: self._dict.update(response['Table']) elif 'TableDescription' in response: self....
[ "def", "update_from_response", "(", "self", ",", "response", ")", ":", "if", "'Table'", "in", "response", ":", "self", ".", "_dict", ".", "update", "(", "response", "[", "'Table'", "]", ")", "elif", "'TableDescription'", "in", "response", ":", "self", ".",...
40.818182
8.272727
def represent_pixel_location(self): """ Returns a NumPy array that represents the 2D pixel location, which is defined by PFNC, of the original image data. You may use the returned NumPy array for a calculation to map the original image to another format. :return: A NumP...
[ "def", "represent_pixel_location", "(", "self", ")", ":", "if", "self", ".", "data", "is", "None", ":", "return", "None", "#", "return", "self", ".", "_data", ".", "reshape", "(", "self", ".", "height", "+", "self", ".", "y_padding", ",", "int", "(", ...
32.833333
20.611111
def create_authorizer(self, restapi, uri, authorizer): """ Create Authorizer for API gateway """ authorizer_type = authorizer.get("type", "TOKEN").upper() identity_validation_expression = authorizer.get('validation_expression', None) authorizer_resource = troposphere.api...
[ "def", "create_authorizer", "(", "self", ",", "restapi", ",", "uri", ",", "authorizer", ")", ":", "authorizer_type", "=", "authorizer", ".", "get", "(", "\"type\"", ",", "\"TOKEN\"", ")", ".", "upper", "(", ")", "identity_validation_expression", "=", "authoriz...
50.5
24.571429
def print_nodes(nodes, detailed=False): """Prints all the given nodes""" found = 0 for node in nodes: found += 1 print_node(node, detailed=detailed) print("\nFound {0} node{1}".format(found, "s" if found != 1 else ""))
[ "def", "print_nodes", "(", "nodes", ",", "detailed", "=", "False", ")", ":", "found", "=", "0", "for", "node", "in", "nodes", ":", "found", "+=", "1", "print_node", "(", "node", ",", "detailed", "=", "detailed", ")", "print", "(", "\"\\nFound {0} node{1}...
34.857143
14.857143
def _transformBy(self, matrix, **kwargs): """ Subclasses may override this method. """ for contour in self.contours: contour.transformBy(matrix) for component in self.components: component.transformBy(matrix) for anchor in self.anchors: ...
[ "def", "_transformBy", "(", "self", ",", "matrix", ",", "*", "*", "kwargs", ")", ":", "for", "contour", "in", "self", ".", "contours", ":", "contour", ".", "transformBy", "(", "matrix", ")", "for", "component", "in", "self", ".", "components", ":", "co...
35
1.666667
def get_structures(self, chemsys_formula_id, final=True): """ Get a list of Structures corresponding to a chemical system, formula, or materials_id. Args: chemsys_formula_id (str): A chemical system (e.g., Li-Fe-O), or formula (e.g., Fe2O3) or materials_id (e...
[ "def", "get_structures", "(", "self", ",", "chemsys_formula_id", ",", "final", "=", "True", ")", ":", "prop", "=", "\"final_structure\"", "if", "final", "else", "\"initial_structure\"", "data", "=", "self", ".", "get_data", "(", "chemsys_formula_id", ",", "prop"...
40.705882
21.882353
def link_file(self, path, prefixed_path, source_storage): """ Attempt to link ``path`` """ # Skip this file if it was already copied earlier if prefixed_path in self.symlinked_files: return self.log("Skipping '%s' (already linked earlier)" % path) # Delete the...
[ "def", "link_file", "(", "self", ",", "path", ",", "prefixed_path", ",", "source_storage", ")", ":", "# Skip this file if it was already copied earlier", "if", "prefixed_path", "in", "self", ".", "symlinked_files", ":", "return", "self", ".", "log", "(", "\"Skipping...
43.210526
15.210526
def open_file_dialog(windowTitle, wildcard, defaultDir=os.getcwd(), style=None, parent=None): """ Opens a wx widget file select dialog. Wild card specifies which kinds of files are allowed. Style - specifies style of dialog (read wx documentation for information) """ if parent == None: ...
[ "def", "open_file_dialog", "(", "windowTitle", ",", "wildcard", ",", "defaultDir", "=", "os", ".", "getcwd", "(", ")", ",", "style", "=", "None", ",", "parent", "=", "None", ")", ":", "if", "parent", "==", "None", ":", "app", "=", "wx", ".", "App", ...
31.190476
23.095238
def item(self, index: int) -> Optional[Node]: """Return item with the index. If the index is negative number or out of the list, return None. """ if not isinstance(index, int): raise TypeError( 'Indeces must be integer, not {}'.format(type(index))) re...
[ "def", "item", "(", "self", ",", "index", ":", "int", ")", "->", "Optional", "[", "Node", "]", ":", "if", "not", "isinstance", "(", "index", ",", "int", ")", ":", "raise", "TypeError", "(", "'Indeces must be integer, not {}'", ".", "format", "(", "type",...
41.555556
17
def _get_equivalent_distances_east(wid, lng, mag, repi, focal_depth=10., ab06=False): """ Computes equivalent values of Joyner-Boore and closest distance to the rupture given epoicentral distance. The procedure is described in Atkinson (2012) - Appendix A (page 32). ...
[ "def", "_get_equivalent_distances_east", "(", "wid", ",", "lng", ",", "mag", ",", "repi", ",", "focal_depth", "=", "10.", ",", "ab06", "=", "False", ")", ":", "dtop", "=", "focal_depth", "-", "0.5", "*", "wid", "# this computes a minimum ztor value - used for AB...
34.625
17.375
def _compute_term2(self, C, mag, r): """ This computes the term f2 equation 8 Drouet & Cotton (2015) """ return (C['c4'] + C['c5'] * mag) * \ np.log(np.sqrt(r**2 + C['c6']**2)) + C['c7'] * r
[ "def", "_compute_term2", "(", "self", ",", "C", ",", "mag", ",", "r", ")", ":", "return", "(", "C", "[", "'c4'", "]", "+", "C", "[", "'c5'", "]", "*", "mag", ")", "*", "np", ".", "log", "(", "np", ".", "sqrt", "(", "r", "**", "2", "+", "C...
38.166667
9.166667
def to_netflux(flux): r"""Compute the netflux. f_ij^{+}=max{0, f_ij-f_ji} for all pairs i,j Parameters ---------- flux : (M, M) scipy.sparse matrix Matrix of flux values between pairs of states. Returns ------- netflux : (M, M) scipy.sparse matrix Matrix of netflux...
[ "def", "to_netflux", "(", "flux", ")", ":", "netflux", "=", "flux", "-", "flux", ".", "T", "\"\"\"Set negative entries to zero\"\"\"", "netflux", "=", "remove_negative_entries", "(", "netflux", ")", "return", "netflux" ]
21.545455
19.681818
def _dfromtimestamp(timestamp): """Custom date timestamp constructor. ditto """ try: return datetime.date.fromtimestamp(timestamp) except OSError: timestamp -= time.timezone d = datetime.date(1970, 1, 1) + datetime.timedelta(seconds=timestamp) if _isdst(d): ti...
[ "def", "_dfromtimestamp", "(", "timestamp", ")", ":", "try", ":", "return", "datetime", ".", "date", ".", "fromtimestamp", "(", "timestamp", ")", "except", "OSError", ":", "timestamp", "-=", "time", ".", "timezone", "d", "=", "datetime", ".", "date", "(", ...
35.25
17.75
def combine_calls(*args): """Combine multiple callsets into a final set of merged calls. """ if len(args) == 3: is_cwl = False batch_id, samples, data = args caller_names, vrn_files = _organize_variants(samples, batch_id) else: is_cwl = True samples = [utils.to_si...
[ "def", "combine_calls", "(", "*", "args", ")", ":", "if", "len", "(", "args", ")", "==", "3", ":", "is_cwl", "=", "False", "batch_id", ",", "samples", ",", "data", "=", "args", "caller_names", ",", "vrn_files", "=", "_organize_variants", "(", "samples", ...
53.203704
24.888889
def handle_hooks(self, hooks, hook_type, *args): ''' Processes hooks of the specified type. :param hook_type: The type of hook, including ``before``, ``after``, ``on_error``, and ``on_route``. :param \*args: Arguments to pass to the hooks. ''' i...
[ "def", "handle_hooks", "(", "self", ",", "hooks", ",", "hook_type", ",", "*", "args", ")", ":", "if", "hook_type", "not", "in", "[", "'before'", ",", "'on_route'", "]", ":", "hooks", "=", "reversed", "(", "hooks", ")", "for", "hook", "in", "hooks", "...
41.352941
21.117647
def _handle_amqp_frame(self, data_in): """Unmarshal a single AMQP frame and return the result. :param data_in: socket data :return: data_in, channel_id, frame """ if not data_in: return data_in, None, None try: byte_count, channel_id, frame_in = ...
[ "def", "_handle_amqp_frame", "(", "self", ",", "data_in", ")", ":", "if", "not", "data_in", ":", "return", "data_in", ",", "None", ",", "None", "try", ":", "byte_count", ",", "channel_id", ",", "frame_in", "=", "pamqp_frame", ".", "unmarshal", "(", "data_i...
37.9
15.3
def validate(self): """ validate: Makes sure content node is valid Args: None Returns: boolean indicating if content node is valid """ assert isinstance(self.author, str) , "Assumption Failed: Author is not a string" assert isinstance(self.aggregator, str) , "Assu...
[ "def", "validate", "(", "self", ")", ":", "assert", "isinstance", "(", "self", ".", "author", ",", "str", ")", ",", "\"Assumption Failed: Author is not a string\"", "assert", "isinstance", "(", "self", ".", "aggregator", ",", "str", ")", ",", "\"Assumption Faile...
64.416667
32.166667
def loadAnns(self, ids=[]): """ Load anns with the specified ids. :param ids (int array) : integer ids specifying anns :return: anns (object array) : loaded ann objects """ if type(ids) == list: return [self.anns[id] for id in ids] elif type(ids)...
[ "def", "loadAnns", "(", "self", ",", "ids", "=", "[", "]", ")", ":", "if", "type", "(", "ids", ")", "==", "list", ":", "return", "[", "self", ".", "anns", "[", "id", "]", "for", "id", "in", "ids", "]", "elif", "type", "(", "ids", ")", "==", ...
35.5
9.1
def forecast_names(self): """get the forecast names from the pestpp options (if any). Returns None if no forecasts are named Returns ------- forecast_names : list a list of forecast names. """ if "forecasts" in self.pestpp_options.keys(): ...
[ "def", "forecast_names", "(", "self", ")", ":", "if", "\"forecasts\"", "in", "self", ".", "pestpp_options", ".", "keys", "(", ")", ":", "return", "self", ".", "pestpp_options", "[", "\"forecasts\"", "]", ".", "lower", "(", ")", ".", "split", "(", "','", ...
33.3125
18.8125
def autosize_fieldname(idfobject): """return autsizeable field names in idfobject""" # undocumented stuff in this code return [fname for (fname, dct) in zip(idfobject.objls, idfobject['objidd']) if 'autosizable' in dct]
[ "def", "autosize_fieldname", "(", "idfobject", ")", ":", "# undocumented stuff in this code", "return", "[", "fname", "for", "(", "fname", ",", "dct", ")", "in", "zip", "(", "idfobject", ".", "objls", ",", "idfobject", "[", "'objidd'", "]", ")", "if", "'auto...
46.666667
8.833333
def from_db_value(self, value, expression, connection, context): """ Convert a string from the database into an Enum value """ if value is None: return value return self.enum[value]
[ "def", "from_db_value", "(", "self", ",", "value", ",", "expression", ",", "connection", ",", "context", ")", ":", "if", "value", "is", "None", ":", "return", "value", "return", "self", ".", "enum", "[", "value", "]" ]
32.428571
12.142857
def get_pos(vcf_line): """ Very lightweight parsing of a vcf line to get position. Returns a dict containing: 'chrom': index of chromosome (int), indicates sort order 'pos': position on chromosome (int) """ if not vcf_line: return None vcf_dat...
[ "def", "get_pos", "(", "vcf_line", ")", ":", "if", "not", "vcf_line", ":", "return", "None", "vcf_data", "=", "vcf_line", ".", "strip", "(", ")", ".", "split", "(", "'\\t'", ")", "return_data", "=", "dict", "(", ")", "return_data", "[", "'chrom'", "]",...
33.066667
13.333333
def user_info(self, kv): """Sets user_info dict entry through a tuple.""" key, value = kv self.__user_info[key] = value
[ "def", "user_info", "(", "self", ",", "kv", ")", ":", "key", ",", "value", "=", "kv", "self", ".", "__user_info", "[", "key", "]", "=", "value" ]
28
15.2
def _new_chart_graphicFrame(self, rId, x, y, cx, cy): """ Return a newly created `p:graphicFrame` element having the specified position and size and containing the chart identified by *rId*. """ id_, name = self.shape_id, self.name return CT_GraphicalObjectFrame.new_chart...
[ "def", "_new_chart_graphicFrame", "(", "self", ",", "rId", ",", "x", ",", "y", ",", "cx", ",", "cy", ")", ":", "id_", ",", "name", "=", "self", ".", "shape_id", ",", "self", ".", "name", "return", "CT_GraphicalObjectFrame", ".", "new_chart_graphicFrame", ...
41.888889
15.222222
def end_of_history(self, current): # (M->) u'''Move to the end of the input history, i.e., the line currently being entered.''' self.history_cursor = len(self.history) current.set_line(self.history[-1].get_line_text())
[ "def", "end_of_history", "(", "self", ",", "current", ")", ":", "# (M->)\r", "self", ".", "history_cursor", "=", "len", "(", "self", ".", "history", ")", "current", ".", "set_line", "(", "self", ".", "history", "[", "-", "1", "]", ".", "get_line_text", ...
50
15.6
def virtual_network_delete(name, resource_group, **kwargs): ''' .. versionadded:: 2019.2.0 Delete a virtual network. :param name: The name of the virtual network to delete. :param resource_group: The resource group name assigned to the virtual network CLI Example: .. code-block:...
[ "def", "virtual_network_delete", "(", "name", ",", "resource_group", ",", "*", "*", "kwargs", ")", ":", "result", "=", "False", "netconn", "=", "__utils__", "[", "'azurearm.get_client'", "]", "(", "'network'", ",", "*", "*", "kwargs", ")", "try", ":", "vne...
25.483871
25.806452
def get_avatar_upload_to(self, filename): """ Returns the path to upload the associated avatar to. """ dummy, ext = os.path.splitext(filename) return os.path.join( machina_settings.PROFILE_AVATAR_UPLOAD_TO, '{id}{ext}'.format(id=str(uuid.uuid4()).replace('-', ''), ext=ext...
[ "def", "get_avatar_upload_to", "(", "self", ",", "filename", ")", ":", "dummy", ",", "ext", "=", "os", ".", "path", ".", "splitext", "(", "filename", ")", "return", "os", ".", "path", ".", "join", "(", "machina_settings", ".", "PROFILE_AVATAR_UPLOAD_TO", "...
46.571429
14.857143
def sort_annotations(annotations: List[Tuple[int, int, str]] ) -> List[Tuple[int, int, str]]: """ Sorts the annotations by their start_time. """ return sorted(annotations, key=lambda x: x[0])
[ "def", "sort_annotations", "(", "annotations", ":", "List", "[", "Tuple", "[", "int", ",", "int", ",", "str", "]", "]", ")", "->", "List", "[", "Tuple", "[", "int", ",", "int", ",", "str", "]", "]", ":", "return", "sorted", "(", "annotations", ",",...
54.25
10.75
def _send_guess(self,value): """ Send the argument as a string in a way that should (probably, maybe!) be processed properly by C++ calls like atoi, atof, etc. This method is NOT RECOMMENDED, particularly for floats, because values are often mangled silently. Instead, specify ...
[ "def", "_send_guess", "(", "self", ",", "value", ")", ":", "if", "type", "(", "value", ")", "!=", "str", "and", "type", "(", "value", ")", "!=", "bytes", "and", "self", ".", "give_warnings", ":", "w", "=", "\"Warning: Sending {} as a string. This can give wi...
49.4
26.1
def timescale_sensitivity(T, k): """ calculate the sensitivity matrix for timescale k given transition matrix T. Parameters ---------- T : numpy.ndarray shape = (n, n) Transition matrix k : int timescale index for timescales of descending order (k = 0 for the infinite one) R...
[ "def", "timescale_sensitivity", "(", "T", ",", "k", ")", ":", "eValues", ",", "rightEigenvectors", "=", "numpy", ".", "linalg", ".", "eig", "(", "T", ")", "leftEigenvectors", "=", "numpy", ".", "linalg", ".", "inv", "(", "rightEigenvectors", ")", "perm", ...
26.378378
24.702703
def get_b64_image_prediction(self, model_id, b64_encoded_string, token=None, url=API_GET_PREDICTION_IMAGE_URL): """ Gets a prediction from a supplied image enconded as a b64 string, useful when uploading images to a server backed by this library. :param model_id: string, once you train a...
[ "def", "get_b64_image_prediction", "(", "self", ",", "model_id", ",", "b64_encoded_string", ",", "token", "=", "None", ",", "url", "=", "API_GET_PREDICTION_IMAGE_URL", ")", ":", "auth", "=", "'Bearer '", "+", "self", ".", "check_for_token", "(", "token", ")", ...
52.888889
29.333333
def translation_table(language, filepath='supported_translations.json'): ''' Opens up file located under the etc directory containing language codes and prints them out. :param file: Path to location of json file :type file: str :return: language codes :rtype: dict ''' fullpath = a...
[ "def", "translation_table", "(", "language", ",", "filepath", "=", "'supported_translations.json'", ")", ":", "fullpath", "=", "abspath", "(", "join", "(", "dirname", "(", "__file__", ")", ",", "'etc'", ",", "filepath", ")", ")", "if", "not", "isfile", "(", ...
30.809524
24.52381
def pack_column_flat(self, value, components=None, offset=False): """ TODO: add documentation """ if components: if isinstance(components, str): components = [components] elif isinstance(components, list): components = components ...
[ "def", "pack_column_flat", "(", "self", ",", "value", ",", "components", "=", "None", ",", "offset", "=", "False", ")", ":", "if", "components", ":", "if", "isinstance", "(", "components", ",", "str", ")", ":", "components", "=", "[", "components", "]", ...
33.290323
14.903226
def load_related(self, related, *related_fields): '''It returns a new :class:`Query` that automatically follows the foreign-key relationship ``related``. :parameter related: A field name corresponding to a :class:`ForeignKey` in :attr:`Query.model`. :parameter related_fields: optional :class:`Field` ...
[ "def", "load_related", "(", "self", ",", "related", ",", "*", "related_fields", ")", ":", "field", "=", "self", ".", "_get_related_field", "(", "related", ")", "if", "not", "field", ":", "raise", "FieldError", "(", "'\"%s\" is not a related field for \"%s\"'", "...
43.083333
25.083333
def _from_dict(cls, _dict): """Initialize a DialogNode object from a json dictionary.""" args = {} if 'dialog_node' in _dict: args['dialog_node'] = _dict.get('dialog_node') else: raise ValueError( 'Required property \'dialog_node\' not present in D...
[ "def", "_from_dict", "(", "cls", ",", "_dict", ")", ":", "args", "=", "{", "}", "if", "'dialog_node'", "in", "_dict", ":", "args", "[", "'dialog_node'", "]", "=", "_dict", ".", "get", "(", "'dialog_node'", ")", "else", ":", "raise", "ValueError", "(", ...
43.792453
14.886792
def modified_data_decorator(function): """ Decorator to initialise the modified_data if necessary. To be used in list functions to modify the list """ @wraps(function) def func(self, *args, **kwargs): """Decorator function""" if not self.get_read_only() or not self.is_locked(): ...
[ "def", "modified_data_decorator", "(", "function", ")", ":", "@", "wraps", "(", "function", ")", "def", "func", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "\"\"\"Decorator function\"\"\"", "if", "not", "self", ".", "get_read_only", "...
29.666667
16.2
def createConnection(self): """Return a CardConnection to the Card object.""" readerobj = None if isinstance(self.reader, Reader): readerobj = self.reader elif type(self.reader) == str: for reader in readers(): if self.reader == str(reader): ...
[ "def", "createConnection", "(", "self", ")", ":", "readerobj", "=", "None", "if", "isinstance", "(", "self", ".", "reader", ",", "Reader", ")", ":", "readerobj", "=", "self", ".", "reader", "elif", "type", "(", "self", ".", "reader", ")", "==", "str", ...
34.25
11.3125
def email_url_config(cls, url, backend=None): """Parses an email URL.""" config = {} url = urlparse(url) if not isinstance(url, cls.URL_CLASS) else url # Remove query strings path = url.path[1:] path = unquote_plus(path.split('?', 2)[0]) # Update with environm...
[ "def", "email_url_config", "(", "cls", ",", "url", ",", "backend", "=", "None", ")", ":", "config", "=", "{", "}", "url", "=", "urlparse", "(", "url", ")", "if", "not", "isinstance", "(", "url", ",", "cls", ".", "URL_CLASS", ")", "else", "url", "# ...
33.813953
17.534884
def get_compiler(self, using=None, connection=None): """ Overrides the Query method get_compiler in order to return an instance of the above custom compiler. """ # Copy the body of this method from Django except the final # return statement. We will ignore code coverage for t...
[ "def", "get_compiler", "(", "self", ",", "using", "=", "None", ",", "connection", "=", "None", ")", ":", "# Copy the body of this method from Django except the final", "# return statement. We will ignore code coverage for this.", "if", "using", "is", "None", "and", "connect...
52.1
16.75
def update_prompt(self, name, new_template=None): """This is called when a prompt template is updated. It processes abbreviations used in the prompt template (like \#) and calculates how many invisible characters (ANSI colour escapes) the resulting prompt contains. It is...
[ "def", "update_prompt", "(", "self", ",", "name", ",", "new_template", "=", "None", ")", ":", "if", "new_template", "is", "not", "None", ":", "self", ".", "templates", "[", "name", "]", "=", "multiple_replace", "(", "prompt_abbreviations", ",", "new_template...
58
25.125
def skip(self, num_bytes): """Jump the ahead the specified bytes in the buffer.""" if num_bytes is None: self._offset = len(self._data) else: self._offset += num_bytes
[ "def", "skip", "(", "self", ",", "num_bytes", ")", ":", "if", "num_bytes", "is", "None", ":", "self", ".", "_offset", "=", "len", "(", "self", ".", "_data", ")", "else", ":", "self", ".", "_offset", "+=", "num_bytes" ]
35
9.5
def __get_rev(self, key, version, **kwa): '''Obtain particular version of the doc at key.''' if '_doc' in kwa: doc = kwa['_doc'] else: if type(version) is int: if version == 0: order = pymongo.ASCENDING elif version == -1: order = pymongo.DESCENDING do...
[ "def", "__get_rev", "(", "self", ",", "key", ",", "version", ",", "*", "*", "kwa", ")", ":", "if", "'_doc'", "in", "kwa", ":", "doc", "=", "kwa", "[", "'_doc'", "]", "else", ":", "if", "type", "(", "version", ")", "is", "int", ":", "if", "versi...
33.190476
16.428571
def apply_translation(self, offset): """ Apply a transformation matrix to the current path in- place Parameters ----------- offset : float or (3,) float Translation to be applied to mesh """ # work on 2D and 3D paths dimension = self.vertices.sh...
[ "def", "apply_translation", "(", "self", ",", "offset", ")", ":", "# work on 2D and 3D paths", "dimension", "=", "self", ".", "vertices", ".", "shape", "[", "1", "]", "# make sure offset is correct length and type", "offset", "=", "np", ".", "array", "(", "offset"...
31.8
12
def normalize_feature_objects(feature_objs): """Takes an iterable of GeoJSON-like Feature mappings or an iterable of objects with a geo interface and normalizes it to the former.""" for obj in feature_objs: if hasattr(obj, "__geo_interface__") and \ 'type' in obj.__geo_interface__.key...
[ "def", "normalize_feature_objects", "(", "feature_objs", ")", ":", "for", "obj", "in", "feature_objs", ":", "if", "hasattr", "(", "obj", ",", "\"__geo_interface__\"", ")", "and", "'type'", "in", "obj", ".", "__geo_interface__", ".", "keys", "(", ")", "and", ...
44.666667
11.533333
def pretty_duration(seconds): """ Returns a user-friendly representation of the provided duration in seconds. For example: 62.8 => "1m2.8s", or 129837.8 => "2d12h4m57.8s" """ if seconds is None: return '' ret = '' if seconds >= 86400: ret += '{:.0f}d'.format(int(seconds / 86400))...
[ "def", "pretty_duration", "(", "seconds", ")", ":", "if", "seconds", "is", "None", ":", "return", "''", "ret", "=", "''", "if", "seconds", ">=", "86400", ":", "ret", "+=", "'{:.0f}d'", ".", "format", "(", "int", "(", "seconds", "/", "86400", ")", ")"...
32.947368
13.789474
def _evaluate(self,R,z,phi=0.,t=0.): """ NAME: _evaluate PURPOSE: evaluate the potential at R,phi,t INPUT: R - Galactocentric cylindrical radius z - vertical height phi - azimuth t - time OUTPUT: Phi(R,z...
[ "def", "_evaluate", "(", "self", ",", "R", ",", "z", ",", "phi", "=", "0.", ",", "t", "=", "0.", ")", ":", "#Calculate relevant time", "if", "t", "<", "self", ".", "_tform", ":", "smooth", "=", "0.", "elif", "t", "<", "self", ".", "_tsteady", ":"...
33.628571
16.371429
async def kick(self, user_id: base.Integer, until_date: typing.Union[base.Integer, None] = None): """ Use this method to kick a user from a group, a supergroup or a channel. In the case of supergroups and channels, the user will not be able to return to the group on th...
[ "async", "def", "kick", "(", "self", ",", "user_id", ":", "base", ".", "Integer", ",", "until_date", ":", "typing", ".", "Union", "[", "base", ".", "Integer", ",", "None", "]", "=", "None", ")", ":", "return", "await", "self", ".", "bot", ".", "kic...
53.304348
30.608696
def publish(message, exchange=None): """ Publish a message to an exchange. This is a synchronous call, meaning that when this function returns, an acknowledgment has been received from the message broker and you can be certain the message was published successfully. There are some cases where ...
[ "def", "publish", "(", "message", ",", "exchange", "=", "None", ")", ":", "pre_publish_signal", ".", "send", "(", "publish", ",", "message", "=", "message", ")", "if", "exchange", "is", "None", ":", "exchange", "=", "config", ".", "conf", "[", "\"publish...
43.117647
25.941176
def add_section(self, name): """Append `section` to model Arguments: name (str): Name of section """ assert isinstance(name, str) # Skip existing sections for section in self.sections: if section.name == name: return section ...
[ "def", "add_section", "(", "self", ",", "name", ")", ":", "assert", "isinstance", "(", "name", ",", "str", ")", "# Skip existing sections", "for", "section", "in", "self", ".", "sections", ":", "if", "section", ".", "name", "==", "name", ":", "return", "...
21.434783
17.130435
def print_commandless_help(self): """ print_commandless_help """ doc_help = self.m_doc.strip().split("\n") if len(doc_help) > 0: print("\033[33m--\033[0m") print("\033[34m" + doc_help[0] + "\033[0m") asp = "author :" doc_help_rest...
[ "def", "print_commandless_help", "(", "self", ")", ":", "doc_help", "=", "self", ".", "m_doc", ".", "strip", "(", ")", ".", "split", "(", "\"\\n\"", ")", "if", "len", "(", "doc_help", ")", ">", "0", ":", "print", "(", "\"\\033[33m--\\033[0m\"", ")", "p...
33.185185
16.888889
def get_region_products(self, region): """获得指定区域的产品信息 Args: - region: 区域,如:"nq" Returns: 返回该区域的产品信息,若失败则返回None """ regions, retInfo = self.list_regions() if regions is None: return None for r in regions: if r.get...
[ "def", "get_region_products", "(", "self", ",", "region", ")", ":", "regions", ",", "retInfo", "=", "self", ".", "list_regions", "(", ")", "if", "regions", "is", "None", ":", "return", "None", "for", "r", "in", "regions", ":", "if", "r", ".", "get", ...
21.411765
16.529412
def sample(self, bqm, chain_strength=1.0, chain_break_fraction=True, **parameters): """Sample the binary quadratic model. Note: At the initial sample(..) call, it will find a suitable embedding and initialize the remaining attributes before sampling the bqm. All following sample(..) calls will ...
[ "def", "sample", "(", "self", ",", "bqm", ",", "chain_strength", "=", "1.0", ",", "chain_break_fraction", "=", "True", ",", "*", "*", "parameters", ")", ":", "if", "self", ".", "embedding", "is", "None", ":", "# Find embedding", "child", "=", "self", "."...
54.4
36.114286
def hourly_horizontal_infrared(self): """A data collection containing hourly horizontal infrared intensity in W/m2. """ sky_cover = self._sky_condition.hourly_sky_cover db_temp = self._dry_bulb_condition.hourly_values dp_temp = self._humidity_condition.hourly_dew_point_values( ...
[ "def", "hourly_horizontal_infrared", "(", "self", ")", ":", "sky_cover", "=", "self", ".", "_sky_condition", ".", "hourly_sky_cover", "db_temp", "=", "self", ".", "_dry_bulb_condition", ".", "hourly_values", "dp_temp", "=", "self", ".", "_humidity_condition", ".", ...
43
17.533333
def format_number(x): """Format number to string Function converts a number to string. For numbers of class :class:`float`, up to 17 digits will be used to print the entire floating point number. Any padding zeros will be removed at the end of the number. See :ref:`user-guide:int` and :ref:`user-guide...
[ "def", "format_number", "(", "x", ")", ":", "if", "isinstance", "(", "x", ",", "float", ")", ":", "# Helps prevent loss of precision as using str() in Python 2 only prints 12 digits of precision.", "# However, IEEE754-1985 standard says that 17 significant decimal digits is required to...
40.4
33.8
def set(self, key, value): """ Sets a single value in a preconfigured data file. Arguments: key -- The full dot-notated key to set the value for. value -- The value to set. """ d = self.data.data keys = key.split('.') latest = keys.pop() ...
[ "def", "set", "(", "self", ",", "key", ",", "value", ")", ":", "d", "=", "self", ".", "data", ".", "data", "keys", "=", "key", ".", "split", "(", "'.'", ")", "latest", "=", "keys", ".", "pop", "(", ")", "for", "k", "in", "keys", ":", "d", "...
30.666667
15.222222
def svg2paths2(svg_file_location, return_svg_attributes=True, convert_circles_to_paths=True, convert_ellipses_to_paths=True, convert_lines_to_paths=True, convert_polylines_to_paths=True, convert_polygons_to_paths=True, ...
[ "def", "svg2paths2", "(", "svg_file_location", ",", "return_svg_attributes", "=", "True", ",", "convert_circles_to_paths", "=", "True", ",", "convert_ellipses_to_paths", "=", "True", ",", "convert_lines_to_paths", "=", "True", ",", "convert_polylines_to_paths", "=", "Tr...
56
16.894737
def _serialize(self, include_run_logs=False, strict_json=False): """ Serialize a representation of this Job to a Python dict object. """ # return tasks in sorted order if graph is in a valid state try: topo_sorted = self.topological_sort() t = [self.tasks[task]._serializ...
[ "def", "_serialize", "(", "self", ",", "include_run_logs", "=", "False", ",", "strict_json", "=", "False", ")", ":", "# return tasks in sorted order if graph is in a valid state", "try", ":", "topo_sorted", "=", "self", ".", "topological_sort", "(", ")", "t", "=", ...
40.741935
17.806452
def obj_with_unit(obj, unit): """ Returns a `FloatWithUnit` instance if obj is scalar, a dictionary of objects with units if obj is a dict, else an instance of `ArrayWithFloatWithUnit`. Args: unit: Specific units (eV, Ha, m, ang, etc.). """ unit_type = _UNAME2UTYPE[unit] if isi...
[ "def", "obj_with_unit", "(", "obj", ",", "unit", ")", ":", "unit_type", "=", "_UNAME2UTYPE", "[", "unit", "]", "if", "isinstance", "(", "obj", ",", "numbers", ".", "Number", ")", ":", "return", "FloatWithUnit", "(", "obj", ",", "unit", "=", "unit", ","...
34.588235
18.588235
def _bracket(self, qinit, f0, fun): """Find a bracket that does contain the minimum""" self.num_bracket = 0 qa = qinit fa = fun(qa) counter = 0 if fa >= f0: while True: self.num_bracket += 1 #print " bracket shrink" ...
[ "def", "_bracket", "(", "self", ",", "qinit", ",", "f0", ",", "fun", ")", ":", "self", ".", "num_bracket", "=", "0", "qa", "=", "qinit", "fa", "=", "fun", "(", "qa", ")", "counter", "=", "0", "if", "fa", ">=", "f0", ":", "while", "True", ":", ...
33.175
12.775
def _parse_params(self, params=None): """ Parse parameters. Combine default and user-defined parameters. """ prm = self.default_params.copy() if params is not None: prm.update(params) if prm["background"]: # Absolute path, just to be su...
[ "def", "_parse_params", "(", "self", ",", "params", "=", "None", ")", ":", "prm", "=", "self", ".", "default_params", ".", "copy", "(", ")", "if", "params", "is", "not", "None", ":", "prm", ".", "update", "(", "params", ")", "if", "prm", "[", "\"ba...
28.285714
14.666667
def _tag_most_likely(examples): """ Return a list of date elements by choosing the most likely element for a token within examples (context-free). """ tokenized_examples = [_tokenize_by_character_class(example) for example in examples] # We currently need the tokenized_examples to all have the same...
[ "def", "_tag_most_likely", "(", "examples", ")", ":", "tokenized_examples", "=", "[", "_tokenize_by_character_class", "(", "example", ")", "for", "example", "in", "examples", "]", "# We currently need the tokenized_examples to all have the same length, so drop instances that have...
48.9375
26.375
def _hz_to_semitones(self, hz): """ Convert hertz into a number of semitones above or below some reference value, in this case, A440 """ return np.log(hz / self._a440) / np.log(self._a)
[ "def", "_hz_to_semitones", "(", "self", ",", "hz", ")", ":", "return", "np", ".", "log", "(", "hz", "/", "self", ".", "_a440", ")", "/", "np", ".", "log", "(", "self", ".", "_a", ")" ]
36.666667
11.666667
def cli(env, quote): """View a quote""" manager = ordering.OrderingManager(env.client) result = manager.get_quote_details(quote) package = result['order']['items'][0]['package'] title = "{} - Package: {}, Id {}".format(result.get('name'), package['keyName'], package['id']) table = formatting.T...
[ "def", "cli", "(", "env", ",", "quote", ")", ":", "manager", "=", "ordering", ".", "OrderingManager", "(", "env", ".", "client", ")", "result", "=", "manager", ".", "get_quote_details", "(", "quote", ")", "package", "=", "result", "[", "'order'", "]", ...
30.84
18.04