text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def format(self, record): """Format the record as tersely as possible but preserve info.""" super(CliFormatter, self).format(record) localized_time = datetime.datetime.fromtimestamp(record.created) terse_time = localized_time.strftime(u'%H:%M:%S') terse_level = record.levelname[0] terse_name = r...
[ "def", "format", "(", "self", ",", "record", ")", ":", "super", "(", "CliFormatter", ",", "self", ")", ".", "format", "(", "record", ")", "localized_time", "=", "datetime", ".", "datetime", ".", "fromtimestamp", "(", "record", ".", "created", ")", "terse...
49.681818
16.727273
def spell_correct(string): """ Uses aspell to spell correct an input string. Requires aspell to be installed and added to the path. Returns the spell corrected string if aspell is found, original string if not. string - string """ # Create a temp file so that aspell could be used # By d...
[ "def", "spell_correct", "(", "string", ")", ":", "# Create a temp file so that aspell could be used", "# By default, tempfile will delete this file when the file handle is closed.", "f", "=", "tempfile", ".", "NamedTemporaryFile", "(", "mode", "=", "'w'", ")", "f", ".", "writ...
36.180328
19.295082
def send_item(self, destination, item_id, force_send): """ Run send method for item_id at destination. :param destination: str which type of operation are we doing (SHARE_DESTINATION or DELIVER_DESTINATION) :param item_id: str D4S2 service id representing the item we want to send ...
[ "def", "send_item", "(", "self", ",", "destination", ",", "item_id", ",", "force_send", ")", ":", "data", "=", "json", ".", "dumps", "(", "{", "'force'", ":", "force_send", ",", "}", ")", "url_suffix", "=", "\"{}/send/\"", ".", "format", "(", "item_id", ...
48.2
22.6
def getname(obj): """ Return the most qualified name of an object :param obj: object to fetch name :return: name of ``obj`` """ for name_attribute in ('__qualname__', '__name__'): try: # an object always has a class, as per Python data model return getattr(obj, n...
[ "def", "getname", "(", "obj", ")", ":", "for", "name_attribute", "in", "(", "'__qualname__'", ",", "'__name__'", ")", ":", "try", ":", "# an object always has a class, as per Python data model", "return", "getattr", "(", "obj", ",", "name_attribute", ",", "getattr",...
35.357143
20.214286
def _mass(self,R,z=0.,t=0.): """ NAME: _mass PURPOSE: calculate the mass out to a given radius INPUT: R - radius at which to return the enclosed mass z - (don't specify this) vertical height OUTPUT: mass in natural units ...
[ "def", "_mass", "(", "self", ",", "R", ",", "z", "=", "0.", ",", "t", "=", "0.", ")", ":", "if", "z", "is", "None", ":", "r", "=", "R", "else", ":", "r", "=", "numpy", ".", "sqrt", "(", "R", "**", "2.", "+", "z", "**", "2.", ")", "retur...
29.470588
14.529412
def _read_http_goaway(self, size, kind, flag): """Read HTTP/2 GOAWAY frames. Structure of HTTP/2 GOAWAY frame [RFC 7540]: +-----------------------------------------------+ | Length (24) | +---------------+---------------+------------...
[ "def", "_read_http_goaway", "(", "self", ",", "size", ",", "kind", ",", "flag", ")", ":", "_dlen", "=", "size", "-", "8", "if", "_dlen", "<", "0", ":", "raise", "ProtocolError", "(", "f'HTTP/2: [Type {kind}] invalid format'", ",", "quiet", "=", "True", ")"...
47.784314
25.509804
def paginate_activity(visible_date=None): """ Creates "get previous day" / "get next day" pagination for activities. Visible date is the date of the activities currently being shown, represented by a date object. If not provided, it will default to today. #Expects date as default "Aug. 25, 20...
[ "def", "paginate_activity", "(", "visible_date", "=", "None", ")", ":", "#if visible_date:", "# visible_date = datetime.datetime.strptime(visible_date, \"%b %d \")", "if", "not", "visible_date", ":", "visible_date", "=", "datetime", ".", "date", ".", "today", "(", ")",...
34.181818
19.909091
def within_depth_range(self, lower_depth=None, upper_depth=None): ''' Selects events within a specified depth range :param float lower_depth: Lower depth for consideration :param float upper_depth: Upper depth for consideration :returns: Ins...
[ "def", "within_depth_range", "(", "self", ",", "lower_depth", "=", "None", ",", "upper_depth", "=", "None", ")", ":", "if", "not", "lower_depth", ":", "if", "not", "upper_depth", ":", "# No limiting depths defined - so return entire catalogue!", "return", "self", "....
33.518519
21
def ps(self): """ Get the process information from the system PS command. """ # Get the process ID pid = self.get() # Parent / child processes parent = None children = [] # If the process is running if pid: ...
[ "def", "ps", "(", "self", ")", ":", "# Get the process ID", "pid", "=", "self", ".", "get", "(", ")", "# Parent / child processes", "parent", "=", "None", "children", "=", "[", "]", "# If the process is running", "if", "pid", ":", "proc", "=", "Popen", "(", ...
34.388889
16.833333
def verify_valid_dependencies(self): """ Checks if the assigned dependencies are valid valid dependency graphs are: - noncyclic (i.e. no `A -> B -> ... -> A`) - Contain no undefined dependencies (dependencies referencing undefined tasks) """ un...
[ "def", "verify_valid_dependencies", "(", "self", ")", ":", "unobserved_dependencies", "=", "set", "(", "self", ".", "tasks", ".", "keys", "(", ")", ")", "target_queue", "=", "[", "]", "while", "len", "(", "unobserved_dependencies", ")", ">", "0", ":", "tar...
34.294118
16.058824
def calculate(self, T, P, zs, ws, method): r'''Method to calculate surface tension of a liquid mixture at temperature `T`, pressure `P`, mole fractions `zs` and weight fractions `ws` with a given method. This method has no exception handling; see `mixture_property` for that. ...
[ "def", "calculate", "(", "self", ",", "T", ",", "P", ",", "zs", ",", "ws", ",", "method", ")", ":", "if", "method", "==", "SIMPLE", ":", "sigmas", "=", "[", "i", "(", "T", ")", "for", "i", "in", "self", ".", "SurfaceTensions", "]", "return", "m...
38.026316
20.973684
def set_file(name, source, template=None, context=None, defaults=None, **kwargs): ''' Set debconf selections from a file or a template .. code-block:: yaml <state_id>: debconf.set_file: - source: salt://pathto/pkg.selections <state_id>: debconf.set_file: ...
[ "def", "set_file", "(", "name", ",", "source", ",", "template", "=", "None", ",", "context", "=", "None", ",", "defaults", "=", "None", ",", "*", "*", "kwargs", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'changes'", ":", "{", "}", ",...
27.760563
24.464789
def remove_layer(svg_source, layer_name): ''' Remove layer(s) from SVG document. Arguments --------- svg_source : str or file-like A file path, URI, or file-like object. layer_name : str or list Layer name or list of layer names to remove from SVG document. Returns ----...
[ "def", "remove_layer", "(", "svg_source", ",", "layer_name", ")", ":", "# Parse input file.", "xml_root", "=", "lxml", ".", "etree", ".", "parse", "(", "svg_source", ")", "svg_root", "=", "xml_root", ".", "xpath", "(", "'/svg:svg'", ",", "namespaces", "=", "...
29.447368
21.394737
def expect_re(self, regexp): """Test against the given regular expression and returns the match object. :param regexp: the expression to be tested. :returns: the match object. """ prefix_len = self.match_prefix( self.prefix, self.next_line(require_prefix=False) ...
[ "def", "expect_re", "(", "self", ",", "regexp", ")", ":", "prefix_len", "=", "self", ".", "match_prefix", "(", "self", ".", "prefix", ",", "self", ".", "next_line", "(", "require_prefix", "=", "False", ")", ")", "if", "prefix_len", ">=", "0", ":", "mat...
33.266667
15.333333
def backup(self): """ Backup the main dataframe """ try: self.backup_df = self.df.copy() except Exception as e: self.err(e, "Can not backup data") return self.ok("Dataframe backed up")
[ "def", "backup", "(", "self", ")", ":", "try", ":", "self", ".", "backup_df", "=", "self", ".", "df", ".", "copy", "(", ")", "except", "Exception", "as", "e", ":", "self", ".", "err", "(", "e", ",", "\"Can not backup data\"", ")", "return", "self", ...
25.9
10.1
def first_available(self, *quantities): """ Return the first available quantity in the input arguments. Return `None` if none of them is available. """ for i, q in enumerate(quantities): if self.has_quantity(q): if i: warnings.warn(...
[ "def", "first_available", "(", "self", ",", "*", "quantities", ")", ":", "for", "i", ",", "q", "in", "enumerate", "(", "quantities", ")", ":", "if", "self", ".", "has_quantity", "(", "q", ")", ":", "if", "i", ":", "warnings", ".", "warn", "(", "'{}...
39.8
13.6
def filtered_list(cls, name=None, obj=None): """List datacenters matching name and compatible with obj""" options = {} if name: options['id'] = cls.usable_id(name) def obj_ok(dc, obj): if not obj or obj['datacenter_id'] == dc['id']: return...
[ "def", "filtered_list", "(", "cls", ",", "name", "=", "None", ",", "obj", "=", "None", ")", ":", "options", "=", "{", "}", "if", "name", ":", "options", "[", "'id'", "]", "=", "cls", ".", "usable_id", "(", "name", ")", "def", "obj_ok", "(", "dc",...
31
16.769231
def pack_value(self, val): """Convert 8-byte string into 16-byte list""" if isinstance(val, bytes): val = list(iterbytes(val)) slen = len(val) if self.pad: pad = b'\0\0' * (slen % 2) else: pad = b'' return struct.pack('>' + 'H' * sle...
[ "def", "pack_value", "(", "self", ",", "val", ")", ":", "if", "isinstance", "(", "val", ",", "bytes", ")", ":", "val", "=", "list", "(", "iterbytes", "(", "val", ")", ")", "slen", "=", "len", "(", "val", ")", "if", "self", ".", "pad", ":", "pad...
25.692308
19.615385
def ordinary_diffusion(target, pore_area='pore.area', throat_area='throat.area', pore_diffusivity='pore.diffusivity', throat_diffusivity='throat.diffusivity', conduit_lengths='throat.conduit_lengths', ...
[ "def", "ordinary_diffusion", "(", "target", ",", "pore_area", "=", "'pore.area'", ",", "throat_area", "=", "'throat.area'", ",", "pore_diffusivity", "=", "'pore.diffusivity'", ",", "throat_diffusivity", "=", "'throat.diffusivity'", ",", "conduit_lengths", "=", "'throat....
38.711864
25.338983
def unparse_qsl(qsl, sort=False, reverse=False): """Reverse conversion for parse_qsl""" result = [] items = qsl if sort: items = sorted(items, key=lambda x: x[0], reverse=reverse) for keys, values in items: query_name = quote(keys) result.append(query_name + "=" + quote(value...
[ "def", "unparse_qsl", "(", "qsl", ",", "sort", "=", "False", ",", "reverse", "=", "False", ")", ":", "result", "=", "[", "]", "items", "=", "qsl", "if", "sort", ":", "items", "=", "sorted", "(", "items", ",", "key", "=", "lambda", "x", ":", "x", ...
34.2
15.8
def get_queryset(self): """ Returns all the approved topics or posts. """ qs = super().get_queryset() qs = qs.filter(approved=True) return qs
[ "def", "get_queryset", "(", "self", ")", ":", "qs", "=", "super", "(", ")", ".", "get_queryset", "(", ")", "qs", "=", "qs", ".", "filter", "(", "approved", "=", "True", ")", "return", "qs" ]
33.8
9.6
def _active_mounts_freebsd(ret): ''' List active mounts on FreeBSD systems ''' for line in __salt__['cmd.run_stdout']('mount -p').split('\n'): comps = re.sub(r"\s+", " ", line).split() ret[comps[1]] = {'device': comps[0], 'fstype': comps[2], ...
[ "def", "_active_mounts_freebsd", "(", "ret", ")", ":", "for", "line", "in", "__salt__", "[", "'cmd.run_stdout'", "]", "(", "'mount -p'", ")", ".", "split", "(", "'\\n'", ")", ":", "comps", "=", "re", ".", "sub", "(", "r\"\\s+\"", ",", "\" \"", ",", "li...
38.5
18.5
def set_privatekey(self, pkey): """ Set the certificate portion of the PKCS #12 structure. :param pkey: The new private key, or :py:const:`None` to unset it. :type pkey: :py:class:`PKey` or :py:const:`None` :return: ``None`` """ if not isinstance(pkey, PKey): ...
[ "def", "set_privatekey", "(", "self", ",", "pkey", ")", ":", "if", "not", "isinstance", "(", "pkey", ",", "PKey", ")", ":", "raise", "TypeError", "(", "\"pkey must be a PKey instance\"", ")", "self", ".", "_pkey", "=", "pkey" ]
32.666667
17.666667
def __validInputs(self): """Validates the inputs of the constructor.""" #if not isinstance(self.__column, Column): # raise Sitools2Exception("column must be an instance of Column") try: float(self.__minVal) except ValueError as ex: raise Sitools2Excepti...
[ "def", "__validInputs", "(", "self", ")", ":", "#if not isinstance(self.__column, Column):", "# raise Sitools2Exception(\"column must be an instance of Column\")", "try", ":", "float", "(", "self", ".", "__minVal", ")", "except", "ValueError", "as", "ex", ":", "raise", ...
38
15.466667
def addcert(self, cert): """ Adds a certificate (probably intermediate CA) to the SignedData structure """ if libcrypto.CMS_add1_cert(self.ptr, cert.cert) <= 0: raise CMSError("Cannot add cert")
[ "def", "addcert", "(", "self", ",", "cert", ")", ":", "if", "libcrypto", ".", "CMS_add1_cert", "(", "self", ".", "ptr", ",", "cert", ".", "cert", ")", "<=", "0", ":", "raise", "CMSError", "(", "\"Cannot add cert\"", ")" ]
34.285714
13.714286
def get_bbox_list(self, crs=None, buffer=None, reduce_bbox_sizes=None): """Returns a list of bounding boxes that are the result of the split :param crs: Coordinate reference system in which the bounding boxes should be returned. If None the CRS will be the default CRS of the splitte...
[ "def", "get_bbox_list", "(", "self", ",", "crs", "=", "None", ",", "buffer", "=", "None", ",", "reduce_bbox_sizes", "=", "None", ")", ":", "bbox_list", "=", "self", ".", "bbox_list", "if", "buffer", ":", "bbox_list", "=", "[", "bbox", ".", "buffer", "(...
47
24.884615
def exit_with_error(message): """ Display formatted error message and exit call """ click.secho(message, err=True, bg='red', fg='white') sys.exit(0)
[ "def", "exit_with_error", "(", "message", ")", ":", "click", ".", "secho", "(", "message", ",", "err", "=", "True", ",", "bg", "=", "'red'", ",", "fg", "=", "'white'", ")", "sys", ".", "exit", "(", "0", ")" ]
39.25
13
def to_iso639_1(key): """Find ISO 639-1 code for language specified by key. >>> to_iso639_1("swe") u'sv' >>> to_iso639_1("English") u'en' """ item = find(whatever=key) if not item: raise NonExistentLanguageError('Language does not exist.') return item[u'iso639_1']
[ "def", "to_iso639_1", "(", "key", ")", ":", "item", "=", "find", "(", "whatever", "=", "key", ")", "if", "not", "item", ":", "raise", "NonExistentLanguageError", "(", "'Language does not exist.'", ")", "return", "item", "[", "u'iso639_1'", "]" ]
24.833333
18.166667
def write_back(self, documents, doc_ids=None, eids=None): """ Write back documents by doc_id :param documents: a list of document to write back :param doc_ids: a list of document IDs which need to be written back :returns: a list of document IDs that have been written ""...
[ "def", "write_back", "(", "self", ",", "documents", ",", "doc_ids", "=", "None", ",", "eids", "=", "None", ")", ":", "doc_ids", "=", "_get_doc_ids", "(", "doc_ids", ",", "eids", ")", "if", "doc_ids", "is", "not", "None", "and", "not", "len", "(", "do...
34.852941
21.970588
def _check_message_valid(msg): """Check packet length valid and that checksum is good.""" try: if int(msg[:2], 16) != (len(msg) - 2): raise ValueError("Elk message length incorrect") _check_checksum(msg) except IndexError: raise ValueError("Elk message length incorrect")
[ "def", "_check_message_valid", "(", "msg", ")", ":", "try", ":", "if", "int", "(", "msg", "[", ":", "2", "]", ",", "16", ")", "!=", "(", "len", "(", "msg", ")", "-", "2", ")", ":", "raise", "ValueError", "(", "\"Elk message length incorrect\"", ")", ...
39
14.25
def build_network(self, network=None, *args, **kwargs): """ Core method to construct PyPSA Network object. """ # TODO: build_network takes care of divergences in database design and # future PyPSA changes from PyPSA's v0.6 on. This concept should be # replaced, when the oedb has...
[ "def", "build_network", "(", "self", ",", "network", "=", "None", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# TODO: build_network takes care of divergences in database design and", "# future PyPSA changes from PyPSA's v0.6 on. This concept should be", "# replaced, w...
38.033333
22.833333
def newSession(): """ Returns a new Requests session with pre-loaded default HTTP Headers Generates a new Requests session and consults with the Configuration class to determine if a Configuration exists and attempts to use the configured HTTP Request headers first. If this fail...
[ "def", "newSession", "(", ")", ":", "from", "neolib", ".", "config", ".", "Configuration", "import", "Configuration", "s", "=", "requests", ".", "session", "(", ")", "if", "not", "Configuration", ".", "loaded", "(", ")", ":", "if", "not", "Configuration", ...
41.037037
23.851852
def OnPasteFormat(self, event): """Paste format event handler""" with undo.group(_("Paste format")): self.grid.actions.paste_format() self.grid.ForceRefresh() self.grid.update_attribute_toolbar() self.grid.actions.zoom()
[ "def", "OnPasteFormat", "(", "self", ",", "event", ")", ":", "with", "undo", ".", "group", "(", "_", "(", "\"Paste format\"", ")", ")", ":", "self", ".", "grid", ".", "actions", ".", "paste_format", "(", ")", "self", ".", "grid", ".", "ForceRefresh", ...
29.555556
12.888889
def marketYesterdayDF(token='', version=''): '''This returns previous day adjusted price data for whole market https://iexcloud.io/docs/api/#previous-day-prices Available after 4am ET Tue-Sat Args: symbol (string); Ticker to request token (string); Access token version (string)...
[ "def", "marketYesterdayDF", "(", "token", "=", "''", ",", "version", "=", "''", ")", ":", "x", "=", "marketYesterday", "(", "token", ",", "version", ")", "data", "=", "[", "]", "for", "key", "in", "x", ":", "data", ".", "append", "(", "x", "[", "...
25.26087
18.913043
def followee_num(self): """获取关注了多少人. :return: 关注的人数 :rtype: int """ if self.url is None: return 0 else: number = int(self.soup.find( 'div', class_='zm-profile-side-following').a.strong.text) return number
[ "def", "followee_num", "(", "self", ")", ":", "if", "self", ".", "url", "is", "None", ":", "return", "0", "else", ":", "number", "=", "int", "(", "self", ".", "soup", ".", "find", "(", "'div'", ",", "class_", "=", "'zm-profile-side-following'", ")", ...
24.5
16.916667
def _getParLabelAndUnit(self, param): """ checks param to see if it contains a parent link (ie star.) then returns the correct unit and label for the job from the parDicts :return: """ firstObject = self.objectList[0] if isinstance(firstObject, ac.Planet): ...
[ "def", "_getParLabelAndUnit", "(", "self", ",", "param", ")", ":", "firstObject", "=", "self", ".", "objectList", "[", "0", "]", "if", "isinstance", "(", "firstObject", ",", "ac", ".", "Planet", ")", ":", "if", "'star.'", "in", "param", ":", "return", ...
39.470588
17.705882
def set_source_filter(self, source): """ Only search for tweets entered via given source :param source: String. Name of the source to search for. An example \ would be ``source=twitterfeed`` for tweets submitted via TwitterFeed :raises: TwitterSearchException """ if isi...
[ "def", "set_source_filter", "(", "self", ",", "source", ")", ":", "if", "isinstance", "(", "source", ",", "str", "if", "py3k", "else", "basestring", ")", "and", "len", "(", "source", ")", ">=", "2", ":", "self", ".", "source_filter", "=", "source", "el...
39.666667
19.333333
def create_mackup_home(self): """If the Mackup home folder does not exist, create it.""" if not os.path.isdir(self.mackup_folder): if utils.confirm("Mackup needs a directory to store your" " configuration files\n" "Do you want to crea...
[ "def", "create_mackup_home", "(", "self", ")", ":", "if", "not", "os", ".", "path", ".", "isdir", "(", "self", ".", "mackup_folder", ")", ":", "if", "utils", ".", "confirm", "(", "\"Mackup needs a directory to store your\"", "\" configuration files\\n\"", "\"Do yo...
52.6
16.8
def abort(self): """ ensure the master exit from Barrier """ self.mutex.release() self.turnstile.release() self.mutex.release() self.turnstile2.release()
[ "def", "abort", "(", "self", ")", ":", "self", ".", "mutex", ".", "release", "(", ")", "self", ".", "turnstile", ".", "release", "(", ")", "self", ".", "mutex", ".", "release", "(", ")", "self", ".", "turnstile2", ".", "release", "(", ")" ]
31.333333
10.5
def copy_tree_root(src_dir: str, dest_parent: str) -> None: """ Copies a directory ``src_dir`` into the directory ``dest_parent``. That is, with a file structure like: .. code-block:: none /source/thing/a.txt /source/thing/b.txt /source/thing/somedir/c.txt the command ...
[ "def", "copy_tree_root", "(", "src_dir", ":", "str", ",", "dest_parent", ":", "str", ")", "->", "None", ":", "dirname", "=", "os", ".", "path", ".", "basename", "(", "os", ".", "path", ".", "normpath", "(", "src_dir", ")", ")", "dest_dir", "=", "os",...
23.428571
20.142857
def get_all(self, keys): """ Returns the entries for the given keys. **Warning: The returned map is NOT backed by the original map, so changes to the original map are NOT reflected in the returned map, and vice-versa.** **Warning 2: This method uses __hash__ and __eq__ ...
[ "def", "get_all", "(", "self", ",", "keys", ")", ":", "check_not_none", "(", "keys", ",", "\"keys can't be None\"", ")", "if", "not", "keys", ":", "return", "ImmediateFuture", "(", "{", "}", ")", "partition_service", "=", "self", ".", "_client", ".", "part...
37.225806
22.516129
def compute_pmap_stats(pmaps, stats, weights, imtls): """ :param pmaps: a list of R probability maps :param stats: a sequence of S statistic functions :param weights: a list of ImtWeights :param imtls: a DictArray of intensity measure types :returns: a pro...
[ "def", "compute_pmap_stats", "(", "pmaps", ",", "stats", ",", "weights", ",", "imtls", ")", ":", "sids", "=", "set", "(", ")", "p0", "=", "next", "(", "iter", "(", "pmaps", ")", ")", "L", "=", "p0", ".", "shape_y", "for", "pmap", "in", "pmaps", "...
33.527778
14.305556
def get(name, stype, **kwargs): """Returns the rcParams specified in the style file given by `name` and `stype`. Parameters ---------- name: str The name of the style. stype: str Any of ('context', 'style', 'palette'). kwargs: - stylelib_url: str Overwrite the value ...
[ "def", "get", "(", "name", ",", "stype", ",", "*", "*", "kwargs", ")", ":", "stype", "=", "str", "(", "stype", ")", "params", "=", "{", "}", "if", "stype", "in", "MPLS_STYPES", ":", "params", ".", "update", "(", "__get", "(", "name", ",", "stype"...
26.842105
24.447368
def parser(self, lines): """Given a set of lines parse the into a MOP Header""" while len(lines) > 0: if lines[0].startswith('##') and lines[1].startswith('# '): # A two-line keyword/value line starts here. self._header_append(lines.pop(0), lines.pop(0)) ...
[ "def", "parser", "(", "self", ",", "lines", ")", ":", "while", "len", "(", "lines", ")", ">", "0", ":", "if", "lines", "[", "0", "]", ".", "startswith", "(", "'##'", ")", "and", "lines", "[", "1", "]", ".", "startswith", "(", "'# '", ")", ":", ...
53.625
20.125
def generate_iv_for_export(self, client_random, server_random, con_end, read_or_write, req_len): """ Generate IV for EXPORT ciphersuite, i.e. weakens it. An export IV generation example is given in section 6.3.1 of RFC 2246. See also page 86 of EKR's book. ...
[ "def", "generate_iv_for_export", "(", "self", ",", "client_random", ",", "server_random", ",", "con_end", ",", "read_or_write", ",", "req_len", ")", ":", "s", "=", "con_end", "+", "read_or_write", "s", "=", "(", "s", "==", "\"clientwrite\"", "or", "s", "==",...
37.071429
14.5
def __get_verb(counts): """Let's fetch a VERB :param counts: """ cursor = CONN.cursor() check_query = "select verb_id from surverbs" cursor.execute(check_query) check_result = cursor.fetchall() id_list = [] for row in check_result: id_list.append(row[0]) rand = random...
[ "def", "__get_verb", "(", "counts", ")", ":", "cursor", "=", "CONN", ".", "cursor", "(", ")", "check_query", "=", "\"select verb_id from surverbs\"", "cursor", ".", "execute", "(", "check_query", ")", "check_result", "=", "cursor", ".", "fetchall", "(", ")", ...
22.384615
20.153846
def _unpack_bin(self, packed): """ Internal. Decodes 16 bit RGB565 into python list [R,G,B] """ output = struct.unpack('H', packed) bits16 = output[0] r = (bits16 & 0xF800) >> 11 g = (bits16 & 0x7E0) >> 5 b = (bits16 & 0x1F) return [int(r << 3), i...
[ "def", "_unpack_bin", "(", "self", ",", "packed", ")", ":", "output", "=", "struct", ".", "unpack", "(", "'H'", ",", "packed", ")", "bits16", "=", "output", "[", "0", "]", "r", "=", "(", "bits16", "&", "0xF800", ")", ">>", "11", "g", "=", "(", ...
30.363636
11.818182
def get_field_kwargs(field_name, model_field): """ Creating a default instance of a basic non-relational field. """ kwargs = {} # The following will only be used by ModelField classes. # Gets removed for everything else. kwargs['model_field'] = model_field if hasattr(model_field, 'verb...
[ "def", "get_field_kwargs", "(", "field_name", ",", "model_field", ")", ":", "kwargs", "=", "{", "}", "# The following will only be used by ModelField classes.", "# Gets removed for everything else.", "kwargs", "[", "'model_field'", "]", "=", "model_field", "if", "hasattr", ...
37.772152
21.898734
def _get_metadap_dap(name, version=''): '''Return data for dap of given or latest version.''' m = metadap(name) if not m: raise DapiCommError('DAP {dap} not found.'.format(dap=name)) if not version: d = m['latest_stable'] or m['latest'] if d: d = data(d) else: ...
[ "def", "_get_metadap_dap", "(", "name", ",", "version", "=", "''", ")", ":", "m", "=", "metadap", "(", "name", ")", "if", "not", "m", ":", "raise", "DapiCommError", "(", "'DAP {dap} not found.'", ".", "format", "(", "dap", "=", "name", ")", ")", "if", ...
33.066667
20.933333
def _set_ext_vni(self, v, load=False): """ Setter method for ext_vni, mapped from YANG variable /overlay/access_list/type/vxlan/extended/ext_seq/ext_vni (uint32) If this variable is read-only (config: false) in the source YANG file, then _set_ext_vni is considered as a private method. Backends looki...
[ "def", "_set_ext_vni", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", "v", ",", "base",...
96.181818
46.272727
def send_task(self, request, response): """send off a celery task for the current page and recache""" # TODO is this too messy? from bettercache.tasks import GeneratePage try: GeneratePage.apply_async((strip_wsgi(request),)) except: logger.error("failed t...
[ "def", "send_task", "(", "self", ",", "request", ",", "response", ")", ":", "# TODO is this too messy?", "from", "bettercache", ".", "tasks", "import", "GeneratePage", "try", ":", "GeneratePage", ".", "apply_async", "(", "(", "strip_wsgi", "(", "request", ")", ...
37.3
14.6
async def log_source(self, **params): """ Logging users request sources """ if params.get("message"): params = json.loads(params.get("message", "{}")) if not params: return {"error":400, "reason":"Missed required fields"} # Insert new source if does not exists the one database = client[settings.D...
[ "async", "def", "log_source", "(", "self", ",", "*", "*", "params", ")", ":", "if", "params", ".", "get", "(", "\"message\"", ")", ":", "params", "=", "json", ".", "loads", "(", "params", ".", "get", "(", "\"message\"", ",", "\"{}\"", ")", ")", "if...
29.611111
18.277778
def build_images(): # type: () -> None """ Build all docker images for the project. """ registry = conf.get('docker.registry') docker_images = conf.get('docker.images', []) for image in docker_images: build_image(registry, image)
[ "def", "build_images", "(", ")", ":", "# type: () -> None", "registry", "=", "conf", ".", "get", "(", "'docker.registry'", ")", "docker_images", "=", "conf", ".", "get", "(", "'docker.images'", ",", "[", "]", ")", "for", "image", "in", "docker_images", ":", ...
31.375
12.875
def _PrintStorageInformationAsText(self, storage_reader): """Prints information about the store as human-readable text. Args: storage_reader (StorageReader): storage reader. """ table_view = views.ViewsFactory.GetTableView( self._views_format_type, title='Plaso Storage Information') t...
[ "def", "_PrintStorageInformationAsText", "(", "self", ",", "storage_reader", ")", ":", "table_view", "=", "views", ".", "ViewsFactory", ".", "GetTableView", "(", "self", ".", "_views_format_type", ",", "title", "=", "'Plaso Storage Information'", ")", "table_view", ...
39.234043
23.702128
def check_request_parameters(self, parameters: dict = dict): """Check parameters passed to avoid errors and help debug. :param dict response: search request parameters """ # -- SEMANTIC QUERY --------------------------------------------------- li_args = parameters.get("q").split...
[ "def", "check_request_parameters", "(", "self", ",", "parameters", ":", "dict", "=", "dict", ")", ":", "# -- SEMANTIC QUERY ---------------------------------------------------", "li_args", "=", "parameters", ".", "get", "(", "\"q\"", ")", ".", "split", "(", ")", "lo...
43.635514
20.35514
def get_task_positions_objs(client, list_id): ''' Gets a list containing the object that encapsulates information about the order lists are laid out in. This list will always contain exactly one object. See https://developer.wunderlist.com/documentation/endpoints/positions for more info Return: A ...
[ "def", "get_task_positions_objs", "(", "client", ",", "list_id", ")", ":", "params", "=", "{", "'list_id'", ":", "int", "(", "list_id", ")", "}", "response", "=", "client", ".", "authenticated_request", "(", "client", ".", "api", ".", "Endpoints", ".", "TA...
39.928571
35.071429
def get_instance_property(instance, property_name): """Retrieves property of an instance, keeps retrying until getting a non-None""" name = get_name(instance) while True: try: value = getattr(instance, property_name) if value is not None: break print(f"retrieving {property_name} on ...
[ "def", "get_instance_property", "(", "instance", ",", "property_name", ")", ":", "name", "=", "get_name", "(", "instance", ")", "while", "True", ":", "try", ":", "value", "=", "getattr", "(", "instance", ",", "property_name", ")", "if", "value", "is", "not...
28.434783
21.304348
def sort_samples(self, stable=True, inplace=False, ascending=True): """Sort the columns of the matrix alphabetically by sample name. Parameters ---------- stable: bool, optional Whether to use a stable sorting algorithm. [True] inplace: bool, optional Whe...
[ "def", "sort_samples", "(", "self", ",", "stable", "=", "True", ",", "inplace", "=", "False", ",", "ascending", "=", "True", ")", ":", "kind", "=", "'quicksort'", "if", "stable", ":", "kind", "=", "'mergesort'", "return", "self", ".", "sort_index", "(", ...
32.954545
18
def _advance_to_next_stage(self, config_ids, losses): """ SuccessiveHalving simply continues the best based on the current loss. """ ranks = np.argsort(np.argsort(losses)) return(ranks < max(self.min_samples_advance, self.num_configs[self.stage] * (1-self.resampling_rate)) )
[ "def", "_advance_to_next_stage", "(", "self", ",", "config_ids", ",", "losses", ")", ":", "ranks", "=", "np", ".", "argsort", "(", "np", ".", "argsort", "(", "losses", ")", ")", "return", "(", "ranks", "<", "max", "(", "self", ".", "min_samples_advance",...
40.428571
21.285714
def login(request, template_name=None, extra_context=None, **kwargs): """Logs a user in using the :class:`~openstack_auth.forms.Login` form.""" # If the user enabled websso and the default redirect # redirect to the default websso url if (request.method == 'GET' and utils.is_websso_enabled and ...
[ "def", "login", "(", "request", ",", "template_name", "=", "None", ",", "extra_context", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# If the user enabled websso and the default redirect", "# redirect to the default websso url", "if", "(", "request", ".", "method...
46.438776
19.367347
def significance_fdr(p, alpha): """Calculate significance by controlling for the false discovery rate. This function determines which of the p-values in `p` can be considered significant. Correction for multiple comparisons is performed by controlling the false discovery rate (FDR). The FDR is the maxi...
[ "def", "significance_fdr", "(", "p", ",", "alpha", ")", ":", "i", "=", "np", ".", "argsort", "(", "p", ",", "axis", "=", "None", ")", "m", "=", "i", ".", "size", "-", "np", ".", "sum", "(", "np", ".", "isnan", "(", "p", ")", ")", "j", "=", ...
27.886364
22.818182
def has_opt(self, opt): """Check if option is present in configuration file Parameters ----------- opt : string Name of option (e.g. output-file-format) """ for sec in self.sections: val = self.cp.has_option(sec, opt) if val: ...
[ "def", "has_opt", "(", "self", ",", "opt", ")", ":", "for", "sec", "in", "self", ".", "sections", ":", "val", "=", "self", ".", "cp", ".", "has_option", "(", "sec", ",", "opt", ")", "if", "val", ":", "return", "val", "return", "False" ]
24.714286
17.142857
def encrypt(self, password): """Encrypt the password. """ if not password or not self._crypter: return password or b'' return self._crypter.encrypt(password)
[ "def", "encrypt", "(", "self", ",", "password", ")", ":", "if", "not", "password", "or", "not", "self", ".", "_crypter", ":", "return", "password", "or", "b''", "return", "self", ".", "_crypter", ".", "encrypt", "(", "password", ")" ]
32.666667
4.833333
def add(assetclass: int, symbol: str): """ Add a stock to an asset class """ assert isinstance(symbol, str) assert isinstance(assetclass, int) symbol = symbol.upper() app = AppAggregate() new_item = app.add_stock_to_class(assetclass, symbol) print(f"Record added: {new_item}.")
[ "def", "add", "(", "assetclass", ":", "int", ",", "symbol", ":", "str", ")", ":", "assert", "isinstance", "(", "symbol", ",", "str", ")", "assert", "isinstance", "(", "assetclass", ",", "int", ")", "symbol", "=", "symbol", ".", "upper", "(", ")", "ap...
33.111111
10.777778
def mail2blogger(entry, **kwargs): """This signal handler cross-posts published ``Entry``'s to Blogger. For this to work, the following settings must be non-False; e.g.: BLARGG = { 'mail2blogger': True, 'mail2blogger_email': 'user@example.com', } """ enabled = b...
[ "def", "mail2blogger", "(", "entry", ",", "*", "*", "kwargs", ")", ":", "enabled", "=", "blargg_settings", ".", "get", "(", "'mail2blogger'", ",", "False", ")", "recipient", "=", "blargg_settings", ".", "get", "(", "'mail2blogger_email'", ",", "None", ")", ...
35.913043
16.652174
def _bashcomplete(cmd, prog_name, complete_var=None): """Internal handler for the bash completion support.""" if complete_var is None: complete_var = '_%s_COMPLETE' % (prog_name.replace('-', '_')).upper() complete_instr = os.environ.get(complete_var) if not complete_instr: return fr...
[ "def", "_bashcomplete", "(", "cmd", ",", "prog_name", ",", "complete_var", "=", "None", ")", ":", "if", "complete_var", "is", "None", ":", "complete_var", "=", "'_%s_COMPLETE'", "%", "(", "prog_name", ".", "replace", "(", "'-'", ",", "'_'", ")", ")", "."...
39.545455
18.181818
def round_float(f, digits, rounding=ROUND_HALF_UP): """ Accurate float rounding from http://stackoverflow.com/a/15398691. """ return Decimal(str(f)).quantize(Decimal(10) ** (-1 * digits), rounding=rounding)
[ "def", "round_float", "(", "f", ",", "digits", ",", "rounding", "=", "ROUND_HALF_UP", ")", ":", "return", "Decimal", "(", "str", "(", "f", ")", ")", ".", "quantize", "(", "Decimal", "(", "10", ")", "**", "(", "-", "1", "*", "digits", ")", ",", "r...
42.166667
13.166667
def partitionSum(M,I,T,step=None): """ INPUT PARAMETERS: M: HITRAN molecule number (required) I: HITRAN isotopologue number (required) T: temperature conditions (required) step: step to calculate temperatures (optional) OUTPUT PARAMETERS:...
[ "def", "partitionSum", "(", "M", ",", "I", ",", "T", ",", "step", "=", "None", ")", ":", "# partitionSum", "if", "not", "step", ":", "if", "type", "(", "T", ")", "not", "in", "set", "(", "[", "list", ",", "tuple", "]", ")", ":", "return", "BD_T...
40.727273
21.363636
def img(self, id): """Serve Pylons' stock images""" return self._serve_file(os.path.join(media_path, 'img', id))
[ "def", "img", "(", "self", ",", "id", ")", ":", "return", "self", ".", "_serve_file", "(", "os", ".", "path", ".", "join", "(", "media_path", ",", "'img'", ",", "id", ")", ")" ]
42.666667
16.333333
def notify(cls, user_or_email_, object_id=None, **filters): """Start notifying the given user or email address when this event occurs and meets the criteria given in ``filters``. Return the created (or the existing matching) Watch so you can call :meth:`~tidings.models.Watch.activate()`...
[ "def", "notify", "(", "cls", ",", "user_or_email_", ",", "object_id", "=", "None", ",", "*", "*", "filters", ")", ":", "# A test-for-existence-then-create race condition exists here, but it", "# doesn't matter: de-duplication on fire() and deletion of all matches", "# on stop_not...
46.140625
18.46875
def env(config, endpoint): """Print RENKU environment variables. Run this command to configure your Renku client: $ eval "$(renku env)" """ access_token = config['endpoints'][endpoint]['token']['access_token'] click.echo('export {0}={1}'.format('RENKU_ENDPOINT', endpoint)) click.echo(...
[ "def", "env", "(", "config", ",", "endpoint", ")", ":", "access_token", "=", "config", "[", "'endpoints'", "]", "[", "endpoint", "]", "[", "'token'", "]", "[", "'access_token'", "]", "click", ".", "echo", "(", "'export {0}={1}'", ".", "format", "(", "'RE...
36.692308
21.615385
def draw_multi_dispersion_chart(self, nan_locs): """Draws a multi dimensional dispersion chart, each color corresponds to a different target variable. """ for index, nan_values in enumerate(nan_locs): label, nan_locations = nan_values # if features passed in then...
[ "def", "draw_multi_dispersion_chart", "(", "self", ",", "nan_locs", ")", ":", "for", "index", ",", "nan_values", "in", "enumerate", "(", "nan_locs", ")", ":", "label", ",", "nan_locations", "=", "nan_values", "# if features passed in then, label as such", "if", "sel...
39.733333
15.6
def get_string_u_at_rva(self, rva, max_length = 2**16): """Get an Unicode string located at the given address.""" try: # If the RVA is invalid all would blow up. Some EXEs seem to be # specially nasty and have an invalid RVA. data = self.get_data(rva, 2) ...
[ "def", "get_string_u_at_rva", "(", "self", ",", "rva", ",", "max_length", "=", "2", "**", "16", ")", ":", "try", ":", "# If the RVA is invalid all would blow up. Some EXEs seem to be", "# specially nasty and have an invalid RVA.", "data", "=", "self", ".", "get_data", "...
31.041667
18.666667
def match(self, path_info: str) -> MatchResult: """ parse path_info and detect urlvars of url pattern """ matched = self.regex.match(path_info) if matched is None: return None matchlength = len(matched.group(0)) matchdict = matched.groupdict() try: ...
[ "def", "match", "(", "self", ",", "path_info", ":", "str", ")", "->", "MatchResult", ":", "matched", "=", "self", ".", "regex", ".", "match", "(", "path_info", ")", "if", "matched", "is", "None", ":", "return", "None", "matchlength", "=", "len", "(", ...
32
13.533333
def _program_files_from_executable(self, executable, required_paths, parent_dir=False): """ Get a list of program files by expanding a list of path patterns and interpreting it as relative to the executable. This method can be used as helper for implementing the method program_files(). ...
[ "def", "_program_files_from_executable", "(", "self", ",", "executable", ",", "required_paths", ",", "parent_dir", "=", "False", ")", ":", "base_dir", "=", "os", ".", "path", ".", "dirname", "(", "executable", ")", "if", "parent_dir", ":", "base_dir", "=", "...
64.944444
31.5
def activate(username): """Activate a user. Example: \b ```bash $ polyaxon user activate david ``` """ try: PolyaxonClient().user.activate_user(username) except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e: Printer.print_error('Could no...
[ "def", "activate", "(", "username", ")", ":", "try", ":", "PolyaxonClient", "(", ")", ".", "user", ".", "activate_user", "(", "username", ")", "except", "(", "PolyaxonHTTPError", ",", "PolyaxonShouldExitError", ",", "PolyaxonClientException", ")", "as", "e", "...
28.277778
26.611111
def _proxy(self): """ Generate an instance context for the instance, the context is capable of performing various actions. All instance actions are proxied to the context :returns: SettingsContext for this SettingsInstance :rtype: twilio.rest.voice.v1.dialing_permissions.settin...
[ "def", "_proxy", "(", "self", ")", ":", "if", "self", ".", "_context", "is", "None", ":", "self", ".", "_context", "=", "SettingsContext", "(", "self", ".", "_version", ",", ")", "return", "self", ".", "_context" ]
42.181818
22.363636
def set_proxy_pool(self, proxies, auth=None, https=True): """设置代理池 :param proxies: proxy列表, 形如 ``["ip1:port1", "ip2:port2"]`` :param auth: 如果代理需要验证身份, 通过这个参数提供, 比如 :param https: 默认为 True, 传入 False 则不设置 https 代理 .. code-block:: python from requests.auth import HTTP...
[ "def", "set_proxy_pool", "(", "self", ",", "proxies", ",", "auth", "=", "None", ",", "https", "=", "True", ")", ":", "from", "random", "import", "choice", "if", "https", ":", "self", ".", "proxies", "=", "[", "{", "'http'", ":", "p", ",", "'https'", ...
35.131579
17
def get_access_token(self, http=None, additional_claims=None): """Create a signed jwt. Args: http: unused additional_claims: dict, additional claims to add to the payload of the JWT. Returns: An AccessTokenInfo with the signed jwt """ ...
[ "def", "get_access_token", "(", "self", ",", "http", "=", "None", ",", "additional_claims", "=", "None", ")", ":", "if", "additional_claims", "is", "None", ":", "if", "self", ".", "access_token", "is", "None", "or", "self", ".", "access_token_expired", ":", ...
40.3
17.1
def add_row(self, obj): """ fill a new row with the given obj obj instance of the exporter's model """ row = {} for column in self.headers: value = '' if '__col__' in column: if isinstance(column['__col__'], C...
[ "def", "add_row", "(", "self", ",", "obj", ")", ":", "row", "=", "{", "}", "for", "column", "in", "self", ".", "headers", ":", "value", "=", "''", "if", "'__col__'", "in", "column", ":", "if", "isinstance", "(", "column", "[", "'__col__'", "]", ","...
26.913043
22.043478
def callback(self, username, request): """ Having :username: return user's identifiers or None. """ credentials = self._get_credentials(request) if credentials: username, api_key = credentials if self.check: return self.check(username, api_key, request)
[ "def", "callback", "(", "self", ",", "username", ",", "request", ")", ":", "credentials", "=", "self", ".", "_get_credentials", "(", "request", ")", "if", "credentials", ":", "username", ",", "api_key", "=", "credentials", "if", "self", ".", "check", ":", ...
44.428571
9.857143
def validate_opts(opts, brokers_num): """Basic option validation. Returns True if the options are not valid, False otherwise. :param opts: the command line options :type opts: map :param brokers_num: the number of brokers :type brokers_num: integer :returns: bool """ if opts.skip < ...
[ "def", "validate_opts", "(", "opts", ",", "brokers_num", ")", ":", "if", "opts", ".", "skip", "<", "0", "or", "opts", ".", "skip", ">=", "brokers_num", ":", "print", "(", "\"Error: --skip must be >= 0 and < #brokers\"", ")", "return", "True", "if", "opts", "...
33.16
13.84
def update_warning(self): """Update the warning label, buttons state and sequence text.""" new_qsequence = self.new_qsequence new_sequence = self.new_sequence self.text_new_sequence.setText( new_qsequence.toString(QKeySequence.NativeText)) conflicts = self.che...
[ "def", "update_warning", "(", "self", ")", ":", "new_qsequence", "=", "self", ".", "new_qsequence", "new_sequence", "=", "self", ".", "new_sequence", "self", ".", "text_new_sequence", ".", "setText", "(", "new_qsequence", ".", "toString", "(", "QKeySequence", "....
43.854545
14.272727
def _partition(s, sep, find): """ (str|unicode).(partition|rpartition) for Python 2.4/2.5. """ idx = find(sep) if idx != -1: left = s[0:idx] return left, sep, s[len(left)+len(sep):]
[ "def", "_partition", "(", "s", ",", "sep", ",", "find", ")", ":", "idx", "=", "find", "(", "sep", ")", "if", "idx", "!=", "-", "1", ":", "left", "=", "s", "[", "0", ":", "idx", "]", "return", "left", ",", "sep", ",", "s", "[", "len", "(", ...
26.25
12.5
def options(self, context, module_options): ''' PATH Path to the file containing raw shellcode to inject PROCID Process ID to inject into (default: current powershell process) ''' if not 'PATH' in module_options: context.log.error('PATH option is requir...
[ "def", "options", "(", "self", ",", "context", ",", "module_options", ")", ":", "if", "not", "'PATH'", "in", "module_options", ":", "context", ".", "log", ".", "error", "(", "'PATH option is required!'", ")", "exit", "(", "1", ")", "self", ".", "shellcode_...
35.666667
25.47619
def get_mean_and_stddevs(self, sctx, rctx, dctx, imt, stddev_types): """ Returns the mean and standard deviations """ # Return Distance Tables imls = self._return_tables(rctx.mag, imt, "IMLs") # Get distance vector for the given magnitude idx = numpy.searchsorted(...
[ "def", "get_mean_and_stddevs", "(", "self", ",", "sctx", ",", "rctx", ",", "dctx", ",", "imt", ",", "stddev_types", ")", ":", "# Return Distance Tables", "imls", "=", "self", ".", "_return_tables", "(", "rctx", ".", "mag", ",", "imt", ",", "\"IMLs\"", ")",...
41.076923
13.230769
def get_json(self): """Create JSON data for slot. :returns: JSON data for slot as follows: { "@SlotIdx":0, "OnboardControllers":{ "OnboardController": [ ] }, "AddOnCards":{ ...
[ "def", "get_json", "(", "self", ")", ":", "json", "=", "self", ".", "get_basic_json", "(", ")", "if", "self", ".", "onboard_cards", ":", "json", "[", "'OnboardControllers'", "]", "=", "{", "'OnboardController'", ":", "[", "c", ".", "get_json", "(", ")", ...
28.25
16.392857
def secure(self): ''' Creates a hard link to the target file in the vault directory and saves information about the target file in the database ''' verbose('Saving information about target into conman database') self._id = self.db.insertTarget(self.name, self.path...
[ "def", "secure", "(", "self", ")", ":", "verbose", "(", "'Saving information about target into conman database'", ")", "self", ".", "_id", "=", "self", ".", "db", ".", "insertTarget", "(", "self", ".", "name", ",", "self", ".", "path", ")", "verbose", "(", ...
40.333333
25.5
def tanh_warp_arb(X, l1, l2, lw, x0): r"""Warps the `X` coordinate with the tanh model .. math:: l = \frac{l_1 + l_2}{2} - \frac{l_1 - l_2}{2}\tanh\frac{x-x_0}{l_w} Parameters ---------- X : :py:class:`Array`, (`M`,) or scalar float `M` locations to evaluate length sca...
[ "def", "tanh_warp_arb", "(", "X", ",", "l1", ",", "l2", ",", "lw", ",", "x0", ")", ":", "if", "isinstance", "(", "X", ",", "scipy", ".", "ndarray", ")", ":", "if", "isinstance", "(", "X", ",", "scipy", ".", "matrix", ")", ":", "X", "=", "scipy"...
34.645161
20.935484
def call_fdel(self, obj) -> None: """Remove the predefined custom value and call the delete function.""" self.fdel(obj) try: del vars(obj)[self.name] except KeyError: pass
[ "def", "call_fdel", "(", "self", ",", "obj", ")", "->", "None", ":", "self", ".", "fdel", "(", "obj", ")", "try", ":", "del", "vars", "(", "obj", ")", "[", "self", ".", "name", "]", "except", "KeyError", ":", "pass" ]
31.571429
13.857143
def write_reaction(self, value_dict): con = self.connection or self._connect() self._initialize(con) cur = con.cursor() ase_ids = value_dict['ase_ids'] energy_corrections = value_dict.get('energy_corrections', {}) key_list = get_key_list(start_index=1) values = ...
[ "def", "write_reaction", "(", "self", ",", "value_dict", ")", ":", "con", "=", "self", ".", "connection", "or", "self", ".", "_connect", "(", ")", "self", ".", "_initialize", "(", "con", ")", "cur", "=", "con", ".", "cursor", "(", ")", "ase_ids", "="...
31.695652
18.043478
def compute_process_sigmas(self, dt, fx=None, **fx_args): """ computes the values of sigmas_f. Normally a user would not call this, but it is useful if you need to call update more than once between calls to predict (to update for multiple simultaneous measurements), so the sigma...
[ "def", "compute_process_sigmas", "(", "self", ",", "dt", ",", "fx", "=", "None", ",", "*", "*", "fx_args", ")", ":", "if", "fx", "is", "None", ":", "fx", "=", "self", ".", "fx", "# calculate sigma points for given mean and covariance", "sigmas", "=", "self",...
37.235294
22.176471
def get_firmware(self): """Get the current firmware version.""" self.get_status() try: self.firmware = self.data['fw_version'] except TypeError: self.firmware = 'Unknown' return self.firmware
[ "def", "get_firmware", "(", "self", ")", ":", "self", ".", "get_status", "(", ")", "try", ":", "self", ".", "firmware", "=", "self", ".", "data", "[", "'fw_version'", "]", "except", "TypeError", ":", "self", ".", "firmware", "=", "'Unknown'", "return", ...
27.555556
15.666667
async def create_payment_address(wallet_handle: int, payment_method: str, config: str) -> str: """ Create the payment address for specified payment method This method generates private part of payment address and stores it in a secur...
[ "async", "def", "create_payment_address", "(", "wallet_handle", ":", "int", ",", "payment_method", ":", "str", ",", "config", ":", "str", ")", "->", "str", ":", "logger", "=", "logging", ".", "getLogger", "(", "__name__", ")", "logger", ".", "debug", "(", ...
40.326087
23.065217
def predict(self, X): """ Perform classification on an array of test vectors X. Parameters ---------- X : array-like, shape = [n_samples, n_features] Returns ------- C : array, shape = [n_samples] Predicted target values for X """ ...
[ "def", "predict", "(", "self", ",", "X", ")", ":", "jll", "=", "self", ".", "_joint_log_likelihood", "(", "X", ")", "return", "delayed", "(", "self", ".", "classes_", ")", "[", "da", ".", "argmax", "(", "jll", ",", "axis", "=", "1", ")", "]" ]
31.384615
13.538462
def find_le(self, dt): '''Find the index corresponding to the rightmost value less than or equal to *dt*. If *dt* is less than :func:`dynts.TimeSeries.end` a :class:`dynts.exceptions.LeftOutOfBound` exception will raise. *dt* must be a python datetime.date instance.''' i = bisect_right(self.dat...
[ "def", "find_le", "(", "self", ",", "dt", ")", ":", "i", "=", "bisect_right", "(", "self", ".", "dates", ",", "dt", ")", "if", "i", ":", "return", "i", "-", "1", "raise", "LeftOutOfBound" ]
32.083333
14.583333
def v_reference_leaf_leafref(ctx, stmt): """Verify that all leafrefs in a leaf or leaf-list have correct path""" if (hasattr(stmt, 'i_leafref') and stmt.i_leafref is not None and stmt.i_leafref_expanded is False): path_type_spec = stmt.i_leafref not_req_inst = not(path_type_spec...
[ "def", "v_reference_leaf_leafref", "(", "ctx", ",", "stmt", ")", ":", "if", "(", "hasattr", "(", "stmt", ",", "'i_leafref'", ")", "and", "stmt", ".", "i_leafref", "is", "not", "None", "and", "stmt", ".", "i_leafref_expanded", "is", "False", ")", ":", "pa...
41.391304
11.521739
def get_prefix(self, include_version=True): """Return the appropriate URL prefix to prepend to requests, based on the host provided in settings. """ host = settings.host if '://' not in host: host = 'https://%s' % host.strip('/') elif host.startswith('http://'...
[ "def", "get_prefix", "(", "self", ",", "include_version", "=", "True", ")", ":", "host", "=", "settings", ".", "host", "if", "'://'", "not", "in", "host", ":", "host", "=", "'https://%s'", "%", "host", ".", "strip", "(", "'/'", ")", "elif", "host", "...
43.826087
18.826087
def update(self, reservation_status=values.unset, worker_activity_sid=values.unset, instruction=values.unset, dequeue_post_work_activity_sid=values.unset, dequeue_from=values.unset, dequeue_record=values.unset, dequeue_timeout=values.unset, dequeue_to=values.u...
[ "def", "update", "(", "self", ",", "reservation_status", "=", "values", ".", "unset", ",", "worker_activity_sid", "=", "values", ".", "unset", ",", "instruction", "=", "values", ".", "unset", ",", "dequeue_post_work_activity_sid", "=", "values", ".", "unset", ...
62.09816
28.797546
def list_tag(self, limit=500, offset=0): """List `all` the tags for this Thing Returns lists of tags, as below #!python [ "mytag1", "mytag2" "ein_name", "nochein_name" ] - OR... Raises...
[ "def", "list_tag", "(", "self", ",", "limit", "=", "500", ",", "offset", "=", "0", ")", ":", "evt", "=", "self", ".", "_client", ".", "_request_entity_tag_list", "(", "self", ".", "__lid", ",", "limit", "=", "limit", ",", "offset", "=", "offset", ")"...
32.689655
26.62069