text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def rindex(values, value): """ :return: the highest index in values where value is found, else raise ValueError """ if isinstance(values, STRING_TYPES): try: return values.rindex(value) except TypeError: # Python 3 compliance: search for str values in bytearray ...
[ "def", "rindex", "(", "values", ",", "value", ")", ":", "if", "isinstance", "(", "values", ",", "STRING_TYPES", ")", ":", "try", ":", "return", "values", ".", "rindex", "(", "value", ")", "except", "TypeError", ":", "# Python 3 compliance: search for str value...
40.090909
18.818182
def groups_setPurpose(self, *, channel: str, purpose: str, **kwargs) -> SlackResponse: """Sets the purpose for a private channel. Args: channel (str): The channel id. e.g. 'G1234567890' purpose (str): The new purpose for the channel. e.g. 'My Purpose' """ kwargs....
[ "def", "groups_setPurpose", "(", "self", ",", "*", ",", "channel", ":", "str", ",", "purpose", ":", "str", ",", "*", "*", "kwargs", ")", "->", "SlackResponse", ":", "kwargs", ".", "update", "(", "{", "\"channel\"", ":", "channel", ",", "\"purpose\"", "...
47
24
def _parse_text(v, header_d): """ Parses unicode. Note: unicode types for py2 and str types for py3. """ v = nullify(v) if v is None: return None try: return six.text_type(v).strip() except Exception as e: raise CastingError(six.text_type, header_d, v, st...
[ "def", "_parse_text", "(", "v", ",", "header_d", ")", ":", "v", "=", "nullify", "(", "v", ")", "if", "v", "is", "None", ":", "return", "None", "try", ":", "return", "six", ".", "text_type", "(", "v", ")", ".", "strip", "(", ")", "except", "Except...
18.176471
22.882353
def fingerprint(self): """A total graph fingerprint The result is invariant under permutation of the vertex indexes. The chance that two different (molecular) graphs yield the same fingerprint is small but not zero. (See unit tests.)""" if self.num_vertices == 0: ...
[ "def", "fingerprint", "(", "self", ")", ":", "if", "self", ".", "num_vertices", "==", "0", ":", "return", "np", ".", "zeros", "(", "20", ",", "np", ".", "ubyte", ")", "else", ":", "return", "sum", "(", "self", ".", "vertex_fingerprints", ")" ]
40.9
16.9
def action_sequence_to_logical_form(self, action_sequence: List[str]) -> str: """ Takes an action sequence as produced by :func:`logical_form_to_action_sequence`, which is a linearization of an abstract syntax tree, and reconstructs the logical form defined by that abstract syntax tree. ...
[ "def", "action_sequence_to_logical_form", "(", "self", ",", "action_sequence", ":", "List", "[", "str", "]", ")", "->", "str", ":", "# Basic outline: we assume that the bracketing that we get in the RHS of each action is the", "# correct bracketing for reconstructing the logical form...
54.5
32.5
def get_current_frame(): """ :return: current frame object (excluding this function call) :rtype: types.FrameType Uses sys._getframe if available, otherwise some trickery with sys.exc_info and a dummy exception. """ if hasattr(sys, "_getframe"): # noinspection PyProtectedMember ...
[ "def", "get_current_frame", "(", ")", ":", "if", "hasattr", "(", "sys", ",", "\"_getframe\"", ")", ":", "# noinspection PyProtectedMember", "return", "sys", ".", "_getframe", "(", "1", ")", "try", ":", "raise", "ZeroDivisionError", "except", "ZeroDivisionError", ...
32.142857
16.428571
def create_widget(self): """ Create the underlying widget. """ d = self.declaration self.widget = Icon(self.get_context(), None, d.style)
[ "def", "create_widget", "(", "self", ")", ":", "d", "=", "self", ".", "declaration", "self", ".", "widget", "=", "Icon", "(", "self", ".", "get_context", "(", ")", ",", "None", ",", "d", ".", "style", ")" ]
27.5
14.833333
def write_to_fil(self, filename_out, *args, **kwargs): """ Write data to .fil file. It check the file size then decides how to write the file. Args: filename_out (str): Name of output file """ #For timing how long it takes to write a file. t0 = time.time...
[ "def", "write_to_fil", "(", "self", ",", "filename_out", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "#For timing how long it takes to write a file.", "t0", "=", "time", ".", "time", "(", ")", "#Update header", "self", ".", "__update_header", "(", ")"...
28.52381
20.380952
def get_item_prices(self, package_id): """Get item prices. Retrieve a SoftLayer_Product_Package item prices record. :param int package_id: package identifier. :returns: A list of price IDs associated with the given package. """ mask = 'mask[pricingLocationGroup[locatio...
[ "def", "get_item_prices", "(", "self", ",", "package_id", ")", ":", "mask", "=", "'mask[pricingLocationGroup[locations]]'", "prices", "=", "self", ".", "package_svc", ".", "getItemPrices", "(", "id", "=", "package_id", ",", "mask", "=", "mask", ")", "return", ...
31.538462
22.615385
def gen_renewing_time(lease_time, elapsed=0): """Generate RENEWING time. [:rfc:`2131#section-4.4.5`]:: T1 defaults to (0.5 * duration_of_lease). T2 defaults to (0.875 * duration_of_lease). Times T1 and T2 SHOULD be chosen with some random "fuzz" around a fixed value, to avoid...
[ "def", "gen_renewing_time", "(", "lease_time", ",", "elapsed", "=", "0", ")", ":", "renewing_time", "=", "int", "(", "lease_time", ")", "*", "RENEW_PERC", "-", "elapsed", "# FIXME:80 [:rfc:`2131#section-4.4.5`]: the chosen \"fuzz\" could fingerprint", "# the implementation"...
37.913043
18.478261
def same_indexes(l1,l2): ''' from elist.elist import * l1 = [1,2,3,5] l2 = [0,2,3,4] same_indexes(l1,l2) ''' rslt = [] for i in range(0,l1.__len__()): if(l1[i]==l2[i]): rslt.append(i) return(rslt)
[ "def", "same_indexes", "(", "l1", ",", "l2", ")", ":", "rslt", "=", "[", "]", "for", "i", "in", "range", "(", "0", ",", "l1", ".", "__len__", "(", ")", ")", ":", "if", "(", "l1", "[", "i", "]", "==", "l2", "[", "i", "]", ")", ":", "rslt",...
21.416667
18.583333
def set_missing_defaults(self): """ Ensure that minimal configuration is setup and set defaults for missing values """ if 'pub_options' not in self.config: self.config['pub_options'] = { 'acknowledge': True, 'retain': True }...
[ "def", "set_missing_defaults", "(", "self", ")", ":", "if", "'pub_options'", "not", "in", "self", ".", "config", ":", "self", ".", "config", "[", "'pub_options'", "]", "=", "{", "'acknowledge'", ":", "True", ",", "'retain'", ":", "True", "}", "if", "'sub...
31.208333
13.625
def decode_event_to_internal(abi, log_event): """ Enforce the binary for internal usage. """ # Note: All addresses inside the event_data must be decoded. decoded_event = decode_event(abi, log_event) if not decoded_event: raise UnknownEventType() # copy the attribute dict because that data...
[ "def", "decode_event_to_internal", "(", "abi", ",", "log_event", ")", ":", "# Note: All addresses inside the event_data must be decoded.", "decoded_event", "=", "decode_event", "(", "abi", ",", "log_event", ")", "if", "not", "decoded_event", ":", "raise", "UnknownEventTyp...
39.354167
25.604167
def add_interactions_from(self, quadratic, vartype=None): """Add interactions and/or quadratic biases to a binary quadratic model. Args: quadratic (dict[(variable, variable), bias]/iterable[(variable, variable, bias)]): A collection of variables that have an interaction and ...
[ "def", "add_interactions_from", "(", "self", ",", "quadratic", ",", "vartype", "=", "None", ")", ":", "if", "isinstance", "(", "quadratic", ",", "abc", ".", "Mapping", ")", ":", "for", "(", "u", ",", "v", ")", ",", "bias", "in", "iteritems", "(", "qu...
49.531915
27.808511
def reset(self): """Reset the instance to its initial state""" self.alpha_ = np.zeros(self._size, dtype=int) self.beta_ = np.zeros(self._size, dtype=int) self.theta_ = np.empty(self._size, dtype=float) if self.store_variance: self.var_theta_ = np.empty(self._size, dty...
[ "def", "reset", "(", "self", ")", ":", "self", ".", "alpha_", "=", "np", ".", "zeros", "(", "self", ".", "_size", ",", "dtype", "=", "int", ")", "self", ".", "beta_", "=", "np", ".", "zeros", "(", "self", ".", "_size", ",", "dtype", "=", "int",...
38.538462
15.538462
def distutils_autosemver_case( metadata, with_release_notes=False, with_authors=True, with_changelog=True, bugtracker_url=None, ): """ :param metadata: distutils metadata object. :param with_release_notes: if true, will create the release notes. :type with_release_notes: bool :param with_aut...
[ "def", "distutils_autosemver_case", "(", "metadata", ",", "with_release_notes", "=", "False", ",", "with_authors", "=", "True", ",", "with_changelog", "=", "True", ",", "bugtracker_url", "=", "None", ",", ")", ":", "metadata", ".", "version", "=", "pkg_version",...
30.103448
19.275862
def get_content_type(name, content): """ Checks if the content_type is already set. Otherwise uses the mimetypes library to guess. """ if hasattr(content, "content_type"): content_type = content.content_type else: mime_type, encoding = mimetypes.guess_type(name) content_t...
[ "def", "get_content_type", "(", "name", ",", "content", ")", ":", "if", "hasattr", "(", "content", ",", "\"content_type\"", ")", ":", "content_type", "=", "content", ".", "content_type", "else", ":", "mime_type", ",", "encoding", "=", "mimetypes", ".", "gues...
31.727273
8.636364
def hasPESignature(self, rd): """ Check for PE signature. @type rd: L{ReadData} @param rd: A L{ReadData} object. @rtype: bool @return: True is the given L{ReadData} stream has the PE signature. Otherwise, False. """ rd.setOffset(0) e_lfanew_offse...
[ "def", "hasPESignature", "(", "self", ",", "rd", ")", ":", "rd", ".", "setOffset", "(", "0", ")", "e_lfanew_offset", "=", "unpack", "(", "\"<L\"", ",", "rd", ".", "readAt", "(", "0x3c", ",", "4", ")", ")", "[", "0", "]", "sign", "=", "rd", ".", ...
28.75
17.5
def target_types_for_alias(self, alias): """Returns all the target types that might be produced by the given alias. Normally there is 1 target type per alias, but macros can expand a single alias to several target types. :param string alias: The alias to look up associated target types for. :retur...
[ "def", "target_types_for_alias", "(", "self", ",", "alias", ")", ":", "registered_aliases", "=", "self", ".", "context", ".", "build_configuration", ".", "registered_aliases", "(", ")", "target_types", "=", "registered_aliases", ".", "target_types_by_alias", ".", "g...
52.375
29.0625
def form_invalid(self, form, forms, open_tabs, position_form_default): """ Called if a form is invalid. Re-renders the context data with the data-filled forms and errors. """ # return self.render_to_response( self.get_context_data( form = form, forms = forms ) ) return self.rende...
[ "def", "form_invalid", "(", "self", ",", "form", ",", "forms", ",", "open_tabs", ",", "position_form_default", ")", ":", "# return self.render_to_response( self.get_context_data( form = form, forms = forms ) )", "return", "self", ".", "render_to_response", "(", "self", ".",...
73.5
43.166667
def getreference(self, validate=True): """Returns and validates the Text Content's reference. Raises UnresolvableTextContent when invalid""" if self.offset is None: return None #nothing to test if self.ref: ref = self.doc[self.ref] else: ref = self.finddefaultref...
[ "def", "getreference", "(", "self", ",", "validate", "=", "True", ")", ":", "if", "self", ".", "offset", "is", "None", ":", "return", "None", "#nothing to test", "if", "self", ".", "ref", ":", "ref", "=", "self", ".", "doc", "[", "self", ".", "ref", ...
59
38.166667
def abort_all_pending_sis_imports(self, account_id): """ Abort all pending SIS imports. Abort already created but not processed or processing SIS imports. """ path = {} data = {} params = {} # REQUIRED - PATH - account_id """ID""" ...
[ "def", "abort_all_pending_sis_imports", "(", "self", ",", "account_id", ")", ":", "path", "=", "{", "}", "data", "=", "{", "}", "params", "=", "{", "}", "# REQUIRED - PATH - account_id\r", "\"\"\"ID\"\"\"", "path", "[", "\"account_id\"", "]", "=", "account_id", ...
42.25
30.0625
def set_float_param(params, name, value, min=None, max=None): """ Set a float parameter if applicable. :param dict params: A dict containing API call parameters. :param str name: The name of the parameter to set. :param float value: The value of the parameter. If ``None``, the field will ...
[ "def", "set_float_param", "(", "params", ",", "name", ",", "value", ",", "min", "=", "None", ",", "max", "=", "None", ")", ":", "if", "value", "is", "None", ":", "return", "try", ":", "value", "=", "float", "(", "str", "(", "value", ")", ")", "ex...
31.658537
22.341463
def mail(ui, repo, *pats, **opts): """mail a change for review Uploads a patch to the code review server and then sends mail to the reviewer and CC list asking for a review. """ if codereview_disabled: raise hg_util.Abort(codereview_disabled) cl, err = CommandLineCL(ui, repo, pats, opts, op="mail", defaultcc=...
[ "def", "mail", "(", "ui", ",", "repo", ",", "*", "pats", ",", "*", "*", "opts", ")", ":", "if", "codereview_disabled", ":", "raise", "hg_util", ".", "Abort", "(", "codereview_disabled", ")", "cl", ",", "err", "=", "CommandLineCL", "(", "ui", ",", "re...
30.892857
17.607143
def get_scope_path(cls, scope_separator="::"): """ Generate a string that represents this enum's declaration namespace scope. Parameters ---------- scope_separator: str Override the separator between namespace scopes """ if cls.get_parent_scop...
[ "def", "get_scope_path", "(", "cls", ",", "scope_separator", "=", "\"::\"", ")", ":", "if", "cls", ".", "get_parent_scope", "(", ")", "is", "None", ":", "return", "\"\"", "elif", "isinstance", "(", "cls", ".", "get_parent_scope", "(", ")", ",", "comp", "...
32.375
17.708333
def fetch(self, url, callback=None, raise_error=True, **kwargs): """ Fetch the given url and fire the callback when ready. Optionally pass a `streaming_callback` to handle data from large requests. Parameters ---------- url: string The url to access....
[ "def", "fetch", "(", "self", ",", "url", ",", "callback", "=", "None", ",", "raise_error", "=", "True", ",", "*", "*", "kwargs", ")", ":", "app", "=", "BridgedApplication", ".", "instance", "(", ")", "f", "=", "app", ".", "create_future", "(", ")", ...
33.3
17.9
def mgd(self, mgdid=None, hgnc_symbol=None, hgnc_identifier=None, limit=None, as_df=False): """Method to query :class:`.models.MGD` objects in database :param mgdid: Mouse genome informatics database ID(s) :type mgdid: str or tuple(str) or None :param hgnc_symbol: HGNC symbol(s) ...
[ "def", "mgd", "(", "self", ",", "mgdid", "=", "None", ",", "hgnc_symbol", "=", "None", ",", "hgnc_identifier", "=", "None", ",", "limit", "=", "None", ",", "as_df", "=", "False", ")", ":", "q", "=", "self", ".", "session", ".", "query", "(", "model...
38.65
24.5
def natural_name(self, value): """Set natural name.""" if value is None: value = "" if hasattr(self, "_natural_name") and self.name != "/": keys = [k for k in self._instances.keys() if k.startswith(self.fullpath)] dskeys = [k for k in Dataset._instances.keys()...
[ "def", "natural_name", "(", "self", ",", "value", ")", ":", "if", "value", "is", "None", ":", "value", "=", "\"\"", "if", "hasattr", "(", "self", ",", "\"_natural_name\"", ")", "and", "self", ".", "name", "!=", "\"/\"", ":", "keys", "=", "[", "k", ...
47.066667
16.866667
def get_imageid(vm_): ''' Returns the ImageId to use ''' image = config.get_cloud_config_value( 'image', vm_, __opts__, search_global=False ) if image.startswith('ami-'): return image # a poor man's cache if not hasattr(get_imageid, 'images'): get_imageid.images =...
[ "def", "get_imageid", "(", "vm_", ")", ":", "image", "=", "config", ".", "get_cloud_config_value", "(", "'image'", ",", "vm_", ",", "__opts__", ",", "search_global", "=", "False", ")", "if", "image", ".", "startswith", "(", "'ami-'", ")", ":", "return", ...
39.08
15.96
def listdir(*paths, glob=None): ''' List the (optionally glob filtered) full paths from a dir. Args: *paths ([str,...]): A list of path elements glob (str): An optional fnmatch glob str ''' path = genpath(*paths) names = os.listdir(path) if glob is not None: names =...
[ "def", "listdir", "(", "*", "paths", ",", "glob", "=", "None", ")", ":", "path", "=", "genpath", "(", "*", "paths", ")", "names", "=", "os", ".", "listdir", "(", "path", ")", "if", "glob", "is", "not", "None", ":", "names", "=", "fnmatch", ".", ...
25.375
22
def validator(ch): """ Update screen if necessary and release the lock so receiveThread can run """ global screen_needs_update try: if screen_needs_update: curses.doupdate() screen_needs_update = False return ch finally: winlock.release() s...
[ "def", "validator", "(", "ch", ")", ":", "global", "screen_needs_update", "try", ":", "if", "screen_needs_update", ":", "curses", ".", "doupdate", "(", ")", "screen_needs_update", "=", "False", "return", "ch", "finally", ":", "winlock", ".", "release", "(", ...
27.071429
15.5
def _estimate_strains(self): """Compute an estimate of the strains.""" # Estimate the strain based on the PGV and shear-wave velocity for l in self._profile: l.reset() l.strain = self._motion.pgv / l.initial_shear_vel
[ "def", "_estimate_strains", "(", "self", ")", ":", "# Estimate the strain based on the PGV and shear-wave velocity", "for", "l", "in", "self", ".", "_profile", ":", "l", ".", "reset", "(", ")", "l", ".", "strain", "=", "self", ".", "_motion", ".", "pgv", "/", ...
43.333333
15.166667
def _set_ldp_eol(self, v, load=False): """ Setter method for ldp_eol, mapped from YANG variable /mpls_config/router/mpls/mpls_cmds_holder/ldp/ldp_holder/ldp_eol (container) If this variable is read-only (config: false) in the source YANG file, then _set_ldp_eol is considered as a private method. Bac...
[ "def", "_set_ldp_eol", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", "v", ",", "base",...
87.681818
42
def value(self, dcode, dextra): """Decode value of symbol together with the extra bits. >>> d = DistanceAlphabet('D', NPOSTFIX=2, NDIRECT=10) >>> d[34].value(2) (0, 35) """ if dcode<16: return [(1,0),(2,0),(3,0),(4,0), (1,-1),(1,+1),(1,-2),...
[ "def", "value", "(", "self", ",", "dcode", ",", "dextra", ")", ":", "if", "dcode", "<", "16", ":", "return", "[", "(", "1", ",", "0", ")", ",", "(", "2", ",", "0", ")", ",", "(", "3", ",", "0", ")", ",", "(", "4", ",", "0", ")", ",", ...
45.47619
16.52381
def list_all_promotions(cls, **kwargs): """List Promotions Return a list of Promotions This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.list_all_promotions(async=True) >>> result = thre...
[ "def", "list_all_promotions", "(", "cls", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async'", ")", ":", "return", "cls", ".", "_list_all_promotions_with_http_info", "(", ...
36.782609
14.652174
def dispatch_event(self, event): """ Takes an event dict. Logs the event if needed and cleans up the dict such as setting the index needed for composits. """ if self.config["debug"]: self.py3_wrapper.log("received event {}".format(event)) # usage variables ...
[ "def", "dispatch_event", "(", "self", ",", "event", ")", ":", "if", "self", ".", "config", "[", "\"debug\"", "]", ":", "self", ".", "py3_wrapper", ".", "log", "(", "\"received event {}\"", ".", "format", "(", "event", ")", ")", "# usage variables", "event"...
37.727273
16.490909
def view(self, repo): """ View repository information """ status = "{0}disabled{1}".format(self.meta.color["RED"], self.meta.color["ENDC"]) self.form["Status:"] = status self.form["Default:"] = "no" if repo in self.meta.def...
[ "def", "view", "(", "self", ",", "repo", ")", ":", "status", "=", "\"{0}disabled{1}\"", ".", "format", "(", "self", ".", "meta", ".", "color", "[", "\"RED\"", "]", ",", "self", ".", "meta", ".", "color", "[", "\"ENDC\"", "]", ")", "self", ".", "for...
49.961538
15.576923
def summary(args): """ %prog summary gffile Print summary stats for features of different types. """ from jcvi.formats.base import SetFile from jcvi.formats.bed import BedSummary from jcvi.utils.table import tabulate p = OptionParser(summary.__doc__) p.add_option("--isoform", defau...
[ "def", "summary", "(", "args", ")", ":", "from", "jcvi", ".", "formats", ".", "base", "import", "SetFile", "from", "jcvi", ".", "formats", ".", "bed", "import", "BedSummary", "from", "jcvi", ".", "utils", ".", "table", "import", "tabulate", "p", "=", "...
29.530303
18.227273
def connect(self): """ Hook up the moderation methods to pre- and post-save signals from the comment models. """ signals.comment_will_be_posted.connect(self.pre_save_moderation, sender=comments.get_model()) signals.comment_was_posted.connect(self.post_save_moderation, se...
[ "def", "connect", "(", "self", ")", ":", "signals", ".", "comment_will_be_posted", ".", "connect", "(", "self", ".", "pre_save_moderation", ",", "sender", "=", "comments", ".", "get_model", "(", ")", ")", "signals", ".", "comment_was_posted", ".", "connect", ...
42.375
27.125
def generate_wave(message, wpm=WPM, framerate=FRAMERATE, skip_frame=0, amplitude=AMPLITUDE, frequency=FREQUENCY, word_ref=WORD): """ Generate binary Morse code of message at a given code speed wpm and framerate Parameters ---------- word : string wpm : int or float - word per minute framera...
[ "def", "generate_wave", "(", "message", ",", "wpm", "=", "WPM", ",", "framerate", "=", "FRAMERATE", ",", "skip_frame", "=", "0", ",", "amplitude", "=", "AMPLITUDE", ",", "frequency", "=", "FREQUENCY", ",", "word_ref", "=", "WORD", ")", ":", "lst_bin", "=...
35.851852
25.925926
def reset_small(self, eq): """Reset numbers smaller than 1e-12 in f and g equations""" assert eq in ('f', 'g') for idx, var in enumerate(self.__dict__[eq]): if abs(var) <= 1e-12: self.__dict__[eq][idx] = 0
[ "def", "reset_small", "(", "self", ",", "eq", ")", ":", "assert", "eq", "in", "(", "'f'", ",", "'g'", ")", "for", "idx", ",", "var", "in", "enumerate", "(", "self", ".", "__dict__", "[", "eq", "]", ")", ":", "if", "abs", "(", "var", ")", "<=", ...
42
7.5
def to_dict(self): """ Convert the tree node to its dictionary representation. :return: an expansion dictionary that represents the type and expansions of this tree node. :rtype dict[list[union[str, unicode]]] """ expansion_strings = [] for expansion in self.exp...
[ "def", "to_dict", "(", "self", ")", ":", "expansion_strings", "=", "[", "]", "for", "expansion", "in", "self", ".", "expansions", ":", "expansion_strings", ".", "extend", "(", "expansion", ".", "to_strings", "(", ")", ")", "return", "{", "self", ".", "ty...
29.666667
21.133333
def tenant_provisioned(tenant_id): """Returns true if any networks or ports exist for a tenant.""" session = db.get_reader_session() with session.begin(): res = any( session.query(m).filter(m.tenant_id == tenant_id).count() for m in [models_v2.Network, models_v2.Port] ...
[ "def", "tenant_provisioned", "(", "tenant_id", ")", ":", "session", "=", "db", ".", "get_reader_session", "(", ")", "with", "session", ".", "begin", "(", ")", ":", "res", "=", "any", "(", "session", ".", "query", "(", "m", ")", ".", "filter", "(", "m...
36.555556
16.444444
def set_transmitters(transmitters, device=None, address=None): """ All parameters are passed to irsend. See the man page for irsend for details about their usage. Parameters ---------- transmitters: iterable yielding ints device: str address: str Notes ----- No attempt is m...
[ "def", "set_transmitters", "(", "transmitters", ",", "device", "=", "None", ",", "address", "=", "None", ")", ":", "args", "=", "[", "'set_transmitters'", "]", "+", "[", "str", "(", "i", ")", "for", "i", "in", "transmitters", "]", "_call", "(", "args",...
28.631579
22.736842
def show_raslog_output_show_all_raslog_rbridge_id(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") show_raslog = ET.Element("show_raslog") config = show_raslog output = ET.SubElement(show_raslog, "output") show_all_raslog = ET.SubElement(o...
[ "def", "show_raslog_output_show_all_raslog_rbridge_id", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "show_raslog", "=", "ET", ".", "Element", "(", "\"show_raslog\"", ")", "config", "=", "show_ras...
41.615385
14.461538
def add_virtual_columns_cartesian_to_polar(self, x="x", y="y", radius_out="r_polar", azimuth_out="phi_polar", propagate_uncertainties=False, radians=False): """Convert cartesian to polar coordinates :param x: ...
[ "def", "add_virtual_columns_cartesian_to_polar", "(", "self", ",", "x", "=", "\"x\"", ",", "y", "=", "\"y\"", ",", "radius_out", "=", "\"r_polar\"", ",", "azimuth_out", "=", "\"phi_polar\"", ",", "propagate_uncertainties", "=", "False", ",", "radians", "=", "Fal...
40.740741
20.222222
def run_forecast(self): """ Updates card & runs for RAPID to GSSHA & LSM to GSSHA """ # ---------------------------------------------------------------------- # LSM to GSSHA # ---------------------------------------------------------------------- self.prepare_hme...
[ "def", "run_forecast", "(", "self", ")", ":", "# ----------------------------------------------------------------------", "# LSM to GSSHA", "# ----------------------------------------------------------------------", "self", ".", "prepare_hmet", "(", ")", "self", ".", "prepare_gag", ...
38.36
26.6
def statustext_send(self, severity, text, force_mavlink1=False): ''' Status text message. These messages are printed in yellow in the COMM console of QGroundControl. WARNING: They consume quite some bandwidth, so use only for important status and ...
[ "def", "statustext_send", "(", "self", ",", "severity", ",", "text", ",", "force_mavlink1", "=", "False", ")", ":", "return", "self", ".", "send", "(", "self", ".", "statustext_encode", "(", "severity", ",", "text", ")", ",", "force_mavlink1", "=", "force_...
60.142857
38.428571
def add_scalar_summary(self, x, tag=None): """Adds a scalar summary for x.""" if not self.summary_collections: return with self.g.as_default(): tag = tag or _tag_for(x.name) summary = (tf.summary.scalar( tag, x, collections=self.summary_collections)) return summary
[ "def", "add_scalar_summary", "(", "self", ",", "x", ",", "tag", "=", "None", ")", ":", "if", "not", "self", ".", "summary_collections", ":", "return", "with", "self", ".", "g", ".", "as_default", "(", ")", ":", "tag", "=", "tag", "or", "_tag_for", "(...
33.666667
10.111111
def jsonp(func): """Wraps JSONified output for JSONP requests.""" @wraps(func) def decorated(*args, **kwargs): callback = request.args.get('callback', False) if callback: data = str(func(*args, **kwargs).data) content = str(callback) + '(' + data + ')' mim...
[ "def", "jsonp", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "decorated", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "callback", "=", "request", ".", "args", ".", "get", "(", "'callback'", ",", "False", ")", "if", "call...
37.692308
15.230769
def _image_channel_compress_bottom(inputs, model_hparams, name="bottom"): """Compresses channel-wise input pixels into whole pixel representions. Perform conversion of RGB pixel values to a real number in the range -1 to 1. This combines pixel channels to form a representation of shape [img_len, img_len]. A...
[ "def", "_image_channel_compress_bottom", "(", "inputs", ",", "model_hparams", ",", "name", "=", "\"bottom\"", ")", ":", "num_channels", "=", "3", "with", "tf", ".", "variable_scope", "(", "name", ")", ":", "inputs", "=", "tf", ".", "to_float", "(", "inputs",...
34.72093
20.069767
def write(histogram): """Convert a histogram to a protobuf message. Note: Currently, all binnings are converted to static form. When you load the histogram again, you will lose any related behaviour. Note: A histogram collection is also planned. Parameters ---------- histogram...
[ "def", "write", "(", "histogram", ")", ":", "histogram_dict", "=", "histogram", ".", "to_dict", "(", ")", "message", "=", "Histogram", "(", ")", "for", "field", "in", "SIMPLE_CONVERSION_FIELDS", ":", "setattr", "(", "message", ",", "field", ",", "histogram_d...
30.54717
17
def write(self, iterable): """Writes values from iterable into CSV file""" io_error_text = _("Error writing to file {filepath}.") io_error_text = io_error_text.format(filepath=self.path) try: with open(self.path, "wb") as csvfile: csv_writer = csv.writer(cs...
[ "def", "write", "(", "self", ",", "iterable", ")", ":", "io_error_text", "=", "_", "(", "\"Error writing to file {filepath}.\"", ")", "io_error_text", "=", "io_error_text", ".", "format", "(", "filepath", "=", "self", ".", "path", ")", "try", ":", "with", "o...
33.076923
22.807692
def backprop(self, input_data, targets, cache=None): """Compute gradients for each task and combine the results. **Parameters:** input_data : ``GPUArray`` Inpute data to compute activations for. targets : ``GPUArray`` The target values of the units. ca...
[ "def", "backprop", "(", "self", ",", "input_data", ",", "targets", ",", "cache", "=", "None", ")", ":", "df_input", "=", "gpuarray", ".", "zeros_like", "(", "input_data", ")", "if", "cache", "is", "None", ":", "cache", "=", "self", ".", "n_tasks", "*",...
32.142857
22.095238
def to_dict(obj): """Generate a JSON serialization for the run state object. Returns ------- Json-like object Json serialization of model run state object """ # Have text description of state in Json object (for readability) json_obj = {'type' : repr(...
[ "def", "to_dict", "(", "obj", ")", ":", "# Have text description of state in Json object (for readability)", "json_obj", "=", "{", "'type'", ":", "repr", "(", "obj", ")", "}", "# Add state-specific elementsTYPE_MODEL_RUN", "if", "obj", ".", "is_failed", ":", "json_obj",...
33.75
15.6875
def get_vector(self): """Return the vector for this survey.""" vec = {} for dim in ['forbidden', 'required', 'permitted']: if self.survey[dim] is None: continue dim_vec = map(lambda x: (x['tag'], x['answer']), self.survey[dim]) ...
[ "def", "get_vector", "(", "self", ")", ":", "vec", "=", "{", "}", "for", "dim", "in", "[", "'forbidden'", ",", "'required'", ",", "'permitted'", "]", ":", "if", "self", ".", "survey", "[", "dim", "]", "is", "None", ":", "continue", "dim_vec", "=", ...
36.5
12.7
def from_cdms2(variable): """Convert a cdms2 variable into an DataArray """ values = np.asarray(variable) name = variable.id dims = variable.getAxisIds() coords = {} for axis in variable.getAxisList(): coords[axis.id] = DataArray( np.asarray(axis), dims=[axis.id], ...
[ "def", "from_cdms2", "(", "variable", ")", ":", "values", "=", "np", ".", "asarray", "(", "variable", ")", "name", "=", "variable", ".", "id", "dims", "=", "variable", ".", "getAxisIds", "(", ")", "coords", "=", "{", "}", "for", "axis", "in", "variab...
43
12.916667
async def write( self, data: Union[PointType, Iterable[PointType]], measurement: Optional[str] = None, db: Optional[str] = None, precision: Optional[str] = None, rp: Optional[str] = None, tag_columns: Optional[Iterable] = None, **extra_tags, ) -> bool:...
[ "async", "def", "write", "(", "self", ",", "data", ":", "Union", "[", "PointType", ",", "Iterable", "[", "PointType", "]", "]", ",", "measurement", ":", "Optional", "[", "str", "]", "=", "None", ",", "db", ":", "Optional", "[", "str", "]", "=", "No...
48.607143
21.285714
def get_plate_list(self, market, plate_class): """ 获取板块集合下的子板块列表 :param market: 市场标识,注意这里不区分沪,深,输入沪或者深都会返回沪深市场的子板块(这个是和客户端保持一致的)参见Market :param plate_class: 板块分类,参见Plate :return: ret == RET_OK 返回pd dataframe数据,data.DataFrame数据, 数据列格式如下 ret != RET_OK 返回错误字符串 ...
[ "def", "get_plate_list", "(", "self", ",", "market", ",", "plate_class", ")", ":", "param_table", "=", "{", "'market'", ":", "market", ",", "'plate_class'", ":", "plate_class", "}", "for", "x", "in", "param_table", ":", "param", "=", "param_table", "[", "x...
41.8
24.12
def get_listener_count(self): """Returns the number of listeners on the network""" return _number( _extract( self._request(self.ws_prefix + ".getInfo", cacheable=True), "listeners" ) )
[ "def", "get_listener_count", "(", "self", ")", ":", "return", "_number", "(", "_extract", "(", "self", ".", "_request", "(", "self", ".", "ws_prefix", "+", "\".getInfo\"", ",", "cacheable", "=", "True", ")", ",", "\"listeners\"", ")", ")" ]
30.25
24
def makefile(self, mode='r', bufsize=-1): 'return a file-like object that operates on the ssl connection' sockfile = gsock.SocketFile.__new__(gsock.SocketFile) gfiles.FileBase.__init__(sockfile) sockfile._sock = self sockfile.mode = mode if bufsize > 0: sockfi...
[ "def", "makefile", "(", "self", ",", "mode", "=", "'r'", ",", "bufsize", "=", "-", "1", ")", ":", "sockfile", "=", "gsock", ".", "SocketFile", ".", "__new__", "(", "gsock", ".", "SocketFile", ")", "gfiles", ".", "FileBase", ".", "__init__", "(", "soc...
39.777778
12.444444
def QueryInfoKey(key): """This calls the Windows RegQueryInfoKey function in a Unicode safe way.""" regqueryinfokey = advapi32["RegQueryInfoKeyW"] regqueryinfokey.restype = ctypes.c_long regqueryinfokey.argtypes = [ ctypes.c_void_p, ctypes.c_wchar_p, LPDWORD, LPDWORD, LPDWORD, LPDWORD, LPDWORD, LPDW...
[ "def", "QueryInfoKey", "(", "key", ")", ":", "regqueryinfokey", "=", "advapi32", "[", "\"RegQueryInfoKeyW\"", "]", "regqueryinfokey", ".", "restype", "=", "ctypes", ".", "c_long", "regqueryinfokey", ".", "argtypes", "=", "[", "ctypes", ".", "c_void_p", ",", "c...
38.68
18.68
def area_poly_sphere(lat, lon, r_sphere): ''' Calculates the area enclosed by an arbitrary polygon on the sphere. Parameters ---------- lat : iterable The latitudes, in degrees, of the vertex locations of the polygon, in clockwise order. lon : iterable The longitudes, in degrees, of the vertex locatio...
[ "def", "area_poly_sphere", "(", "lat", ",", "lon", ",", "r_sphere", ")", ":", "dtr", "=", "np", ".", "pi", "/", "180.", "def", "_tranlon", "(", "plat", ",", "plon", ",", "qlat", ",", "qlon", ")", ":", "t", "=", "np", ".", "sin", "(", "(", "qlon...
27.264151
25.037736
def _validate_tools(self, tool): """ Use tool_supported or tool """ tools = [] if not tool: if len(self.project['common']['tools_supported']) == 0: logger.info("No tool defined.") return -1 tools = self.project['common']['tools_supported']...
[ "def", "_validate_tools", "(", "self", ",", "tool", ")", ":", "tools", "=", "[", "]", "if", "not", "tool", ":", "if", "len", "(", "self", ".", "project", "[", "'common'", "]", "[", "'tools_supported'", "]", ")", "==", "0", ":", "logger", ".", "info...
30.916667
18.416667
def rpc_fix_code(self, source, directory): """Formats Python code to conform to the PEP 8 style guide. """ source = get_source(source) return fix_code(source, directory)
[ "def", "rpc_fix_code", "(", "self", ",", "source", ",", "directory", ")", ":", "source", "=", "get_source", "(", "source", ")", "return", "fix_code", "(", "source", ",", "directory", ")" ]
32.833333
8.166667
def workflow_stages(self) -> List[WorkflowStage]: """Return list of workflow stages. Returns: dict, resources of a specified pb """ workflow_stages = [] stages = DB.get_hash_value(self.key, 'workflow_stages') for index in range(len(ast.literal_eval(stages)))...
[ "def", "workflow_stages", "(", "self", ")", "->", "List", "[", "WorkflowStage", "]", ":", "workflow_stages", "=", "[", "]", "stages", "=", "DB", ".", "get_hash_value", "(", "self", ".", "key", ",", "'workflow_stages'", ")", "for", "index", "in", "range", ...
33.916667
17.166667
def _merge_DC_to_base(self, X_DC, X_base, no_DC): """ Merge DC components X_DC to the baseline time series X_base (By baseline, this means any fixed nuisance regressors not updated during fitting, including DC components and any nuisance regressors provided by the...
[ "def", "_merge_DC_to_base", "(", "self", ",", "X_DC", ",", "X_base", ",", "no_DC", ")", ":", "if", "X_base", "is", "not", "None", ":", "reg_sol", "=", "np", ".", "linalg", ".", "lstsq", "(", "X_DC", ",", "X_base", ")", "if", "not", "no_DC", ":", "i...
52.764706
20.735294
def lc_score(value): """ Evaluates the accuracy of a predictive measure (e.g. r-squared) :param value: float, between 0.0 and 1.0. :return: """ rebased = 2 * (value - 0.5) if rebased == 0: return 0 elif rebased > 0: compliment = 1.0 - rebased score = - np.log2(c...
[ "def", "lc_score", "(", "value", ")", ":", "rebased", "=", "2", "*", "(", "value", "-", "0.5", ")", "if", "rebased", "==", "0", ":", "return", "0", "elif", "rebased", ">", "0", ":", "compliment", "=", "1.0", "-", "rebased", "score", "=", "-", "np...
22.833333
17.055556
def config_dir(self): "Return dir(self)." my_vars = set(self) skips = self.bad_names | my_vars yield from ( attr for attr in dir(type(self)) if ( attr not in skips and not ( attr.startswith('_') and...
[ "def", "config_dir", "(", "self", ")", ":", "my_vars", "=", "set", "(", "self", ")", "skips", "=", "self", ".", "bad_names", "|", "my_vars", "yield", "from", "(", "attr", "for", "attr", "in", "dir", "(", "type", "(", "self", ")", ")", "if", "(", ...
24.45
17.25
def _run_toil(args): """Run CWL with Toil. """ main_file, json_file, project_name = _get_main_and_json(args.directory) work_dir = utils.safe_makedir(os.path.join(os.getcwd(), "toil_work")) tmp_dir = utils.safe_makedir(os.path.join(work_dir, "tmpdir")) os.environ["TMPDIR"] = tmp_dir log_file ...
[ "def", "_run_toil", "(", "args", ")", ":", "main_file", ",", "json_file", ",", "project_name", "=", "_get_main_and_json", "(", "args", ".", "directory", ")", "work_dir", "=", "utils", ".", "safe_makedir", "(", "os", ".", "path", ".", "join", "(", "os", "...
47.038462
16.653846
def _transform_from_pauli(data, num_qubits): """Change of basis of bipartite matrix represenation.""" # Change basis: sum_{i=0}^3 =|\sigma_i>><i| basis_mat = np.array( [[1, 0, 0, 1], [0, 1, 1j, 0], [0, 1, -1j, 0], [1, 0j, 0, -1]], dtype=complex) # Note that we manually renormalized after...
[ "def", "_transform_from_pauli", "(", "data", ",", "num_qubits", ")", ":", "# Change basis: sum_{i=0}^3 =|\\sigma_i>><i|", "basis_mat", "=", "np", ".", "array", "(", "[", "[", "1", ",", "0", ",", "0", ",", "1", "]", ",", "[", "0", ",", "1", ",", "1j", "...
44.823529
16.117647
def get_arguments(self): """Return an iterator for accessing the arguments of this cursor.""" num_args = conf.lib.clang_Cursor_getNumArguments(self) for i in xrange(0, num_args): yield conf.lib.clang_Cursor_getArgument(self, i)
[ "def", "get_arguments", "(", "self", ")", ":", "num_args", "=", "conf", ".", "lib", ".", "clang_Cursor_getNumArguments", "(", "self", ")", "for", "i", "in", "xrange", "(", "0", ",", "num_args", ")", ":", "yield", "conf", ".", "lib", ".", "clang_Cursor_ge...
51.8
12.2
def from_project_path(cls, path): """Utility for finding a virtualenv location based on a project path""" path = vistir.compat.Path(path) if path.name == 'Pipfile': pipfile_path = path path = path.parent else: pipfile_path = path / 'Pipfile' pi...
[ "def", "from_project_path", "(", "cls", ",", "path", ")", ":", "path", "=", "vistir", ".", "compat", ".", "Path", "(", "path", ")", "if", "path", ".", "name", "==", "'Pipfile'", ":", "pipfile_path", "=", "path", "path", "=", "path", ".", "parent", "e...
47.583333
14.375
def to_str(obj): """ convert a object to string """ if isinstance(obj, str): return obj if isinstance(obj, unicode): return obj.encode('utf-8') return str(obj)
[ "def", "to_str", "(", "obj", ")", ":", "if", "isinstance", "(", "obj", ",", "str", ")", ":", "return", "obj", "if", "isinstance", "(", "obj", ",", "unicode", ")", ":", "return", "obj", ".", "encode", "(", "'utf-8'", ")", "return", "str", "(", "obj"...
21.222222
11.444444
def install(self, plugin): ''' Add a plugin to the list of plugins and prepare it for beeing applied to all routes of this application. A plugin may be a simple decorator or an object that implements the :class:`Plugin` API. ''' if hasattr(plugin, 'setup'): plugin.setup(s...
[ "def", "install", "(", "self", ",", "plugin", ")", ":", "if", "hasattr", "(", "plugin", ",", "'setup'", ")", ":", "plugin", ".", "setup", "(", "self", ")", "if", "not", "callable", "(", "plugin", ")", "and", "not", "hasattr", "(", "plugin", ",", "'...
48.818182
24.636364
def add_photo(self, collection_id, photo_id): """ Add a photo to one of the logged-in user’s collections. Requires the 'write_collections' scope. Note: If the photo is already in the collection, this acion has no effect. :param collection_id [string]: The collection’s ID. Requi...
[ "def", "add_photo", "(", "self", ",", "collection_id", ",", "photo_id", ")", ":", "url", "=", "\"/collections/%s/add\"", "%", "collection_id", "data", "=", "{", "\"collection_id\"", ":", "collection_id", ",", "\"photo_id\"", ":", "photo_id", "}", "result", "=", ...
41.5
20.611111
def get_after(self, timestamp, s=None): """ Find all the (available) logs that are after the given time stamp. If `s` is not supplied, then all lines are used. Otherwise, only the lines contain the `s` are used. `s` can be either a single string or a string list. For list, all...
[ "def", "get_after", "(", "self", ",", "timestamp", ",", "s", "=", "None", ")", ":", "time_format", "=", "self", ".", "time_format", "# Annoyingly, strptime insists that it get the whole time string and", "# nothing but the time string. However, for most logs we only have a", "...
48.865591
23.962366
def merge_component_types(self, ct, base_ct): """ Merge various maps in the given component type from a base component type. @param ct: Component type to be resolved. @type ct: lems.model.component.ComponentType @param base_ct: Component type to be resolved. @t...
[ "def", "merge_component_types", "(", "self", ",", "ct", ",", "base_ct", ")", ":", "#merge_maps(ct.parameters, base_ct.parameters)", "for", "parameter", "in", "base_ct", ".", "parameters", ":", "if", "parameter", ".", "name", "in", "ct", ".", "parameters", ":", "...
50.338983
25.457627
def remote_styles(family_metadata): """Get a dictionary of TTFont objects of all font files of a given family as currently hosted at Google Fonts. """ def download_family_from_Google_Fonts(family_name): """Return a zipfile containing a font family hosted on fonts.google.com""" from zipfile import Zi...
[ "def", "remote_styles", "(", "family_metadata", ")", ":", "def", "download_family_from_Google_Fonts", "(", "family_name", ")", ":", "\"\"\"Return a zipfile containing a font family hosted on fonts.google.com\"\"\"", "from", "zipfile", "import", "ZipFile", "from", "fontbakery", ...
34.894737
17.131579
def bisect(seq, func=bool): """ Split a sequence into two sequences: the first is elements that return False for func(element) and the second for True for func(element). By default, func is ``bool``, so uses the truth value of the object. >>> is_odd = lambda n: n%2 >>> even, odd = bisect(range(5), is_odd) >>>...
[ "def", "bisect", "(", "seq", ",", "func", "=", "bool", ")", ":", "queues", "=", "GroupbySaved", "(", "seq", ",", "func", ")", "return", "queues", ".", "get_first_n_queues", "(", "2", ")" ]
22.652174
21.173913
def dispatch(self, request, *args, **kwargs): """Dispatch all HTTP methods to the proxy.""" self.request = DownstreamRequest(request) self.args = args self.kwargs = kwargs self._verify_config() self.middleware = MiddlewareSet(self.proxy_middleware) return self....
[ "def", "dispatch", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "request", "=", "DownstreamRequest", "(", "request", ")", "self", ".", "args", "=", "args", "self", ".", "kwargs", "=", "kwargs", "self"...
28.818182
18.909091
def get_bank_ids_by_assessment_offered(self, assessment_offered_id): """Gets the list of ``Bank`` ``Ids`` mapped to an ``AssessmentOffered``. arg: assessment_offered_id (osid.id.Id): ``Id`` of an ``AssessmentOffered`` return: (osid.id.IdList) - list of bank ``Ids`` r...
[ "def", "get_bank_ids_by_assessment_offered", "(", "self", ",", "assessment_offered_id", ")", ":", "# Implemented from template for", "# osid.resource.ResourceBinSession.get_bin_ids_by_resource", "mgr", "=", "self", ".", "_get_provider_manager", "(", "'ASSESSMENT'", ",", "local", ...
51.652174
21.304348
def handle_label_relation(self, line: str, position: int, tokens: ParseResults) -> ParseResults: """Handle statements like ``p(X) label "Label for X"``. :raises: RelabelWarning """ subject_node_dsl = self.ensure_node(tokens[SUBJECT]) description = tokens[OBJECT] if self...
[ "def", "handle_label_relation", "(", "self", ",", "line", ":", "str", ",", "position", ":", "int", ",", "tokens", ":", "ParseResults", ")", "->", "ParseResults", ":", "subject_node_dsl", "=", "self", ".", "ensure_node", "(", "tokens", "[", "SUBJECT", "]", ...
37.8
19.3
def can_user_run(self, user, command, groups): ''' Break out the permissions into the following: Check whether a user is in any group, including whether a group has the '*' membership :type user: str :param user: The username being checked against :type command: str ...
[ "def", "can_user_run", "(", "self", ",", "user", ",", "command", ",", "groups", ")", ":", "log", ".", "info", "(", "'%s wants to run %s with groups %s'", ",", "user", ",", "command", ",", "groups", ")", "for", "key", ",", "val", "in", "groups", ".", "ite...
42.542857
26.885714
def new_leaves(self, column_name): """ :param column_name: :return: ALL COLUMNS THAT START WITH column_name, INCLUDING DEEP COLUMNS """ column_name = unnest_path(column_name) columns = self.columns all_paths = self.snowflake.sorted_query_paths output = {}...
[ "def", "new_leaves", "(", "self", ",", "column_name", ")", ":", "column_name", "=", "unnest_path", "(", "column_name", ")", "columns", "=", "self", ".", "columns", "all_paths", "=", "self", ".", "snowflake", ".", "sorted_query_paths", "output", "=", "{", "}"...
38.65625
15.09375
def from_uncharted_json_file(cls, file): """ Construct an AnalysisGraph object from a file containing INDRA statements serialized exported by Uncharted's CauseMos webapp. """ with open(file, "r") as f: _dict = json.load(f) return cls.from_uncharted_json_serialized_dic...
[ "def", "from_uncharted_json_file", "(", "cls", ",", "file", ")", ":", "with", "open", "(", "file", ",", "\"r\"", ")", "as", "f", ":", "_dict", "=", "json", ".", "load", "(", "f", ")", "return", "cls", ".", "from_uncharted_json_serialized_dict", "(", "_di...
46
9.285714
def get_all_events(self, source_identifier=None, source_type=None, start_time=None, end_time=None, max_records=None, marker=None): """ Get information about events related to your DBInstances, DBSecurityGroups and DBParameterGroups. :type so...
[ "def", "get_all_events", "(", "self", ",", "source_identifier", "=", "None", ",", "source_type", "=", "None", ",", "start_time", "=", "None", ",", "end_time", "=", "None", ",", "max_records", "=", "None", ",", "marker", "=", "None", ")", ":", "params", "...
44.517857
21.910714
async def recv_event(self) -> Any: """\ Receives an event from the task. If the task terminates before another event, an exception is raised. A normal return is wrapped in a `Success` exception, other exceptions result in a `Failure` with the original exception as the cause. ...
[ "async", "def", "recv_event", "(", "self", ")", "->", "Any", ":", "try", ":", "return", "await", "self", ".", "_events", ".", "recv", "(", ")", "except", "EOFError", ":", "# component has terminated, raise the cause (either Failure, or LifecycleError) or Success", "ra...
46.5
19.583333
def geometry_identifiers(self): """ Look up geometries by identifier MD5 Returns --------- identifiers: dict, identifier md5: key in self.geometry """ identifiers = {mesh.identifier_md5: name for name, mesh in self.geometry.items()} ...
[ "def", "geometry_identifiers", "(", "self", ")", ":", "identifiers", "=", "{", "mesh", ".", "identifier_md5", ":", "name", "for", "name", ",", "mesh", "in", "self", ".", "geometry", ".", "items", "(", ")", "}", "return", "identifiers" ]
29.909091
15.363636
def get_cutout(self, clearance=0): " get the cutout for the shaft" return cq.Workplane('XY', origin=(0, 0, 0)) \ .circle((self.diam / 2) + clearance) \ .extrude(10)
[ "def", "get_cutout", "(", "self", ",", "clearance", "=", "0", ")", ":", "return", "cq", ".", "Workplane", "(", "'XY'", ",", "origin", "=", "(", "0", ",", "0", ",", "0", ")", ")", ".", "circle", "(", "(", "self", ".", "diam", "/", "2", ")", "+...
40
9.2
def add(self, connection): '''Add a connection''' key = (connection.host, connection.port) with self._lock: if key not in self._connections: self._connections[key] = connection self.added(connection) return connection else: ...
[ "def", "add", "(", "self", ",", "connection", ")", ":", "key", "=", "(", "connection", ".", "host", ",", "connection", ".", "port", ")", "with", "self", ".", "_lock", ":", "if", "key", "not", "in", "self", ".", "_connections", ":", "self", ".", "_c...
33.8
10.8
def sum_queryset(qs: QuerySet, key: str= 'amount', default=Decimal(0)) -> Decimal: """ Returns aggregate sum of queryset 'amount' field. :param qs: QuerySet :param key: Field to sum (default: 'amount') :param default: Default value if no results :return: Sum of 'amount' field values (coalesced 0...
[ "def", "sum_queryset", "(", "qs", ":", "QuerySet", ",", "key", ":", "str", "=", "'amount'", ",", "default", "=", "Decimal", "(", "0", ")", ")", "->", "Decimal", ":", "res", "=", "qs", ".", "aggregate", "(", "b", "=", "Sum", "(", "key", ")", ")", ...
41.1
11.3
def safe_rm_oldest_items_in_dir(root_dir, num_of_items_to_keep, excludes=frozenset()): """ Keep `num_of_items_to_keep` newly modified items besides `excludes` in `root_dir` then remove the rest. :param root_dir: the folder to examine :param num_of_items_to_keep: number of files/folders/symlinks to keep after th...
[ "def", "safe_rm_oldest_items_in_dir", "(", "root_dir", ",", "num_of_items_to_keep", ",", "excludes", "=", "frozenset", "(", ")", ")", ":", "if", "os", ".", "path", ".", "isdir", "(", "root_dir", ")", ":", "found_files", "=", "[", "]", "for", "old_file", "i...
48.705882
22.235294
def update_task_descriptor_content(self, courseid, taskid, content, force_extension=None): """ Update the task descriptor with the dict in content :param courseid: the course id of the course :param taskid: the task id of the task :param content: the content to put in the task fi...
[ "def", "update_task_descriptor_content", "(", "self", ",", "courseid", ",", "taskid", ",", "content", ",", "force_extension", "=", "None", ")", ":", "if", "not", "id_checker", "(", "courseid", ")", ":", "raise", "InvalidNameException", "(", "\"Course with invalid ...
50.384615
26.076923
def log_info(self, logger): """Print statistical information via the provided logger Parameters ---------- logger : logging.Logger logger created using logging.getLogger() """ logger.info('#words in training set: %d' % self._words_in_train_data) logge...
[ "def", "log_info", "(", "self", ",", "logger", ")", ":", "logger", ".", "info", "(", "'#words in training set: %d'", "%", "self", ".", "_words_in_train_data", ")", "logger", ".", "info", "(", "\"Vocab info: #words %d, #tags %d #rels %d\"", "%", "(", "self", ".", ...
41.1
22.8
def addcols(self, desc, dminfo={}, addtoparent=True): """Add one or more columns. Columns can always be added to a normal table. They can also be added to a reference table and optionally to its parent table. `desc` contains a description of the column(s) to be added....
[ "def", "addcols", "(", "self", ",", "desc", ",", "dminfo", "=", "{", "}", ",", "addtoparent", "=", "True", ")", ":", "tdesc", "=", "desc", "# Create a tabdesc if only a coldesc is given.", "if", "'name'", "in", "desc", ":", "import", "casacore", ".", "tables...
43.673469
24
def make_handler(f, remote, with_response=True): """Make a handler for authorized and disconnect callbacks. :param f: Callable or an import path to a callable """ if isinstance(f, six.string_types): f = import_string(f) @wraps(f) def inner(*args, **kwargs): if with_response: ...
[ "def", "make_handler", "(", "f", ",", "remote", ",", "with_response", "=", "True", ")", ":", "if", "isinstance", "(", "f", ",", "six", ".", "string_types", ")", ":", "f", "=", "import_string", "(", "f", ")", "@", "wraps", "(", "f", ")", "def", "inn...
29.266667
16
def split_args(self, args=None): """Split the specified arg list (or sys.argv if unspecified). args[0] is ignored. Returns a SplitArgs tuple. """ goals = OrderedSet() scope_to_flags = {} def add_scope(s): # Force the scope to appear, even if empty. if s not in scope_to_flags: ...
[ "def", "split_args", "(", "self", ",", "args", "=", "None", ")", ":", "goals", "=", "OrderedSet", "(", ")", "scope_to_flags", "=", "{", "}", "def", "add_scope", "(", "s", ")", ":", "# Force the scope to appear, even if empty.", "if", "s", "not", "in", "sco...
35.808219
19.369863
def get_size(self): """Retrieves the size of the file-like object. Returns: int: size of the decoded stream. Raises: IOError: if the file-like object has not been opened. OSError: if the file-like object has not been opened. """ if not self._is_open: raise IOError('Not open...
[ "def", "get_size", "(", "self", ")", ":", "if", "not", "self", ".", "_is_open", ":", "raise", "IOError", "(", "'Not opened.'", ")", "if", "self", ".", "_decoded_stream_size", "is", "None", ":", "self", ".", "_decoded_stream_size", "=", "self", ".", "_GetDe...
26.647059
19.176471
def anonymize_user(doc): """Preprocess an event by anonymizing user information. The anonymization is done by removing fields that can uniquely identify a user, such as the user's ID, session ID, IP address and User Agent, and hashing them to produce a ``visitor_id`` and ``unique_session_id``. To f...
[ "def", "anonymize_user", "(", "doc", ")", ":", "ip", "=", "doc", ".", "pop", "(", "'ip_address'", ",", "None", ")", "if", "ip", ":", "doc", ".", "update", "(", "{", "'country'", ":", "get_geoip", "(", "ip", ")", "}", ")", "user_id", "=", "doc", "...
40.884058
22.217391