text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
async def post(self): """ Funds from account to given address. 1. Verify signature 2. Freeze senders amount. 3. Request to withdraw server. 4. Call balances sub_frozen method. Accepts: - message [dict]: - coinid [string] - amount [integer] - address [string] - timestamp [float] - r...
[ "async", "def", "post", "(", "self", ")", ":", "# Sign-verifying functional", "if", "settings", ".", "SIGNATURE_VERIFICATION", ":", "super", "(", ")", ".", "verify", "(", ")", "logging", ".", "debug", "(", "\"\\n\\n[+] -- Withdraw debugging\"", ")", "# Get data fr...
27.653543
0.037658
def get_present_child(self, parent, locator, params=None, timeout=None, visible=False): """ Get child-element present in the DOM. If timeout is 0 (zero) return WebElement instance or None, else we wait and retry for timeout and raise TimeoutException should the element not be found. ...
[ "def", "get_present_child", "(", "self", ",", "parent", ",", "locator", ",", "params", "=", "None", ",", "timeout", "=", "None", ",", "visible", "=", "False", ")", ":", "return", "self", ".", "get_present_element", "(", "locator", ",", "params", ",", "ti...
49.866667
0.009186
def _divide(divisor, remainder, quotient, remainders, base, precision=None): """ Given a divisor and dividend, continue until precision in is reached. :param int divisor: the divisor :param int remainder: the remainder :param int base: the base :param precision: maximum ...
[ "def", "_divide", "(", "divisor", ",", "remainder", ",", "quotient", ",", "remainders", ",", "base", ",", "precision", "=", "None", ")", ":", "# pylint: disable=too-many-arguments", "indices", "=", "itertools", ".", "count", "(", ")", "if", "precision", "is", ...
33.90625
0.001792
def get_app_dir(app_name, roaming=True, force_posix=False): r"""Returns the config folder for the application. The default behavior is to return whatever is most appropriate for the operating system. To give you an idea, for an app called ``"Foo Bar"``, something like the following folders could be re...
[ "def", "get_app_dir", "(", "app_name", ",", "roaming", "=", "True", ",", "force_posix", "=", "False", ")", ":", "if", "WIN", ":", "key", "=", "roaming", "and", "'APPDATA'", "or", "'LOCALAPPDATA'", "folder", "=", "os", ".", "environ", ".", "get", "(", "...
40.020408
0.000996
def atlas_get_peer( peer_hostport, peer_table=None ): """ Get the given peer's info """ ret = None with AtlasPeerTableLocked(peer_table) as ptbl: ret = ptbl.get(peer_hostport, None) return ret
[ "def", "atlas_get_peer", "(", "peer_hostport", ",", "peer_table", "=", "None", ")", ":", "ret", "=", "None", "with", "AtlasPeerTableLocked", "(", "peer_table", ")", "as", "ptbl", ":", "ret", "=", "ptbl", ".", "get", "(", "peer_hostport", ",", "None", ")", ...
21.7
0.013274
def Scan(self, matcher): """Yields spans occurrences of a given pattern within the chunk. Only matches that span over regular (non-overlapped) chunk bytes are returned. Matches lying completely within the overlapped zone are ought to be returned by the previous chunk. Args: matcher: A `Match...
[ "def", "Scan", "(", "self", ",", "matcher", ")", ":", "position", "=", "0", "while", "True", ":", "span", "=", "matcher", ".", "Match", "(", "self", ".", "data", ",", "position", ")", "if", "span", "is", "None", ":", "return", "# We are not interested ...
34.03125
0.011607
def _process_refs(x, labels): """Strips surrounding curly braces and adds modifiers to the attributes of Cite elements. Only references with labels in the 'labels' list are processed. Repeats processing (via decorator) until no more broken references are found.""" # Scan the element list x for Ci...
[ "def", "_process_refs", "(", "x", ",", "labels", ")", ":", "# Scan the element list x for Cite elements with known labels", "for", "i", ",", "v", "in", "enumerate", "(", "x", ")", ":", "if", "v", "[", "'t'", "]", "==", "'Cite'", "and", "len", "(", "v", "["...
37.466667
0.000867
def conference_hangup(self, call_params): """REST Conference Hangup helper """ path = '/' + self.api_version + '/ConferenceHangup/' method = 'POST' return self.request(path, method, call_params)
[ "def", "conference_hangup", "(", "self", ",", "call_params", ")", ":", "path", "=", "'/'", "+", "self", ".", "api_version", "+", "'/ConferenceHangup/'", "method", "=", "'POST'", "return", "self", ".", "request", "(", "path", ",", "method", ",", "call_params"...
38.166667
0.008547
def _validate_certificate_url(self, cert_url): # type: (str) -> None """Validate the URL containing the certificate chain. This method validates if the URL provided adheres to the format mentioned here : https://developer.amazon.com/docs/custom-skills/host-a-custom-skill-as-a-we...
[ "def", "_validate_certificate_url", "(", "self", ",", "cert_url", ")", ":", "# type: (str) -> None", "parsed_url", "=", "urlparse", "(", "cert_url", ")", "protocol", "=", "parsed_url", ".", "scheme", "if", "protocol", ".", "lower", "(", ")", "!=", "CERT_CHAIN_UR...
46.333333
0.001626
def getOxum(dataPath): """ Calculate the oxum for a given path """ fileCount = 0L fileSizeTotal = 0L for root, dirs, files in os.walk(dataPath): for fileName in files: fullName = os.path.join(root, fileName) stats = os.stat(fullName) fileSizeTotal += ...
[ "def", "getOxum", "(", "dataPath", ")", ":", "fileCount", "=", "0L", "fileSizeTotal", "=", "0L", "for", "root", ",", "dirs", ",", "files", "in", "os", ".", "walk", "(", "dataPath", ")", ":", "for", "fileName", "in", "files", ":", "fullName", "=", "os...
28.214286
0.002451
def doc(self): """Get the document tree from a parser context. """ ret = libxml2mod.xmlParserGetDoc(self._o) if ret is None:raise parserError('xmlParserGetDoc() failed') __tmp = xmlDoc(_obj=ret) return __tmp
[ "def", "doc", "(", "self", ")", ":", "ret", "=", "libxml2mod", ".", "xmlParserGetDoc", "(", "self", ".", "_o", ")", "if", "ret", "is", "None", ":", "raise", "parserError", "(", "'xmlParserGetDoc() failed'", ")", "__tmp", "=", "xmlDoc", "(", "_obj", "=", ...
40.333333
0.016194
def write_info (self, url_data): """Write url_data.info.""" self.write(self.part("info") + self.spaces("info")) self.writeln(self.wrap(url_data.info, 65), color=self.colorinfo)
[ "def", "write_info", "(", "self", ",", "url_data", ")", ":", "self", ".", "write", "(", "self", ".", "part", "(", "\"info\"", ")", "+", "self", ".", "spaces", "(", "\"info\"", ")", ")", "self", ".", "writeln", "(", "self", ".", "wrap", "(", "url_da...
49.25
0.015
def diff(a, n=1): """ Calculate the n-th discrete difference along given axis. The first difference is given by ``out[n] = a[n+1] - a[n]`` along the given axis, higher differences are calculated by using `diff` recursively. :param a: The list to calculate the diff on :param n: The order of ...
[ "def", "diff", "(", "a", ",", "n", "=", "1", ")", ":", "if", "n", "==", "0", ":", "return", "a", "if", "n", "<", "0", ":", "raise", "ValueError", "(", "\"order must be non-negative but got \"", "+", "repr", "(", "n", ")", ")", "b", "=", "map", "(...
27.956522
0.001504
def phytozome(args): """ %prog phytozome species Retrieve genomes and annotations from phytozome FTP. Available species listed below. Use comma to give a list of species to download. For example: $ %prog phytozome Athaliana,Vvinifera,Osativa,Sbicolor,Slycopersicum """ from jcvi.formats.gff...
[ "def", "phytozome", "(", "args", ")", ":", "from", "jcvi", ".", "formats", ".", "gff", "import", "bed", "as", "gff_bed", "from", "jcvi", ".", "formats", ".", "fasta", "import", "format", "as", "fasta_format", "p", "=", "OptionParser", "(", "phytozome", "...
38.105263
0.000898
def diff_speed(sw_dens=1.028, dens_gcm3=1.053, seal_length=300, seal_girth=200, Cd=0.09): '''Calculate terminal velocity of animal with a body size Args ---- sw_dens: float Density of seawater (g/cm^3) dens_gcm3: float Density of animal (g/cm^3) seal_length: float ...
[ "def", "diff_speed", "(", "sw_dens", "=", "1.028", ",", "dens_gcm3", "=", "1.053", ",", "seal_length", "=", "300", ",", "seal_girth", "=", "200", ",", "Cd", "=", "0.09", ")", ":", "import", "numpy", "surf", ",", "vol", "=", "surf_vol", "(", "seal_lengt...
25.355556
0.001688
def republish_collection(cursor, ident_hash, version): """Republish the collection identified as ``ident_hash`` with the given ``version``. """ if not isinstance(version, (list, tuple,)): split_version = version.split('.') if len(split_version) == 1: split_version.append(None...
[ "def", "republish_collection", "(", "cursor", ",", "ident_hash", ",", "version", ")", ":", "if", "not", "isinstance", "(", "version", ",", "(", "list", ",", "tuple", ",", ")", ")", ":", "split_version", "=", "version", ".", "split", "(", "'.'", ")", "i...
34.150943
0.000537
def normalize(cls, name): """Return string in all lower case with spaces and question marks removed""" name = name.lower() # lower-case for _replace in [' ','-','(',')','?']: name = name.replace(_replace,'') return name
[ "def", "normalize", "(", "cls", ",", "name", ")", ":", "name", "=", "name", ".", "lower", "(", ")", "# lower-case", "for", "_replace", "in", "[", "' '", ",", "'-'", ",", "'('", ",", "')'", ",", "'?'", "]", ":", "name", "=", "name", ".", "replace"...
43
0.034221
def _set_contents(self, force=False): """ Encodes all child objects into the contents for this object. This method is overridden because a Set needs to be encoded by removing defaulted fields and then sorting the fields by tag. :param force: Ensure all contents are ...
[ "def", "_set_contents", "(", "self", ",", "force", "=", "False", ")", ":", "if", "self", ".", "children", "is", "None", ":", "self", ".", "_parse_children", "(", ")", "child_tag_encodings", "=", "[", "]", "for", "index", ",", "child", "in", "enumerate", ...
35.0625
0.001735
def get_active_config(config_option, default=None): """ gets the config value associated with the config_option or returns an empty string if the config is not found :param config_option: :param default: if not None, will be used :return: value of config. If key is not in config, then default will be used if ...
[ "def", "get_active_config", "(", "config_option", ",", "default", "=", "None", ")", ":", "return", "_active_config", ".", "mapping", "[", "config_option", "]", "if", "default", "is", "None", "else", "_active_config", ".", "mapping", ".", "get", "(", "config_op...
55.666667
0.013752
def desaturate_pal(color, prop, reverse=False): """ Create a palette that desaturate a color by some proportion Parameters ---------- color : matplotlib color hex, rgb-tuple, or html color name prop : float saturation channel of color will be multiplied by this value ...
[ "def", "desaturate_pal", "(", "color", ",", "prop", ",", "reverse", "=", "False", ")", ":", "if", "not", "0", "<=", "prop", "<=", "1", ":", "raise", "ValueError", "(", "\"prop must be between 0 and 1\"", ")", "# Get rgb tuple rep", "# Convert to hls", "# Desatur...
29.25
0.000752
def rename_file( source_path, target_path, allow_undo=True, no_confirm=False, rename_on_collision=True, silent=False, extra_flags=0, hWnd=None ): """Perform a shell-based file rename. Renaming in this way allows the possibility of undo, auto-renaming, and showing the "flying ...
[ "def", "rename_file", "(", "source_path", ",", "target_path", ",", "allow_undo", "=", "True", ",", "no_confirm", "=", "False", ",", "rename_on_collision", "=", "True", ",", "silent", "=", "False", ",", "extra_flags", "=", "0", ",", "hWnd", "=", "None", ")"...
24.482759
0.001355
def default_malformed_message_handler(worker, exc_info, message_parts): """The default malformed message handler for :class:`Worker`. It warns as a :exc:`MalformedMessage`. """ exc_type, exc, tb = exc_info exc_strs = traceback.format_exception_only(exc_type, exc) exc_str = exc_strs[0].strip() ...
[ "def", "default_malformed_message_handler", "(", "worker", ",", "exc_info", ",", "message_parts", ")", ":", "exc_type", ",", "exc", ",", "tb", "=", "exc_info", "exc_strs", "=", "traceback", ".", "format_exception_only", "(", "exc_type", ",", "exc", ")", "exc_str...
43.7
0.002242
def resize_widget(self, widget, row_span, col_span): """Resize a widget in the grid to new dimensions. Parameters ---------- widget : Widget The widget to resize row_span : int The number of rows to be occupied by this widget. col_span : int ...
[ "def", "resize_widget", "(", "self", ",", "widget", ",", "row_span", ",", "col_span", ")", ":", "row", "=", "None", "col", "=", "None", "for", "(", "r", ",", "c", ",", "rspan", ",", "cspan", ",", "w", ")", "in", "self", ".", "_grid_widgets", ".", ...
28
0.002381
def open(cls, sock, chunk_type, isatty, chunk_eof_type=None, buf_size=None, select_timeout=None): """Yields the write side of a pipe that will copy appropriately chunked values to a socket.""" with cls.open_multi(sock, (chunk_type,), (isatty,), ...
[ "def", "open", "(", "cls", ",", "sock", ",", "chunk_type", ",", "isatty", ",", "chunk_eof_type", "=", "None", ",", "buf_size", "=", "None", ",", "select_timeout", "=", "None", ")", ":", "with", "cls", ".", "open_multi", "(", "sock", ",", "(", "chunk_ty...
47.777778
0.009132
def corr_bin_genes(self, number_of_features=None, input_gene=None): """A (hacky) method for binning groups of genes correlated along the SAM manifold. Parameters ---------- number_of_features - int, optional, default None The number of genes to bin. Capped at 5000 du...
[ "def", "corr_bin_genes", "(", "self", ",", "number_of_features", "=", "None", ",", "input_gene", "=", "None", ")", ":", "weights", "=", "self", ".", "adata", ".", "var", "[", "'spatial_dispersions'", "]", ".", "values", "all_gene_names", "=", "np", ".", "a...
37.738095
0.000615
def get_metadata(filename, scan, paramfile='', **kwargs): """ Parses sdm file to define metadata for observation, including scan info, image grid parameters, pipeline memory usage, etc. Mirrors parsems.get_metadata(). If paramfile defined, it will use it (filename or RT.Params instance ok). """ ...
[ "def", "get_metadata", "(", "filename", ",", "scan", ",", "paramfile", "=", "''", ",", "*", "*", "kwargs", ")", ":", "# create primary state dictionary", "d", "=", "{", "}", "# set workdir", "d", "[", "'filename'", "]", "=", "os", ".", "path", ".", "absp...
41.022222
0.001164
def arp(self): """dict: trill link details """ xmlns = 'urn:brocade.com:mgmt:brocade-arp' get_arp_info = ET.Element('get-arp', xmlns=xmlns) results = self._callback(get_arp_info, handler='get') result = [] for item in results.findall('{%s}arp-entry' % xmln...
[ "def", "arp", "(", "self", ")", ":", "xmlns", "=", "'urn:brocade.com:mgmt:brocade-arp'", "get_arp_info", "=", "ET", ".", "Element", "(", "'get-arp'", ",", "xmlns", "=", "xmlns", ")", "results", "=", "self", ".", "_callback", "(", "get_arp_info", ",", "handle...
49.68
0.00158
def merge_headers(event): """ Merge the values of headers and multiValueHeaders into a single dict. Opens up support for multivalue headers via API Gateway and ALB. See: https://github.com/Miserlou/Zappa/pull/1756 """ headers = event.get('headers') or {} multi_headers = (event.get('multiValu...
[ "def", "merge_headers", "(", "event", ")", ":", "headers", "=", "event", ".", "get", "(", "'headers'", ")", "or", "{", "}", "multi_headers", "=", "(", "event", ".", "get", "(", "'multiValueHeaders'", ")", "or", "{", "}", ")", ".", "copy", "(", ")", ...
39.928571
0.001748
def diff_dumps(ih1, ih2, tofile=None, name1="a", name2="b", n_context=3): """Diff 2 IntelHex objects and produce unified diff output for their hex dumps. @param ih1 first IntelHex object to compare @param ih2 second IntelHex object to compare @param tofile file-like object to writ...
[ "def", "diff_dumps", "(", "ih1", ",", "ih2", ",", "tofile", "=", "None", ",", "name1", "=", "\"a\"", ",", "name2", "=", "\"b\"", ",", "n_context", "=", "3", ")", ":", "def", "prepare_lines", "(", "ih", ")", ":", "sio", "=", "StringIO", "(", ")", ...
39.08
0.001998
def _compute_type(self, proctype): """Computes tendencies due to all subprocesses of given type ``'proctype'``. Also pass all diagnostics up to parent process.""" tendencies = {} for varname in self.state: tendencies[varname] = 0. * self.state[varname] for proc in sel...
[ "def", "_compute_type", "(", "self", ",", "proctype", ")", ":", "tendencies", "=", "{", "}", "for", "varname", "in", "self", ".", "state", ":", "tendencies", "[", "varname", "]", "=", "0.", "*", "self", ".", "state", "[", "varname", "]", "for", "proc...
50.384615
0.002247
def application(environ, start_response): """WSGI interface: start an URL check.""" # the environment variable CONTENT_LENGTH may be empty or missing try: request_body_size = int(environ.get('CONTENT_LENGTH', 0)) except ValueError: request_body_size = 0 # When the method is POST the...
[ "def", "application", "(", "environ", ",", "start_response", ")", ":", "# the environment variable CONTENT_LENGTH may be empty or missing", "try", ":", "request_body_size", "=", "int", "(", "environ", ".", "get", "(", "'CONTENT_LENGTH'", ",", "0", ")", ")", "except", ...
37.857143
0.001227
def describe(cls, sha1): """Returns a human-readable representation of the given SHA1.""" # For now we invoke git-describe(1), but eventually we will be # able to do this via pygit2, since libgit2 already provides # an API for this: # https://github.com/libgit2/pygit2/pull/459...
[ "def", "describe", "(", "cls", ",", "sha1", ")", ":", "# For now we invoke git-describe(1), but eventually we will be", "# able to do this via pygit2, since libgit2 already provides", "# an API for this:", "# https://github.com/libgit2/pygit2/pull/459#issuecomment-68866929", "# https://g...
37.90625
0.001608
def handle_range(schema, field, validator, parent_schema): """Adds validation logic for ``marshmallow.validate.Range``, setting the values appropriately ``fields.Number`` and it's subclasses. Args: schema (dict): The original JSON schema we generated. This is what we want to post-proces...
[ "def", "handle_range", "(", "schema", ",", "field", ",", "validator", ",", "parent_schema", ")", ":", "if", "not", "isinstance", "(", "field", ",", "fields", ".", "Number", ")", ":", "return", "schema", "if", "validator", ".", "min", ":", "schema", "[", ...
34.242424
0.000861
def query_db_reference(): """ Returns list of cross references by query parameters --- tags: - Query functions parameters: - name: type_ in: query type: string required: false description: Reference type default: EMBL - name: identifier ...
[ "def", "query_db_reference", "(", ")", ":", "args", "=", "get_args", "(", "request_args", "=", "request", ".", "args", ",", "allowed_str_args", "=", "[", "'type_'", ",", "'identifier'", ",", "'entry_name'", "]", ",", "allowed_int_args", "=", "[", "'limit'", ...
20.130435
0.00103
def islink(path): """os.path.islink() but return True for junction points on Windows. """ if platform.system() == "Windows": if sys.version_info[:2] < (3, 5): try: # pylint: disable=undefined-variable attrs = ctypes.windll.kernel32.GetFileAttributesW(unico...
[ "def", "islink", "(", "path", ")", ":", "if", "platform", ".", "system", "(", ")", "==", "\"Windows\"", ":", "if", "sys", ".", "version_info", "[", ":", "2", "]", "<", "(", "3", ",", "5", ")", ":", "try", ":", "# pylint: disable=undefined-variable", ...
42.894737
0.002401
def stop(self, sig=signal.SIGTERM): """ stop the scheduler and stop all processes """ if self.pid is None: self.pid = self.read_pid() if self.pid is None: sp = BackgroundProcess.objects.filter(pk=1).first() if sp: self.pid = sp...
[ "def", "stop", "(", "self", ",", "sig", "=", "signal", ".", "SIGTERM", ")", ":", "if", "self", ".", "pid", "is", "None", ":", "self", ".", "pid", "=", "self", ".", "read_pid", "(", ")", "if", "self", ".", "pid", "is", "None", ":", "sp", "=", ...
34.785714
0.001332
def template(cls, userdata): """Create a template instance used for message callbacks.""" ud = Userdata(cls.normalize(cls.create_empty(None), userdata)) return ud
[ "def", "template", "(", "cls", ",", "userdata", ")", ":", "ud", "=", "Userdata", "(", "cls", ".", "normalize", "(", "cls", ".", "create_empty", "(", "None", ")", ",", "userdata", ")", ")", "return", "ud" ]
45.75
0.010753
def assert_is_not_none(expr, msg_fmt="{msg}"): """Fail if the expression is None. >>> assert_is_not_none(0) >>> assert_is_not_none(None) Traceback (most recent call last): ... AssertionError: expression is None The following msg_fmt arguments are supported: * msg - the default erro...
[ "def", "assert_is_not_none", "(", "expr", ",", "msg_fmt", "=", "\"{msg}\"", ")", ":", "if", "expr", "is", "None", ":", "msg", "=", "\"expression is None\"", "fail", "(", "msg_fmt", ".", "format", "(", "msg", "=", "msg", ",", "expr", "=", "expr", ")", "...
28.625
0.002114
def _authenticate_cram_md5(credentials, sock_info): """Authenticate using CRAM-MD5 (RFC 2195) """ source = credentials.source username = credentials.username password = credentials.password # The password used as the mac key is the # same as what we use for MONGODB-CR passwd = _password_...
[ "def", "_authenticate_cram_md5", "(", "credentials", ",", "sock_info", ")", ":", "source", "=", "credentials", ".", "source", "username", "=", "credentials", ".", "username", "password", "=", "credentials", ".", "password", "# The password used as the mac key is the", ...
41.695652
0.001019
def get_bit_num(bit_pattern): """Returns the lowest bit num from a given bit pattern. Returns None if no bits set. :param bit_pattern: The bit pattern. :type bit_pattern: int :returns: int -- the bit number :returns: None -- no bits set >>> pifacecommon.core.get_bit_num(0) None >>>...
[ "def", "get_bit_num", "(", "bit_pattern", ")", ":", "if", "bit_pattern", "==", "0", ":", "return", "None", "bit_num", "=", "0", "# assume bit 0", "while", "(", "bit_pattern", "&", "1", ")", "==", "0", ":", "bit_pattern", "=", "bit_pattern", ">>", "1", "b...
23.321429
0.001471
def _findKsubcatFeatures( sentence, kSubCatRelsLexicon, addFeaturesToK = True ): ''' Attempts to detect all possible K subcategorization relations from given sentence, using the heuristic methods _detectKsubcatRelType() and _detectPossibleKsubcatRelsFromSent(); Returns a dictionary...
[ "def", "_findKsubcatFeatures", "(", "sentence", ",", "kSubCatRelsLexicon", ",", "addFeaturesToK", "=", "True", ")", ":", "features", "=", "dict", "(", ")", "# Add features to the K (adposition)", "if", "addFeaturesToK", ":", "for", "i", "in", "range", "(", "len", ...
46.833333
0.011855
def plotCurve(self): """Shows a calibration curve, in a separate window, of the currently selected calibration""" try: attenuations, freqs = self.datafile.get_calibration(str(self.ui.calChoiceCmbbx.currentText()), self.calf) self.pw = SimplePlotWidget(freqs, attenuations, parent=...
[ "def", "plotCurve", "(", "self", ")", ":", "try", ":", "attenuations", ",", "freqs", "=", "self", ".", "datafile", ".", "get_calibration", "(", "str", "(", "self", ".", "ui", ".", "calChoiceCmbbx", ".", "currentText", "(", ")", ")", ",", "self", ".", ...
59.5
0.008276
def find_by_id(self, user, params={}, **options): """Returns the full user record for the single user with the provided ID. Parameters ---------- user : {String} An identifier for the user. Can be one of an email address, the globally unique identifier for the user, or the keyw...
[ "def", "find_by_id", "(", "self", ",", "user", ",", "params", "=", "{", "}", ",", "*", "*", "options", ")", ":", "path", "=", "\"/users/%s\"", "%", "(", "user", ")", "return", "self", ".", "client", ".", "get", "(", "path", ",", "params", ",", "*...
44.416667
0.009191
def find_gadget(elf, gadget, align=1, unique=True): """ Find a ROP gadget in a the executable sections of an ELF executable or library. The ROP gadget can be either a set of bytes for an exact match or a (bytes) regular expression. Once it finds gadgets, it uses the capstone engine to verify if the ...
[ "def", "find_gadget", "(", "elf", ",", "gadget", ",", "align", "=", "1", ",", "unique", "=", "True", ")", ":", "if", "not", "HAVE_CAPSTONE", ":", "raise", "NotImplementedError", "(", "'pwnypack requires capstone to find ROP gadgets'", ")", "if", "not", "isinstan...
36.263158
0.001413
def set_vm_status(self, device='FLOPPY', boot_option='BOOT_ONCE', write_protect='YES'): """Sets the Virtual Media drive status It sets the boot option for virtual media device. Note: boot option can be set only for CD device. :param device: virual media device ...
[ "def", "set_vm_status", "(", "self", ",", "device", "=", "'FLOPPY'", ",", "boot_option", "=", "'BOOT_ONCE'", ",", "write_protect", "=", "'YES'", ")", ":", "# CONNECT is a RIBCL call. There is no such property to set in Redfish.", "if", "boot_option", "==", "'CONNECT'", ...
43.868421
0.001761
def get_container_or_none(self, type_): """ Returns reference to the class declaration or None. """ type_ = type_traits.remove_alias(type_) type_ = type_traits.remove_cv(type_) utils.loggers.queries_engine.debug( "Container traits: cleaned up search %s", ty...
[ "def", "get_container_or_none", "(", "self", ",", "type_", ")", ":", "type_", "=", "type_traits", ".", "remove_alias", "(", "type_", ")", "type_", "=", "type_traits", ".", "remove_cv", "(", "type_", ")", "utils", ".", "loggers", ".", "queries_engine", ".", ...
43.107143
0.00081
def devices(self): """Return all devices on Arlo account.""" if self._all_devices: return self._all_devices self._all_devices = {} self._all_devices['cameras'] = [] self._all_devices['base_station'] = [] url = DEVICES_ENDPOINT data = self.query(url) ...
[ "def", "devices", "(", "self", ")", ":", "if", "self", ".", "_all_devices", ":", "return", "self", ".", "_all_devices", "self", ".", "_all_devices", "=", "{", "}", "self", ".", "_all_devices", "[", "'cameras'", "]", "=", "[", "]", "self", ".", "_all_de...
38.464286
0.001812
def set_orient(self): """ Return the computed orientation based on CD matrix. """ self.orient = RADTODEG(N.arctan2(self.cd12,self.cd22))
[ "def", "set_orient", "(", "self", ")", ":", "self", ".", "orient", "=", "RADTODEG", "(", "N", ".", "arctan2", "(", "self", ".", "cd12", ",", "self", ".", "cd22", ")", ")" ]
50
0.019737
def expr_str(expr, sc_expr_str_fn=standard_sc_expr_str): """ Returns the string representation of the expression 'expr', as in a Kconfig file. Passing subexpressions of expressions to this function works as expected. sc_expr_str_fn (default: standard_sc_expr_str): This function is called for...
[ "def", "expr_str", "(", "expr", ",", "sc_expr_str_fn", "=", "standard_sc_expr_str", ")", ":", "if", "expr", ".", "__class__", "is", "not", "tuple", ":", "return", "sc_expr_str_fn", "(", "expr", ")", "if", "expr", "[", "0", "]", "is", "AND", ":", "return"...
40.52381
0.000574
def from_hdf5(hdf5, anno_id=None): """ Converts an HDF5 file to a RAMON object. Returns an object that is a child- -class of RAMON (though it's determined at run-time what type is returned). Accessing multiple IDs from the same file is not supported, because it's not dramatically faster to access e...
[ "def", "from_hdf5", "(", "hdf5", ",", "anno_id", "=", "None", ")", ":", "if", "anno_id", "is", "None", ":", "# The user just wants the first item we find, so... Yeah.", "return", "from_hdf5", "(", "hdf5", ",", "list", "(", "hdf5", ".", "keys", "(", ")", ")", ...
34.311111
0.00063
def _bisect_kmeans(X, n_clusters, n_trials, max_iter, tol): """ Apply Bisecting Kmeans clustering to reach n_clusters number of clusters """ membs = np.empty(shape=X.shape[0], dtype=int) centers = dict() #np.empty(shape=(n_clusters,X.shape[1]), dtype=float) sse_arr = dict() #-1.0*np.ones(sha...
[ "def", "_bisect_kmeans", "(", "X", ",", "n_clusters", ",", "n_trials", ",", "max_iter", ",", "tol", ")", ":", "membs", "=", "np", ".", "empty", "(", "shape", "=", "X", ".", "shape", "[", "0", "]", ",", "dtype", "=", "int", ")", "centers", "=", "d...
41.6875
0.01416
def GetTZInfo(tzname='UTC', utcOffset=None, dst=None): """ Get / Add timezone info """ key = (tzname, utcOffset, dst) tzInfo = TZManager._tzInfos.get(key) if not tzInfo: tzInfo = TZInfo(tzname, utcOffset, dst) TZManager._tzInfos[key] = tzInfo return tzInfo
[ "def", "GetTZInfo", "(", "tzname", "=", "'UTC'", ",", "utcOffset", "=", "None", ",", "dst", "=", "None", ")", ":", "key", "=", "(", "tzname", ",", "utcOffset", ",", "dst", ")", "tzInfo", "=", "TZManager", ".", "_tzInfos", ".", "get", "(", "key", ")...
37.125
0.029605
def likelihood(args): """ %prog likelihood Plot likelihood surface. Look for two files in the current folder: - 100_100.log, haploid model - 100_20.log, diploid model """ p = OptionParser(likelihood.__doc__) opts, args, iopts = p.set_image_options(args, figsize="10x5", ...
[ "def", "likelihood", "(", "args", ")", ":", "p", "=", "OptionParser", "(", "likelihood", ".", "__doc__", ")", "opts", ",", "args", ",", "iopts", "=", "p", ".", "set_image_options", "(", "args", ",", "figsize", "=", "\"10x5\"", ",", "style", "=", "\"whi...
31.242424
0.00141
def _get_p_p_id_and_contract(self): """Get id of consumption profile.""" contracts = {} try: raw_res = yield from self._session.get(PROFILE_URL, timeout=self._timeout) except OSError: raise PyHydroQuebecError("Can...
[ "def", "_get_p_p_id_and_contract", "(", "self", ")", ":", "contracts", "=", "{", "}", "try", ":", "raw_res", "=", "yield", "from", "self", ".", "_session", ".", "get", "(", "PROFILE_URL", ",", "timeout", "=", "self", ".", "_timeout", ")", "except", "OSEr...
40.575758
0.001459
def IntegerAddition(left: vertex_constructor_param_types, right: vertex_constructor_param_types, label: Optional[str]=None) -> Vertex: """ Adds one vertex to another :param left: a vertex to add :param right: a vertex to add """ return Integer(context.jvm_view().IntegerAdditionVertex, label...
[ "def", "IntegerAddition", "(", "left", ":", "vertex_constructor_param_types", ",", "right", ":", "vertex_constructor_param_types", ",", "label", ":", "Optional", "[", "str", "]", "=", "None", ")", "->", "Vertex", ":", "return", "Integer", "(", "context", ".", ...
46.875
0.015707
def __computeDecomp(self): """ Compute optimal dedomposition, each sub-domain has the same volume in index space. @return list if successful, empty list if not successful """ primeNumbers = [getPrimeFactors(d) for d in self.globalDims] ns = [len(pns) for pns in p...
[ "def", "__computeDecomp", "(", "self", ")", ":", "primeNumbers", "=", "[", "getPrimeFactors", "(", "d", ")", "for", "d", "in", "self", ".", "globalDims", "]", "ns", "=", "[", "len", "(", "pns", ")", "for", "pns", "in", "primeNumbers", "]", "validDecomp...
37.967742
0.000828
def translate_and_compute_bleu(estimator, subtokenizer, bleu_source, bleu_ref): """Translate file and report the cased and uncased bleu scores.""" # Create temporary file to store translation. tmp = tempfile.NamedTemporaryFile(delete=False) tmp_filename = tmp.name translate.translate_file( estimator, s...
[ "def", "translate_and_compute_bleu", "(", "estimator", ",", "subtokenizer", ",", "bleu_source", ",", "bleu_ref", ")", ":", "# Create temporary file to store translation.", "tmp", "=", "tempfile", ".", "NamedTemporaryFile", "(", "delete", "=", "False", ")", "tmp_filename...
43.066667
0.016667
def isoline_vmag(hemi, isolines=None, surface='midgray', min_length=2, **kw): ''' isoline_vmag(hemi) calculates the visual magnification function f using the default set of iso-lines (as returned by neuropythy.vision.visual_isolines()). The hemi argument may alternately be a mesh object. isoline...
[ "def", "isoline_vmag", "(", "hemi", ",", "isolines", "=", "None", ",", "surface", "=", "'midgray'", ",", "min_length", "=", "2", ",", "*", "*", "kw", ")", ":", "from", "neuropythy", ".", "util", "import", "(", "curry", ",", "zinv", ")", "from", "neur...
63.5
0.022643
def BC_Rigidity(self): """ Utility function to help implement boundary conditions by specifying them for and applying them to the elastic thickness grid """ ######################################### # FLEXURAL RIGIDITY BOUNDARY CONDITIONS # ######################################### # W...
[ "def", "BC_Rigidity", "(", "self", ")", ":", "#########################################", "# FLEXURAL RIGIDITY BOUNDARY CONDITIONS #", "#########################################", "# West", "if", "self", ".", "BC_W", "==", "'Periodic'", ":", "self", ".", "BC_Rigidity_W", "=",...
40.586207
0.0235
def user(self, email: str) -> models.User: """Fetch a user from the database.""" return self.User.query.filter_by(email=email).first()
[ "def", "user", "(", "self", ",", "email", ":", "str", ")", "->", "models", ".", "User", ":", "return", "self", ".", "User", ".", "query", ".", "filter_by", "(", "email", "=", "email", ")", ".", "first", "(", ")" ]
49.333333
0.013333
def get_process_token(): """ Get the current process token """ token = wintypes.HANDLE() res = process.OpenProcessToken( process.GetCurrentProcess(), process.TOKEN_ALL_ACCESS, token) if not res > 0: raise RuntimeError("Couldn't get process token") return token
[ "def", "get_process_token", "(", ")", ":", "token", "=", "wintypes", ".", "HANDLE", "(", ")", "res", "=", "process", ".", "OpenProcessToken", "(", "process", ".", "GetCurrentProcess", "(", ")", ",", "process", ".", "TOKEN_ALL_ACCESS", ",", "token", ")", "i...
26.2
0.0369
def friends(self, delegate, params={}, extra_args=None): """Get updates from friends. Calls the delgate once for each status object received.""" return self.__get('/statuses/friends_timeline.xml', delegate, params, txml.Statuses, extra_args=extra_args)
[ "def", "friends", "(", "self", ",", "delegate", ",", "params", "=", "{", "}", ",", "extra_args", "=", "None", ")", ":", "return", "self", ".", "__get", "(", "'/statuses/friends_timeline.xml'", ",", "delegate", ",", "params", ",", "txml", ".", "Statuses", ...
47.333333
0.010381
def bind(self): """ Resets the Response object to its factory defaults. """ self._COOKIES = None self.status = 200 self.headers = HeaderDict() self.content_type = 'text/html; charset=UTF-8'
[ "def", "bind", "(", "self", ")", ":", "self", ".", "_COOKIES", "=", "None", "self", ".", "status", "=", "200", "self", ".", "headers", "=", "HeaderDict", "(", ")", "self", ".", "content_type", "=", "'text/html; charset=UTF-8'" ]
37.333333
0.008734
def _dump_inline_table(section): """Preserve inline table in its compact syntax instead of expanding into subsection. https://github.com/toml-lang/toml#user-content-inline-table """ retval = "" if isinstance(section, dict): val_list = [] for k, v in section.items(): ...
[ "def", "_dump_inline_table", "(", "section", ")", ":", "retval", "=", "\"\"", "if", "isinstance", "(", "section", ",", "dict", ")", ":", "val_list", "=", "[", "]", "for", "k", ",", "v", "in", "section", ".", "items", "(", ")", ":", "val", "=", "_du...
31.5
0.001927
def select_content_type(requested, available): """Selects the best content type. :param requested: a sequence of :class:`.ContentType` instances :param available: a sequence of :class:`.ContentType` instances that the server is capable of producing :returns: the selected content type (from ``a...
[ "def", "select_content_type", "(", "requested", ",", "available", ")", ":", "class", "Match", "(", "object", ")", ":", "\"\"\"Sorting assistant.\n\n Sorting matches is a tricky business. We need a way to\n prefer content types by *specificity*. The definition of\n ...
43.12766
0.000241
def create_qgis_pdf_output( impact_report, output_path, layout, file_format, metadata): """Produce PDF output using QgsLayout. :param output_path: The output path. :type output_path: str :param layout: QGIS Layout object. :type layout: qgis.core.QgsPrintLayo...
[ "def", "create_qgis_pdf_output", "(", "impact_report", ",", "output_path", ",", "layout", ",", "file_format", ",", "metadata", ")", ":", "# make sure directory is created", "dirname", "=", "os", ".", "path", ".", "dirname", "(", "output_path", ")", "if", "not", ...
35.848485
0.000411
def __archive_fetch(fh, archive, fromTime, untilTime): """ Fetch data from a single archive. Note that checks for validity of the time period requested happen above this level so it's possible to wrap around the archive on a read and request data older than the archive's retention """ fromInterval = int( fromTime -...
[ "def", "__archive_fetch", "(", "fh", ",", "archive", ",", "fromTime", ",", "untilTime", ")", ":", "fromInterval", "=", "int", "(", "fromTime", "-", "(", "fromTime", "%", "archive", "[", "'secondsPerPoint'", "]", ")", ")", "+", "archive", "[", "'secondsPerP...
42.125
0.025009
def file(ui, repo, clname, pat, *pats, **opts): """assign files to or remove files from a change list Assign files to or (with -d) remove files from a change list. The -d option only removes files from the change list. It does not edit them or remove them from the repository. """ if codereview_disabled: raise...
[ "def", "file", "(", "ui", ",", "repo", ",", "clname", ",", "pat", ",", "*", "pats", ",", "*", "*", "opts", ")", ":", "if", "codereview_disabled", ":", "raise", "hg_util", ".", "Abort", "(", "codereview_disabled", ")", "pats", "=", "tuple", "(", "[", ...
25.52459
0.032777
def model_delta(old_model, new_model): """ Provides delta/difference between two models :param old: The old state of the model instance. :type old: Model :param new: The new state of the model instance. :type new: Model :return: A dictionary with the names of the changed fields as keys and a...
[ "def", "model_delta", "(", "old_model", ",", "new_model", ")", ":", "delta", "=", "{", "}", "fields", "=", "new_model", ".", "_meta", ".", "fields", "for", "field", "in", "fields", ":", "old_value", "=", "get_field_value", "(", "old_model", ",", "field", ...
30.538462
0.001221
def _mmc_loop(self, rounds, temp=298.15, verbose=True): """The main MMC loop. Parameters ---------- rounds : int The number of rounds of optimisation to perform. temp : float, optional The temperature (in K) used during the optimisation. verbose :...
[ "def", "_mmc_loop", "(", "self", ",", "rounds", ",", "temp", "=", "298.15", ",", "verbose", "=", "True", ")", ":", "# TODO add weighted randomisation of altered variable", "current_round", "=", "0", "while", "current_round", "<", "rounds", ":", "modifiable", "=", ...
45.54386
0.001508
def get_sequence_rule_enablers_by_search(self, sequence_rule_enabler_query, sequence_rule_enabler_search): """Pass through to provider SequenceRuleEnablerSearchSession.get_sequence_rule_enablers_by_search""" # Implemented from azosid template for - # osid.resource.ResourceSearchSession.get_resou...
[ "def", "get_sequence_rule_enablers_by_search", "(", "self", ",", "sequence_rule_enabler_query", ",", "sequence_rule_enabler_search", ")", ":", "# Implemented from azosid template for -", "# osid.resource.ResourceSearchSession.get_resources_by_search_template", "if", "not", "self", ".",...
77.714286
0.009091
def padding(self): """The `(left, right)` padding required for the IFFT :type: `tuple` of `int` """ pad = self.ntiles - self.windowsize return (int((pad - 1)/2.), int((pad + 1)/2.))
[ "def", "padding", "(", "self", ")", ":", "pad", "=", "self", ".", "ntiles", "-", "self", ".", "windowsize", "return", "(", "int", "(", "(", "pad", "-", "1", ")", "/", "2.", ")", ",", "int", "(", "(", "pad", "+", "1", ")", "/", "2.", ")", ")...
30.857143
0.009009
def file_generator(self, filepaths, max_chars_per_file=None, max_chars_total=None): """Read complete text of input files and yield unicode strings. By default, one unicode string is produced per file, but this is not guaranteed, since subclasse...
[ "def", "file_generator", "(", "self", ",", "filepaths", ",", "max_chars_per_file", "=", "None", ",", "max_chars_total", "=", "None", ")", ":", "chars_total", "=", "0", "for", "fname", "in", "filepaths", ":", "chars_this_file", "=", "0", "tf", ".", "logging",...
36.435897
0.00891
def verify_no_new_dims(input_shapes, output_shape): """Verifies that all dimensions in the output are in at least one input. Args: input_shapes: a list of Shapes output_shape: a Shape Raises: ValueError: if there are new dimensions in the output. """ all_input_dims = set(sum([s.dims for s in inpu...
[ "def", "verify_no_new_dims", "(", "input_shapes", ",", "output_shape", ")", ":", "all_input_dims", "=", "set", "(", "sum", "(", "[", "s", ".", "dims", "for", "s", "in", "input_shapes", "]", ",", "[", "]", ")", ")", "all_output_dims", "=", "set", "(", "...
36.9375
0.008251
def enter_mainloop(target, mapped_args=None, args=None, kwargs=None, pool=None, pool_size=None, callback=None, queue=None): ''' Manage a multiprocessing pool - If the queue d...
[ "def", "enter_mainloop", "(", "target", ",", "mapped_args", "=", "None", ",", "args", "=", "None", ",", "kwargs", "=", "None", ",", "pool", "=", "None", ",", "pool_size", "=", "None", ",", "callback", "=", "None", ",", "queue", "=", "None", ")", ":",...
33.157895
0.000308
def ordering_url(self, field_name): """ Creates a url link for sorting the given field. The direction of sorting will be either ascending, if the field is not yet sorted, or the opposite of the current sorting if sorted. """ path = self.request.path direction = "...
[ "def", "ordering_url", "(", "self", ",", "field_name", ")", ":", "path", "=", "self", ".", "request", ".", "path", "direction", "=", "\"\"", "query_params", "=", "self", ".", "request", ".", "GET", ".", "copy", "(", ")", "ordering", "=", "self", ".", ...
39.805556
0.001362
def _get_magic_menu(self,menuidentifier, menulabel=None): """return a submagic menu by name, and create it if needed parameters: ----------- menulabel : str Label for the menu Will infere the menu name from the identifier at creation if menulabel not given. ...
[ "def", "_get_magic_menu", "(", "self", ",", "menuidentifier", ",", "menulabel", "=", "None", ")", ":", "menu", "=", "self", ".", "_magic_menu_dict", ".", "get", "(", "menuidentifier", ",", "None", ")", "if", "not", "menu", ":", "if", "not", "menulabel", ...
39.7
0.01845
def soldOutForRole(self,role,includeTemporaryRegs=False): ''' Accepts a DanceRole object and responds if the number of registrations for that role exceeds the capacity for that role at this event. ''' return self.numRegisteredForRole( role,includeTemporaryRegs=include...
[ "def", "soldOutForRole", "(", "self", ",", "role", ",", "includeTemporaryRegs", "=", "False", ")", ":", "return", "self", ".", "numRegisteredForRole", "(", "role", ",", "includeTemporaryRegs", "=", "includeTemporaryRegs", ")", ">=", "(", "self", ".", "capacityFo...
52.142857
0.018868
def without_tz(request): """ Get the time without TZ enabled """ t = Template('{% load tz %}{% get_current_timezone as TIME_ZONE %}{{ TIME_ZONE }}') c = RequestContext(request) response = t.render(c) return HttpResponse(response)
[ "def", "without_tz", "(", "request", ")", ":", "t", "=", "Template", "(", "'{% load tz %}{% get_current_timezone as TIME_ZONE %}{{ TIME_ZONE }}'", ")", "c", "=", "RequestContext", "(", "request", ")", "response", "=", "t", ".", "render", "(", "c", ")", "return", ...
25.5
0.015152
def _get_signature(self, message): """ [MS-NLMP] v28.0 2016-07-14 3.4.4 Message Signature Functions Will create the signature based on the message to send to the server. Depending on the negotiate_flags set this could either be an NTLMv1 signature or NTLMv2 with Extended Session...
[ "def", "_get_signature", "(", "self", ",", "message", ")", ":", "signature", "=", "calc_signature", "(", "message", ",", "self", ".", "negotiate_flags", ",", "self", ".", "outgoing_signing_key", ",", "self", ".", "outgoing_seq_num", ",", "self", ".", "outgoing...
48
0.008174
def _parse_bridge_opts(opts, iface): ''' Filters given options and outputs valid settings for BRIDGING_OPTS If an option has a value that is not expected, this function will log the Interface, Setting and what was expected. ''' config = {} if 'ports' in opts: if isinstance(opts['por...
[ "def", "_parse_bridge_opts", "(", "opts", ",", "iface", ")", ":", "config", "=", "{", "}", "if", "'ports'", "in", "opts", ":", "if", "isinstance", "(", "opts", "[", "'ports'", "]", ",", "list", ")", ":", "opts", "[", "'ports'", "]", "=", "' '", "."...
34.956522
0.000403
def resolve(cls, propname, objcls=None): ''' resolve type of the class property for the class. If objcls is not set then assume that cls argument (class that the function is called from) is the class we are trying to resolve the type for :param cls: :param ...
[ "def", "resolve", "(", "cls", ",", "propname", ",", "objcls", "=", "None", ")", ":", "# object class is not given", "if", "objcls", "is", "None", ":", "objcls", "=", "cls", "# get type", "typemap", "=", "cls", ".", "_types", ".", "get", "(", "objcls", ")...
36.052632
0.009957
def drop_table(dbo, tablename, schema=None, commit=True): """ Drop a database table. Keyword arguments: dbo : database object DB-API 2.0 connection, callable returning a DB-API 2.0 cursor, or SQLAlchemy connection, engine or session tablename : text Name of the table sc...
[ "def", "drop_table", "(", "dbo", ",", "tablename", ",", "schema", "=", "None", ",", "commit", "=", "True", ")", ":", "# sanitise table name", "tablename", "=", "_quote", "(", "tablename", ")", "if", "schema", "is", "not", "None", ":", "tablename", "=", "...
25.32
0.001522
def open(self): """initialize visit variables and statistics """ self._tryfinallys = [] self.stats = self.linter.add_stats(module=0, function=0, method=0, class_=0)
[ "def", "open", "(", "self", ")", ":", "self", ".", "_tryfinallys", "=", "[", "]", "self", ".", "stats", "=", "self", ".", "linter", ".", "add_stats", "(", "module", "=", "0", ",", "function", "=", "0", ",", "method", "=", "0", ",", "class_", "=",...
38.4
0.015306
def initialize(self): """initialize in base class""" self._lb = [b[0] for b in self.bounds] # can be done more efficiently? self._ub = [b[1] for b in self.bounds]
[ "def", "initialize", "(", "self", ")", ":", "self", ".", "_lb", "=", "[", "b", "[", "0", "]", "for", "b", "in", "self", ".", "bounds", "]", "# can be done more efficiently?", "self", ".", "_ub", "=", "[", "b", "[", "1", "]", "for", "b", "in", "se...
46
0.010695
def _convert(self, payload): """ Converts payload to a string. Complex objects are dumped to json """ if not isinstance(payload, six.string_types): payload = json.dumps(payload, cls=DefaultJSONEncoder, sort_keys=True) return str(payload)
[ "def", "_convert", "(", "self", ",", "payload", ")", ":", "if", "not", "isinstance", "(", "payload", ",", "six", ".", "string_types", ")", ":", "payload", "=", "json", ".", "dumps", "(", "payload", ",", "cls", "=", "DefaultJSONEncoder", ",", "sort_keys",...
40.428571
0.010381
def sample(self, **params): """Stream statuses/sample :param \*\*params: Parameters to send with your stream request Accepted params found at: https://developer.twitter.com/en/docs/tweets/sample-realtime/api-reference/get-statuses-sample """ url = 'https://stream.twitte...
[ "def", "sample", "(", "self", ",", "*", "*", "params", ")", ":", "url", "=", "'https://stream.twitter.com/%s/statuses/sample.json'", "%", "self", ".", "streamer", ".", "api_version", "self", ".", "streamer", ".", "_request", "(", "url", ",", "params", "=", "...
39.545455
0.008989
def update_exc(exc, msg, before=True, separator="\n"): """ Adds additional text to an exception's error message. The new text will be added before the existing text by default; to append it after the original text, pass False to the `before` parameter. By default the old and new text will be separ...
[ "def", "update_exc", "(", "exc", ",", "msg", ",", "before", "=", "True", ",", "separator", "=", "\"\\n\"", ")", ":", "emsg", "=", "exc", ".", "message", "if", "before", ":", "parts", "=", "(", "msg", ",", "separator", ",", "emsg", ")", "else", ":",...
33.85
0.001437
def setup (self): ''' Runs only the first time SimpleSteem() is instantiated. Prompts user for the values that are then written to config.py ''' mainaccount = self.add_quotes(self.enter_config_value("mainaccount", 'ned')) keys = self.enter_config_value("keys", '[]') ...
[ "def", "setup", "(", "self", ")", ":", "mainaccount", "=", "self", ".", "add_quotes", "(", "self", ".", "enter_config_value", "(", "\"mainaccount\"", ",", "'ned'", ")", ")", "keys", "=", "self", ".", "enter_config_value", "(", "\"keys\"", ",", "'[]'", ")",...
59.75
0.014413
def _save_settings(self): """ Saves all the parameters to a text file. """ if self._autosettings_path == None: return # Get the gui settings directory gui_settings_dir = _os.path.join(_cwd, 'egg_settings') # make sure the directory exists if not ...
[ "def", "_save_settings", "(", "self", ")", ":", "if", "self", ".", "_autosettings_path", "==", "None", ":", "return", "# Get the gui settings directory", "gui_settings_dir", "=", "_os", ".", "path", ".", "join", "(", "_cwd", ",", "'egg_settings'", ")", "# make s...
36.434783
0.010465
def run(self, refant=[], antsel=[], uvrange='', fluxname='', fluxname_full='', band='', spw0='', spw1='', flaglist=[]): """ Run calibration pipeline. Assumes L-band. refant is list of antenna name strings (e.g., ['ea10']). default is to calculate based on distance from array center. antsel is li...
[ "def", "run", "(", "self", ",", "refant", "=", "[", "]", ",", "antsel", "=", "[", "]", ",", "uvrange", "=", "''", ",", "fluxname", "=", "''", ",", "fluxname_full", "=", "''", ",", "band", "=", "''", ",", "spw0", "=", "''", ",", "spw1", "=", "...
36.5625
0.001525
def decode_cpu_id(self, cpuid): """Decode the CPU id into a string""" ret = () for i in cpuid.split(':'): ret += (eval('0x' + i),) return ret
[ "def", "decode_cpu_id", "(", "self", ",", "cpuid", ")", ":", "ret", "=", "(", ")", "for", "i", "in", "cpuid", ".", "split", "(", "':'", ")", ":", "ret", "+=", "(", "eval", "(", "'0x'", "+", "i", ")", ",", ")", "return", "ret" ]
25.714286
0.010753
def createGroup(self, networkId, body, verbose=None): """ Create a new group in the network specified by the parameter `networkId`. The contents are specified the message body. :param networkId: SUID of the Network :param body: New Group name and contents :param verbose: print m...
[ "def", "createGroup", "(", "self", ",", "networkId", ",", "body", ",", "verbose", "=", "None", ")", ":", "PARAMS", "=", "set_param", "(", "[", "'networkId'", ",", "'body'", "]", ",", "[", "networkId", ",", "body", "]", ")", "response", "=", "api", "(...
41.285714
0.015228
def _parse_settings_bond(opts, iface): ''' Filters given options and outputs valid settings for requested operation. If an option has a value that is not expected, this function will log what the Interface, Setting and what it was expecting. ''' bond_def = { # 803.ad aggregation sel...
[ "def", "_parse_settings_bond", "(", "opts", ",", "iface", ")", ":", "bond_def", "=", "{", "# 803.ad aggregation selection logic", "# 0 for stable (default)", "# 1 for bandwidth", "# 2 for count", "'ad_select'", ":", "'0'", ",", "# Max number of transmit queues (default = 16)", ...
42.705882
0.00101
def observed(func): """ Just like :meth:`Observable.observed`. .. deprecated:: 1.99.1 """ def wrapper(*args, **kwargs): self = args[0] assert(isinstance(self, Observable)) self._notify_method_before(self, func.__name__, args, kwargs) res = func(*args, **kwargs) ...
[ "def", "observed", "(", "func", ")", ":", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", "=", "args", "[", "0", "]", "assert", "(", "isinstance", "(", "self", ",", "Observable", ")", ")", "self", ".", "_notify_method...
28.368421
0.001795
def validate_commits(repo_dir, commits): """Test if a commit is valid for the repository.""" log.debug("Validating {c} exist in {r}".format(c=commits, r=repo_dir)) repo = Repo(repo_dir) for commit in commits: try: commit = repo.commit(commit) except Exception: msg...
[ "def", "validate_commits", "(", "repo_dir", ",", "commits", ")", ":", "log", ".", "debug", "(", "\"Validating {c} exist in {r}\"", ".", "format", "(", "c", "=", "commits", ",", "r", "=", "repo_dir", ")", ")", "repo", "=", "Repo", "(", "repo_dir", ")", "f...
43.533333
0.001499
def fmt_repr(obj): """ Return pretty printed string representation of an object. """ items = {k: v for k, v in list(obj.__dict__.items())} return "<%s: {%s}>" % (obj.__class__.__name__, pprint.pformat(items, width=1))
[ "def", "fmt_repr", "(", "obj", ")", ":", "items", "=", "{", "k", ":", "v", "for", "k", ",", "v", "in", "list", "(", "obj", ".", "__dict__", ".", "items", "(", ")", ")", "}", "return", "\"<%s: {%s}>\"", "%", "(", "obj", ".", "__class__", ".", "_...
31.714286
0.02193
def generatemetadata(self, parameters, parentfile, relevantinputfiles, provenancedata = None): """Generate metadata, given a filename, parameters and a dictionary of inputdata (necessary in case we copy from it)""" assert isinstance(provenancedata,CLAMProvenanceData) or provenancedata is None d...
[ "def", "generatemetadata", "(", "self", ",", "parameters", ",", "parentfile", ",", "relevantinputfiles", ",", "provenancedata", "=", "None", ")", ":", "assert", "isinstance", "(", "provenancedata", ",", "CLAMProvenanceData", ")", "or", "provenancedata", "is", "Non...
41.304348
0.009259
def clean(self, value): """Take a dirty value and clean it.""" if ( self.base_type is not None and value is not None and not isinstance(value, self.base_type) ): if isinstance(self.base_type, tuple): allowed_types = [typ.__name__ fo...
[ "def", "clean", "(", "self", ",", "value", ")", ":", "if", "(", "self", ".", "base_type", "is", "not", "None", "and", "value", "is", "not", "None", "and", "not", "isinstance", "(", "value", ",", "self", ".", "base_type", ")", ")", ":", "if", "isins...
35.96
0.002167
def _get_id(self): """ Get a unique state id. :rtype: int """ id_ = self._last_id.value self._last_id.value += 1 return id_
[ "def", "_get_id", "(", "self", ")", ":", "id_", "=", "self", ".", "_last_id", ".", "value", "self", ".", "_last_id", ".", "value", "+=", "1", "return", "id_" ]
19.111111
0.011111