text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def build_registered_span(self, span): """ Takes a BasicSpan and converts it into a registered JsonSpan """ data = Data(baggage=span.context.baggage) kind = 1 # entry if span.operation_name in self.exit_spans: kind = 2 # exit # log is a special case as it is not entr...
[ "def", "build_registered_span", "(", "self", ",", "span", ")", ":", "data", "=", "Data", "(", "baggage", "=", "span", ".", "context", ".", "baggage", ")", "kind", "=", "1", "# entry", "if", "span", ".", "operation_name", "in", "self", ".", "exit_spans", ...
48.256881
23.669725
def getClassAllSupers(self, aURI): """ note: requires SPARQL 1.1 2015-06-04: currenlty not used, inferred from above """ aURI = aURI try: qres = self.rdfgraph.query( """SELECT DISTINCT ?x WHERE { ...
[ "def", "getClassAllSupers", "(", "self", ",", "aURI", ")", ":", "aURI", "=", "aURI", "try", ":", "qres", "=", "self", ".", "rdfgraph", ".", "query", "(", "\"\"\"SELECT DISTINCT ?x\n WHERE {\n { <%s> rdfs:subClassOf+ ?x }\n ...
34
14.5
def get_status(self, device_id): """List only MyQ garage door devices.""" devices = self.get_devices() if devices != False: for device in devices: if device['door'] == device_id: return device['status'] return False
[ "def", "get_status", "(", "self", ",", "device_id", ")", ":", "devices", "=", "self", ".", "get_devices", "(", ")", "if", "devices", "!=", "False", ":", "for", "device", "in", "devices", ":", "if", "device", "[", "'door'", "]", "==", "device_id", ":", ...
28.8
14
def normalized(self): """Return a normalized version of the histogram where the values sum to one. """ total = self.total() result = Histogram() for value, count in iteritems(self): try: result[value] = count / float(total) except ...
[ "def", "normalized", "(", "self", ")", ":", "total", "=", "self", ".", "total", "(", ")", "result", "=", "Histogram", "(", ")", "for", "value", ",", "count", "in", "iteritems", "(", "self", ")", ":", "try", ":", "result", "[", "value", "]", "=", ...
34
15.071429
def parse_str(self, s): """ Parse entire file and return a :class:`Catchment` object. :param file_name: File path :type file_name: str :return: Parsed object :rtype: :class:`Catchment` """ root = ET.fromstring(s) return self._parse(root)
[ "def", "parse_str", "(", "self", ",", "s", ")", ":", "root", "=", "ET", ".", "fromstring", "(", "s", ")", "return", "self", ".", "_parse", "(", "root", ")" ]
27.272727
12
def merge_all(dcts): """ Shallow merge all the dcts :param dcts: :return: """ return reduce( lambda accum, dct: merge(accum, dct), dict(), dcts )
[ "def", "merge_all", "(", "dcts", ")", ":", "return", "reduce", "(", "lambda", "accum", ",", "dct", ":", "merge", "(", "accum", ",", "dct", ")", ",", "dict", "(", ")", ",", "dcts", ")" ]
17.363636
17.545455
def fixations(self): """ Returns all fixations that are on this image. A precondition for this to work is that a fixmat is associated with this Image object. """ if not self._fixations: raise RuntimeError('This Images object does not have' +' ...
[ "def", "fixations", "(", "self", ")", ":", "if", "not", "self", ".", "_fixations", ":", "raise", "RuntimeError", "(", "'This Images object does not have'", "+", "' an associated fixmat'", ")", "return", "self", ".", "_fixations", "[", "(", "self", ".", "_fixatio...
44
14.545455
def init_states(batch_size, num_lstm_layer, num_hidden): """ Returns name and shape of init states of LSTM network Parameters ---------- batch_size: list of tuple of str and tuple of int and int num_lstm_layer: int num_hidden: int Returns ------- list of tuple of str and tuple ...
[ "def", "init_states", "(", "batch_size", ",", "num_lstm_layer", ",", "num_hidden", ")", ":", "init_c", "=", "[", "(", "'l%d_init_c'", "%", "l", ",", "(", "batch_size", ",", "num_hidden", ")", ")", "for", "l", "in", "range", "(", "num_lstm_layer", ")", "]...
31.470588
23.823529
def run(self): """Build package and fix ordelist per checksum """ self.files_exist() self.info_file() sources = self.sources if len(sources) > 1 and self.sbo_sources != sources: sources = self.sbo_sources # If the list does not have the same order use ...
[ "def", "run", "(", "self", ")", ":", "self", ".", "files_exist", "(", ")", "self", ".", "info_file", "(", ")", "sources", "=", "self", ".", "sources", "if", "len", "(", "sources", ")", ">", "1", "and", "self", ".", "sbo_sources", "!=", "sources", "...
36.333333
15.25
def get_post_reference_section_keyword_patterns(): """Return a list of compiled regex patterns used to search for various keywords that can often be found after, and therefore suggest the end of, a reference section in a full-text document. @return: (list) of compiled regex patterns. """ ...
[ "def", "get_post_reference_section_keyword_patterns", "(", ")", ":", "compiled_patterns", "=", "[", "]", "patterns", "=", "[", "u'('", "+", "_create_regex_pattern_add_optional_spaces_to_word_characters", "(", "u'prepared'", ")", "+", "ur'|'", "+", "_create_regex_pattern_add...
56.52381
23.714286
def add_objects(self, bundle, wait_for_completion=True, poll_interval=1, timeout=60, accept=MEDIA_TYPE_TAXII_V20, content_type=MEDIA_TYPE_STIX_V20): """Implement the ``Add Objects`` endpoint (section 5.4) Add objects to the collection. This may be performed eith...
[ "def", "add_objects", "(", "self", ",", "bundle", ",", "wait_for_completion", "=", "True", ",", "poll_interval", "=", "1", ",", "timeout", "=", "60", ",", "accept", "=", "MEDIA_TYPE_TAXII_V20", ",", "content_type", "=", "MEDIA_TYPE_STIX_V20", ")", ":", "self",...
40.815789
24.894737
def sample_cleanup(data, sample): """ stats, cleanup, and link to samples """ ## get maxlen and depths array from clusters maxlens, depths = get_quick_depths(data, sample) try: depths.max() except ValueError: ## If depths is an empty array max() will raise print(" no clu...
[ "def", "sample_cleanup", "(", "data", ",", "sample", ")", ":", "## get maxlen and depths array from clusters", "maxlens", ",", "depths", "=", "get_quick_depths", "(", "data", ",", "sample", ")", "try", ":", "depths", ".", "max", "(", ")", "except", "ValueError",...
44.806452
24.989247
def autocommand(func): """ A simplified decorator for making a single function a Command instance. In the future this will leverage PEP0484 to do really smart function parsing and conversion to argparse actions. """ name = func.__name__ title, desc = command.parse_docstring(func) if not title: ...
[ "def", "autocommand", "(", "func", ")", ":", "name", "=", "func", ".", "__name__", "title", ",", "desc", "=", "command", ".", "parse_docstring", "(", "func", ")", "if", "not", "title", ":", "title", "=", "'Auto command for: %s'", "%", "name", "if", "not"...
43.416667
16.5
def ConvCnstrMOD(*args, **kwargs): """A wrapper function that dynamically defines a class derived from one of the implementations of the Convolutional Constrained MOD problems, and returns an object instantiated with the provided parameters. The wrapper is designed to allow the appropriate object to...
[ "def", "ConvCnstrMOD", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# Extract method selection argument or set default", "if", "'method'", "in", "kwargs", ":", "method", "=", "kwargs", "[", "'method'", "]", "del", "kwargs", "[", "'method'", "]", "else...
38.596154
20.019231
def overlay(overlay_name, dataset_uri, item_identifier): """Return abspath to file with item content. Fetches the file from remote storage if required. """ dataset = dtoolcore.DataSet.from_uri(dataset_uri) if overlay_name not in dataset.list_overlay_names(): click.secho( "No suc...
[ "def", "overlay", "(", "overlay_name", ",", "dataset_uri", ",", "item_identifier", ")", ":", "dataset", "=", "dtoolcore", ".", "DataSet", ".", "from_uri", "(", "dataset_uri", ")", "if", "overlay_name", "not", "in", "dataset", ".", "list_overlay_names", "(", ")...
29.75
20.291667
def populate_native_libraries(version): """Populates ``binary-extension.rst`` with release-specific data. Args: version (str): The current version. """ with open(BINARY_EXT_TEMPLATE, "r") as file_obj: template = file_obj.read() contents = template.format(revision=version) with o...
[ "def", "populate_native_libraries", "(", "version", ")", ":", "with", "open", "(", "BINARY_EXT_TEMPLATE", ",", "\"r\"", ")", "as", "file_obj", ":", "template", "=", "file_obj", ".", "read", "(", ")", "contents", "=", "template", ".", "format", "(", "revision...
34.636364
10.636364
def parse_issuer_cred(issuer_cred): """ Given an X509 PEM file in the form of a string, parses it into sections by the PEM delimiters of: -----BEGIN <label>----- and -----END <label>---- Confirms the sections can be decoded in the proxy credential order of: issuer cert, issuer private key, proxy cha...
[ "def", "parse_issuer_cred", "(", "issuer_cred", ")", ":", "# get each section of the PEM file", "sections", "=", "re", ".", "findall", "(", "\"-----BEGIN.*?-----.*?-----END.*?-----\"", ",", "issuer_cred", ",", "flags", "=", "re", ".", "DOTALL", ")", "try", ":", "iss...
41.956522
21.173913
def append_this_package_path(depth=1): """ this_package.py 에서 사용 import snipy.this_package """ from .caller import caller logg.debug('caller module %s', caller.modulename(depth + 1)) c = caller.abspath(depth + 1) logg.debug('caller path %s', c) p = guess_package_path(dirname(c)) ...
[ "def", "append_this_package_path", "(", "depth", "=", "1", ")", ":", "from", ".", "caller", "import", "caller", "logg", ".", "debug", "(", "'caller module %s'", ",", "caller", ".", "modulename", "(", "depth", "+", "1", ")", ")", "c", "=", "caller", ".", ...
26.777778
15.222222
def remove_tags(self, tags): """ Add tags to a server. Accepts tags as strings or Tag objects. """ if self.cloud_manager.remove_tags(self, tags): new_tags = [tag for tag in self.tags if tag not in tags] object.__setattr__(self, 'tags', new_tags)
[ "def", "remove_tags", "(", "self", ",", "tags", ")", ":", "if", "self", ".", "cloud_manager", ".", "remove_tags", "(", "self", ",", "tags", ")", ":", "new_tags", "=", "[", "tag", "for", "tag", "in", "self", ".", "tags", "if", "tag", "not", "in", "t...
42.142857
13.857143
def get_pdffilepath(pdffilename): """ Returns the path for the pdf file args: pdffilename: string returns path for the plots folder / pdffilename.pdf """ return FILEPATHSTR.format( root_dir=ROOT_DIR, os_sep=os.sep, os_extsep=os.extsep, ...
[ "def", "get_pdffilepath", "(", "pdffilename", ")", ":", "return", "FILEPATHSTR", ".", "format", "(", "root_dir", "=", "ROOT_DIR", ",", "os_sep", "=", "os", ".", "sep", ",", "os_extsep", "=", "os", ".", "extsep", ",", "name", "=", "pdffilename", ",", "fol...
33.428571
16.285714
def is_in_data_type_range(self, raise_exception=True): """Check if collection values are in physically possible ranges for the data_type. If this method returns False, the Data Collection's data is physically or mathematically impossible for the data_type.""" return self._header.data_ty...
[ "def", "is_in_data_type_range", "(", "self", ",", "raise_exception", "=", "True", ")", ":", "return", "self", ".", "_header", ".", "data_type", ".", "is_in_range", "(", "self", ".", "_values", ",", "self", ".", "_header", ".", "unit", ",", "raise_exception",...
55.857143
16
def propagate(p0, angle, d, deg=True, bearing=False, r=r_earth_mean): """ Given an initial point and angle, move distance d along the surface Parameters ---------- p0 : point-like (or array of point-like) [lon, lat] objects angle : float (or array of float) bearing. Note that by default...
[ "def", "propagate", "(", "p0", ",", "angle", ",", "d", ",", "deg", "=", "True", ",", "bearing", "=", "False", ",", "r", "=", "r_earth_mean", ")", ":", "single", ",", "(", "p0", ",", "angle", ",", "d", ")", "=", "_to_arrays", "(", "(", "p0", ","...
29.892857
22.964286
def fts_count(self, fts, inv): """Return the count of segments in an inventory matching a given feature mask. Args: fts (set): feature mask given as a set of (value, feature) tuples inv (set): inventory of segments (as Unicode IPA strings) Returns: i...
[ "def", "fts_count", "(", "self", ",", "fts", ",", "inv", ")", ":", "return", "len", "(", "list", "(", "filter", "(", "lambda", "s", ":", "self", ".", "fts_match", "(", "fts", ",", "s", ")", ",", "inv", ")", ")", ")" ]
37.833333
24.25
def remove_dhcp_server(self, server): """Removes the DHCP server settings in server of type :class:`IDHCPServer` DHCP server settings to be removed raises :class:`OleErrorInvalidarg` Host network interface @a name already exists. """ if not isin...
[ "def", "remove_dhcp_server", "(", "self", ",", "server", ")", ":", "if", "not", "isinstance", "(", "server", ",", "IDHCPServer", ")", ":", "raise", "TypeError", "(", "\"server can only be an instance of type IDHCPServer\"", ")", "self", ".", "_call", "(", "\"remov...
35.142857
14.428571
def create_arj (archive, compression, cmd, verbosity, interactive, filenames): """Create an ARJ archive.""" cmdlist = [cmd, 'a', '-r'] if not interactive: cmdlist.append('-y') cmdlist.append(archive) cmdlist.extend(filenames) return cmdlist
[ "def", "create_arj", "(", "archive", ",", "compression", ",", "cmd", ",", "verbosity", ",", "interactive", ",", "filenames", ")", ":", "cmdlist", "=", "[", "cmd", ",", "'a'", ",", "'-r'", "]", "if", "not", "interactive", ":", "cmdlist", ".", "append", ...
33.125
15.375
def contains_pyversion(marker): """Check whether a marker contains a python_version operand. """ if not marker: return False marker = _ensure_marker(marker) return _markers_contains_pyversion(marker._markers)
[ "def", "contains_pyversion", "(", "marker", ")", ":", "if", "not", "marker", ":", "return", "False", "marker", "=", "_ensure_marker", "(", "marker", ")", "return", "_markers_contains_pyversion", "(", "marker", ".", "_markers", ")" ]
28.75
13.875
def parse_glyphs_filter(filter_str, is_pre=False): """Parses glyphs custom filter string into a dict object that ufo2ft can consume. Reference: ufo2ft: https://github.com/googlei18n/ufo2ft Glyphs 2.3 Handbook July 2016, p184 Args: filter_str - a string of...
[ "def", "parse_glyphs_filter", "(", "filter_str", ",", "is_pre", "=", "False", ")", ":", "elements", "=", "filter_str", ".", "split", "(", "\";\"", ")", "if", "elements", "[", "0", "]", "==", "\"\"", ":", "logger", ".", "error", "(", "\"Failed to parse glyp...
32.192308
17.615385
def _get_embedded(self, name): ''' Return an embedded struct object to calculate the size or use _tobytes(True) to convert just the embedded parts. :param name: either the original type, or the name of the original type. It is always the type used in type de...
[ "def", "_get_embedded", "(", "self", ",", "name", ")", ":", "if", "hasattr", "(", "name", ",", "'readablename'", ")", ":", "name", "=", "name", ".", "readablename", "t", ",", "i", "=", "self", ".", "_target", ".", "_embedded_indices", "[", "name", "]",...
41.142857
25.714286
def _do_parse(inp, fmt, encoding, force_types): """Actually parse input. Args: inp: bytes yielding file-like object fmt: format to use for parsing encoding: encoding of `inp` force_types: if `True`, integers, floats, booleans and none/null are recogni...
[ "def", "_do_parse", "(", "inp", ",", "fmt", ",", "encoding", ",", "force_types", ")", ":", "res", "=", "{", "}", "_check_lib_installed", "(", "fmt", ",", "'parse'", ")", "if", "fmt", "==", "'ini'", ":", "cfg", "=", "configobj", ".", "ConfigObj", "(", ...
38.538462
19.788462
def transitive_closure(m, orig, rel): ''' Generate the closure over a transitive relationship in depth-first fashion ''' #FIXME: Broken for now links = list(m.match(orig, rel)) for link in links: yield link[0][TARGET] yield from transitive_closure(m, target, rel)
[ "def", "transitive_closure", "(", "m", ",", "orig", ",", "rel", ")", ":", "#FIXME: Broken for now", "links", "=", "list", "(", "m", ".", "match", "(", "orig", ",", "rel", ")", ")", "for", "link", "in", "links", ":", "yield", "link", "[", "0", "]", ...
32.777778
18.555556
def version_parts(version): """ Split a version string into numeric X.Y.Z part and the rest (milestone). """ m = re.match(r'(\d+(?:\.\d+)*)([.%]|$)(.*)', version) if m: numver = m.group(1) rest = m.group(2) + m.group(3) return numver, rest else: return version, ''
[ "def", "version_parts", "(", "version", ")", ":", "m", "=", "re", ".", "match", "(", "r'(\\d+(?:\\.\\d+)*)([.%]|$)(.*)'", ",", "version", ")", "if", "m", ":", "numver", "=", "m", ".", "group", "(", "1", ")", "rest", "=", "m", ".", "group", "(", "2", ...
28.181818
15.454545
def label( self, node ): """Return textual description of this node""" result = [] if node.get('type'): result.append( node['type'] ) if node.get('name' ): result.append( node['name'] ) elif node.get('value') is not None: result.append( unicode...
[ "def", "label", "(", "self", ",", "node", ")", ":", "result", "=", "[", "]", "if", "node", ".", "get", "(", "'type'", ")", ":", "result", ".", "append", "(", "node", "[", "'type'", "]", ")", "if", "node", ".", "get", "(", "'name'", ")", ":", ...
41.578947
11.210526
def get_assignee(self, login): """ given the user login, looks for a user in assignee list of the repo and return it if was found. """ if not login: return GithubObject.NotSet if not hasattr(self, '_assignees'): self._assignees = {c.login: c for c ...
[ "def", "get_assignee", "(", "self", ",", "login", ")", ":", "if", "not", "login", ":", "return", "GithubObject", ".", "NotSet", "if", "not", "hasattr", "(", "self", ",", "'_assignees'", ")", ":", "self", ".", "_assignees", "=", "{", "c", ".", "login", ...
41.461538
14.384615
def add_scheduling_block(config): """Adds a scheduling block to the database, returning a response object""" try: DB.add_sbi(config) except jsonschema.ValidationError as error: error_dict = error.__dict__ for key in error_dict: error_dict[key] = error_dict[key].__str__() ...
[ "def", "add_scheduling_block", "(", "config", ")", ":", "try", ":", "DB", ".", "add_sbi", "(", "config", ")", "except", "jsonschema", ".", "ValidationError", "as", "error", ":", "error_dict", "=", "error", ".", "__dict__", "for", "key", "in", "error_dict", ...
45.636364
15.181818
def handle_pkg_lic(self, p_term, predicate, builder_func): """Handles package lics concluded or declared.""" try: for _, _, licenses in self.graph.triples((p_term, predicate, None)): if (licenses, RDF.type, self.spdx_namespace['ConjunctiveLicenseSet']) in self.graph: ...
[ "def", "handle_pkg_lic", "(", "self", ",", "p_term", ",", "predicate", ",", "builder_func", ")", ":", "try", ":", "for", "_", ",", "_", ",", "licenses", "in", "self", ".", "graph", ".", "triples", "(", "(", "p_term", ",", "predicate", ",", "None", ")...
50.05
24.3
def install_translations(config): """Add check translations according to ``config`` as a fallback to existing translations""" if not config: return from . import _translation checks_translation = gettext.translation(domain=config["domain"], localedi...
[ "def", "install_translations", "(", "config", ")", ":", "if", "not", "config", ":", "return", "from", ".", "import", "_translation", "checks_translation", "=", "gettext", ".", "translation", "(", "domain", "=", "config", "[", "\"domain\"", "]", ",", "localedir...
42.090909
23.454545
async def Claim(self, claims): ''' claims : typing.Sequence[~SingularClaim] Returns -> typing.Sequence[~ErrorResult] ''' # map input types to rpc msg _params = dict() msg = dict(type='Singular', request='Claim', version=2, ...
[ "async", "def", "Claim", "(", "self", ",", "claims", ")", ":", "# map input types to rpc msg", "_params", "=", "dict", "(", ")", "msg", "=", "dict", "(", "type", "=", "'Singular'", ",", "request", "=", "'Claim'", ",", "version", "=", "2", ",", "params", ...
30.714286
11.571429
def inter_data_operation(self, axis, func, other): """Apply a function that requires two BaseFrameManager objects. Args: axis: The axis to apply the function over (0 - rows, 1 - columns) func: The function to apply other: The other BaseFrameManager object to apply fu...
[ "def", "inter_data_operation", "(", "self", ",", "axis", ",", "func", ",", "other", ")", ":", "if", "axis", ":", "partitions", "=", "self", ".", "row_partitions", "other_partitions", "=", "other", ".", "row_partitions", "else", ":", "partitions", "=", "self"...
37.517241
19.793103
def video_category(self): """doc: http://open.youku.com/docs/doc?id=90 """ url = 'https://openapi.youku.com/v2/schemas/video/category.json' r = requests.get(url) check_error(r) return r.json()
[ "def", "video_category", "(", "self", ")", ":", "url", "=", "'https://openapi.youku.com/v2/schemas/video/category.json'", "r", "=", "requests", ".", "get", "(", "url", ")", "check_error", "(", "r", ")", "return", "r", ".", "json", "(", ")" ]
33.428571
13.285714
def run(self, batch=True, interruptible=None, inplace=True): """ Run task :param batch if False batching will be disabled. :param interruptible: If true interruptible instance will be used. :param inplace Apply action on the current object or return a new one. :re...
[ "def", "run", "(", "self", ",", "batch", "=", "True", ",", "interruptible", "=", "None", ",", "inplace", "=", "True", ")", ":", "params", "=", "{", "}", "if", "not", "batch", ":", "params", "[", "'batch'", "]", "=", "False", "if", "interruptible", ...
38.590909
15.863636
def pop(self, key, default=None): """ Remove the key and return the associated value or default if not found Args: key (str): The key to remove default (obj): The value to return if key is not present """ return self._dictionary.pop(key.lower(), d...
[ "def", "pop", "(", "self", ",", "key", ",", "default", "=", "None", ")", ":", "return", "self", ".", "_dictionary", ".", "pop", "(", "key", ".", "lower", "(", ")", ",", "default", ")" ]
40
14.25
def create_translation_field(model, field_name, lang, empty_value): """ Translation field factory. Returns a ``TranslationField`` based on a fieldname and a language. The list of supported fields can be extended by defining a tuple of field names in the projects settings.py like this:: MOD...
[ "def", "create_translation_field", "(", "model", ",", "field_name", ",", "lang", ",", "empty_value", ")", ":", "if", "empty_value", "not", "in", "(", "''", ",", "'both'", ",", "None", ",", "NONE", ")", ":", "raise", "ImproperlyConfigured", "(", "'%s is not a...
49.363636
24.818182
def _depth_event(self, msg): """Handle a depth event :param msg: :return: """ if 'e' in msg and msg['e'] == 'error': # close the socket self.close() # notify the user by returning a None value if self._callback: ...
[ "def", "_depth_event", "(", "self", ",", "msg", ")", ":", "if", "'e'", "in", "msg", "and", "msg", "[", "'e'", "]", "==", "'error'", ":", "# close the socket", "self", ".", "close", "(", ")", "# notify the user by returning a None value", "if", "self", ".", ...
26.190476
18.857143
def printConcordance(concordance, prefix): """Print the concordance. :param concordance: the concordance of each sample. :param prefix: the prefix of all the files. :type concordance: dict :type prefix: str :returns: the concordance percentage (dict) The concordance is the number of geno...
[ "def", "printConcordance", "(", "concordance", ",", "prefix", ")", ":", "outFile", "=", "None", "try", ":", "outFile", "=", "open", "(", "prefix", "+", "\".concordance\"", ",", "\"w\"", ")", "except", "IOError", ":", "msg", "=", "\"%s: can't write file\"", "...
34.204082
21.346939
def _make_blocks(records): # @NoSelf ''' Organizes the physical records into blocks in a list by placing consecutive physical records into a single block, so lesser VXRs will be created. [[start_rec1,end_rec1,data_1], [start_rec2,enc_rec2,data_2], ...] Parameters: ...
[ "def", "_make_blocks", "(", "records", ")", ":", "# @NoSelf", "sparse_blocks", "=", "[", "]", "total", "=", "len", "(", "records", ")", "if", "(", "total", "==", "0", ")", ":", "return", "[", "]", "x", "=", "0", "while", "(", "x", "<", "total", "...
29.218182
18.309091
def is_serving(self) -> bool: """ Tell whether the server is accepting new connections or shutting down. """ try: # Python ≥ 3.7 return self.server.is_serving() # type: ignore except AttributeError: # pragma: no cover # Python < 3.7 ...
[ "def", "is_serving", "(", "self", ")", "->", "bool", ":", "try", ":", "# Python ≥ 3.7", "return", "self", ".", "server", ".", "is_serving", "(", ")", "# type: ignore", "except", "AttributeError", ":", "# pragma: no cover", "# Python < 3.7", "return", "self", "."...
32
16.727273
def Operate(self, values): """Takes a list of values and if at least one matches, returns True.""" for val in values: try: if self.Operation(val, self.right_operand): return True except (TypeError, ValueError): pass return False
[ "def", "Operate", "(", "self", ",", "values", ")", ":", "for", "val", "in", "values", ":", "try", ":", "if", "self", ".", "Operation", "(", "val", ",", "self", ".", "right_operand", ")", ":", "return", "True", "except", "(", "TypeError", ",", "ValueE...
27
18.7
def get_assessment_offered_id(self): """Gets the ``Id`` of the ``AssessmentOffered``. return: (osid.id.Id) - the assessment offered ``Id`` *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.learning.Activity.get_objective_id ...
[ "def", "get_assessment_offered_id", "(", "self", ")", ":", "# Implemented from template for osid.learning.Activity.get_objective_id", "if", "not", "bool", "(", "self", ".", "_my_map", "[", "'assessmentOfferedId'", "]", ")", ":", "raise", "errors", ".", "IllegalState", "...
44.090909
20.545455
def config(self, commands, **kwargs): """Configures the node with the specified commands This method is used to send configuration commands to the node. It will take either a string or a list and prepend the necessary commands to put the session into config mode. Args: ...
[ "def", "config", "(", "self", ",", "commands", ",", "*", "*", "kwargs", ")", ":", "commands", "=", "make_iterable", "(", "commands", ")", "commands", "=", "list", "(", "commands", ")", "# push the configure command onto the command stack", "commands", ".", "inse...
39.194444
23.444444
def fit(self, sequences, y=None): """Fit Preprocessing to X. Parameters ---------- sequences : list of array-like, each of shape [sequence_length, n_features] A list of multivariate timeseries. Each sequence may have a different length, bu...
[ "def", "fit", "(", "self", ",", "sequences", ",", "y", "=", "None", ")", ":", "check_iter_of_sequences", "(", "sequences", ")", "for", "sequence", "in", "sequences", ":", "s", "=", "super", "(", "MultiSequencePreprocessingMixin", ",", "self", ")", "s", "."...
31.772727
20.090909
def start(name, call=None): ''' start a machine by name :param name: name given to the machine :param call: call value in this case is 'action' :return: true if successful CLI Example: .. code-block:: bash salt-cloud -a start vm_name ''' datacenter_id = get_datacenter_id(...
[ "def", "start", "(", "name", ",", "call", "=", "None", ")", ":", "datacenter_id", "=", "get_datacenter_id", "(", ")", "conn", "=", "get_conn", "(", ")", "node", "=", "get_node", "(", "conn", ",", "name", ")", "conn", ".", "start_server", "(", "datacent...
21.238095
23.142857
def remove_users(self, user_ids, nid=None): """Remove users from a network `nid` :type user_ids: list of str :param user_ids: a list of user ids. These are the same ids that are returned by get_all_users. :type nid: str :param nid: This is the ID of the network to ...
[ "def", "remove_users", "(", "self", ",", "user_ids", ",", "nid", "=", "None", ")", ":", "r", "=", "self", ".", "request", "(", "method", "=", "\"network.update\"", ",", "data", "=", "{", "\"remove_users\"", ":", "user_ids", "}", ",", "nid", "=", "nid",...
41
16.190476
def abspath(path): """Return the absolute path to a file and canonicalize it Path is returned without a trailing slash and without redundant slashes. Caches the user's home directory. :param path: A string for the path. This should not have any wildcards. :returns: Absolute path to the file :...
[ "def", "abspath", "(", "path", ")", ":", "global", "_USER_HOME_DIR", "# FIXME(brandyn): User's home directory must exist", "# FIXME(brandyn): Requires something to be in home dir", "if", "path", "[", "0", "]", "==", "'/'", ":", "return", "os", ".", "path", ".", "abspath...
36.086957
16.521739
def add_to_stmts_rules(stmts, rules): """Use by plugins to add extra rules to the existing rules for a statement.""" def is_rule_less_than(ra, rb): rka = ra[0] rkb = rb[0] if not util.is_prefixed(rkb): # old rule is non-prefixed; append new rule after return F...
[ "def", "add_to_stmts_rules", "(", "stmts", ",", "rules", ")", ":", "def", "is_rule_less_than", "(", "ra", ",", "rb", ")", ":", "rka", "=", "ra", "[", "0", "]", "rkb", "=", "rb", "[", "0", "]", "if", "not", "util", ".", "is_prefixed", "(", "rkb", ...
33.8
11.12
def simulate_list(nwords=16, nrec=10, ncats=4): """A function to simulate a list""" # load wordpool wp = pd.read_csv('data/cut_wordpool.csv') # get one list wp = wp[wp['GROUP']==np.random.choice(list(range(16)), 1)[0]].sample(16) wp['COLOR'] = [[int(np.random.rand() * 255) for i in range(3)] ...
[ "def", "simulate_list", "(", "nwords", "=", "16", ",", "nrec", "=", "10", ",", "ncats", "=", "4", ")", ":", "# load wordpool", "wp", "=", "pd", ".", "read_csv", "(", "'data/cut_wordpool.csv'", ")", "# get one list", "wp", "=", "wp", "[", "wp", "[", "'G...
33
25.7
def assure_snapshot(fnc): """ Converts a snapshot ID passed as the snapshot to a CloudBlockStorageSnapshot object. """ @wraps(fnc) def _wrapped(self, snapshot, *args, **kwargs): if not isinstance(snapshot, CloudBlockStorageSnapshot): # Must be the ID snapshot = se...
[ "def", "assure_snapshot", "(", "fnc", ")", ":", "@", "wraps", "(", "fnc", ")", "def", "_wrapped", "(", "self", ",", "snapshot", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "isinstance", "(", "snapshot", ",", "CloudBlockStorageSnap...
34.583333
17.083333
def get(self, typ, id, **kwargs): """ Load type by id """ return self._load(self._request(typ, id=id, params=kwargs))
[ "def", "get", "(", "self", ",", "typ", ",", "id", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_load", "(", "self", ".", "_request", "(", "typ", ",", "id", "=", "id", ",", "params", "=", "kwargs", ")", ")" ]
29
10.2
def select_renderer(self, request, renderers): """ Selects the appropriated parser which matches to the request's accept. :param request: The HTTP request. :param renderers: The lists of parsers. :return: The parser selected or none. """ if not len(request.accept_...
[ "def", "select_renderer", "(", "self", ",", "request", ",", "renderers", ")", ":", "if", "not", "len", "(", "request", ".", "accept_mimetypes", ")", ":", "return", "renderers", "[", "0", "]", ",", "renderers", "[", "0", "]", ".", "mimetype", "for", "mi...
41.529412
16.352941
def add_phase_interconnections(net, snow_partitioning_n, voxel_size=1, marching_cubes_area=False, alias=None): r""" This function connects networks of two or more phases together by interconnecting neighbouring nodes inside different phases. ...
[ "def", "add_phase_interconnections", "(", "net", ",", "snow_partitioning_n", ",", "voxel_size", "=", "1", ",", "marching_cubes_area", "=", "False", ",", "alias", "=", "None", ")", ":", "# -------------------------------------------------------------------------", "# Get ali...
48.266055
21.963303
def db_value(self, value): """Convert the python value for storage in the database.""" value = self.transform_value(value) return self.hhash.encrypt(value, salt_size=self.salt_size, rounds=self.rounds)
[ "def", "db_value", "(", "self", ",", "value", ")", ":", "value", "=", "self", ".", "transform_value", "(", "value", ")", "return", "self", ".", "hhash", ".", "encrypt", "(", "value", ",", "salt_size", "=", "self", ".", "salt_size", ",", "rounds", "=", ...
46.8
7
def train(self, ftrain): '''Trains the polynomial expansion. :param numpy.ndarray/function ftrain: output values corresponding to the quadrature points given by the getQuadraturePoints method to which the expansion should be trained. Or a function that should be evaluated ...
[ "def", "train", "(", "self", ",", "ftrain", ")", ":", "self", ".", "coeffs", "=", "0", "*", "self", ".", "coeffs", "upoints", ",", "wpoints", "=", "self", ".", "getQuadraturePointsAndWeights", "(", ")", "try", ":", "fpoints", "=", "[", "ftrain", "(", ...
32.820513
22.410256
def search_for_devices_by_serial_number(self, sn): """ Returns a list of device objects that match the serial number in param 'sn'. This will match partial serial numbers. """ import re sn_search = re.compile(sn) matches = [] for dev...
[ "def", "search_for_devices_by_serial_number", "(", "self", ",", "sn", ")", ":", "import", "re", "sn_search", "=", "re", ".", "compile", "(", "sn", ")", "matches", "=", "[", "]", "for", "dev_o", "in", "self", ".", "get_all_devices_in_portal", "(", ")", ":",...
32.608696
18.521739
def most_hot(self): """ Returns the *Weather* object in the forecast having the highest max temperature. The temperature is retrieved using the ``get_temperature['temp_max']`` call; was 'temp_max' key missing for every *Weather* instance in the forecast, ``None`` would be returne...
[ "def", "most_hot", "(", "self", ")", ":", "maxtemp", "=", "-", "270.0", "# No one would survive that...", "hottest", "=", "None", "for", "weather", "in", "self", ".", "_forecast", ".", "get_weathers", "(", ")", ":", "d", "=", "weather", ".", "get_temperature...
40.736842
17.368421
def _preprocess(self, filehandle, metadata): "Runs all attached preprocessors on the provided filehandle." for process in self._preprocessors: filehandle = process(filehandle, metadata) return filehandle
[ "def", "_preprocess", "(", "self", ",", "filehandle", ",", "metadata", ")", ":", "for", "process", "in", "self", ".", "_preprocessors", ":", "filehandle", "=", "process", "(", "filehandle", ",", "metadata", ")", "return", "filehandle" ]
47
13
def _notify(self, title, message, expected_action=None): """ Notify user from external event """ if self.editor is None: return inital_value = self.editor.save_on_focus_out self.editor.save_on_focus_out = False self._flg_notify = True dlg_type ...
[ "def", "_notify", "(", "self", ",", "title", ",", "message", ",", "expected_action", "=", "None", ")", ":", "if", "self", ".", "editor", "is", "None", ":", "return", "inital_value", "=", "self", ".", "editor", ".", "save_on_focus_out", "self", ".", "edit...
43.722222
14.277778
def next_game(self): ''' Advances the series to the next game, if possible. Also updates each team's score with points from the most recently completed game. :return: the next game, if the previous game did not end the series; None otherwise :raises SeriesOverEx...
[ "def", "next_game", "(", "self", ")", ":", "if", "self", ".", "is_over", "(", ")", ":", "raise", "dominoes", ".", "SeriesOverException", "(", "'Cannot start a new game - series ended with a score of {} to {}'", ".", "format", "(", "*", "self", ".", "scores", ")", ...
38.348837
24.162791
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rstp_rstp_migrate_time(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_stp_brief_info = ET.Element("get_stp_brief_info") config = get_stp_brief_info output = ET.SubElement(ge...
[ "def", "get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rstp_rstp_migrate_time", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "get_stp_brief_info", "=", "ET", ".", "Element", "(", "\"get_s...
49.6875
19.25
def bundle(self, bundle_name): """Bundle multiple Job or Playbook Apps into a single zip file. Args: bundle_name (str): The output name of the bundle zip file. """ if self.args.bundle or self.tcex_json.get('package', {}).get('bundle', False): if self.tcex_json.ge...
[ "def", "bundle", "(", "self", ",", "bundle_name", ")", ":", "if", "self", ".", "args", ".", "bundle", "or", "self", ".", "tcex_json", ".", "get", "(", "'package'", ",", "{", "}", ")", ".", "get", "(", "'bundle'", ",", "False", ")", ":", "if", "se...
46.083333
21.833333
def set_batch(self, data): """ Store multiple documents Args data <dict> data to store, use document ids as keys Returns revs <dict> dictionary of new revisions indexed by document ids """ # fetch existing documents to get current revisions rows = self.bucket.view("_all...
[ "def", "set_batch", "(", "self", ",", "data", ")", ":", "# fetch existing documents to get current revisions", "rows", "=", "self", ".", "bucket", ".", "view", "(", "\"_all_docs\"", ",", "keys", "=", "data", ".", "keys", "(", ")", ",", "include_docs", "=", "...
25.212121
24.181818
def regulartype(prompt_template="default"): """Echo each character typed. Unlike magictype, this echos the characters the user is pressing. Returns: command_string | The command to be passed to the shell to run. This is | typed by the user. """ echo_prompt(prompt_templ...
[ "def", "regulartype", "(", "prompt_template", "=", "\"default\"", ")", ":", "echo_prompt", "(", "prompt_template", ")", "command_string", "=", "\"\"", "cursor_position", "=", "0", "with", "raw_mode", "(", ")", ":", "while", "True", ":", "in_char", "=", "getcha...
37.842105
10.157895
def clear_lowest_numeric_score(self): """Clears the lowest score. raise: NoAccess - ``Metadata.isRequired()`` or ``Metadata.isReadOnly()`` is ``true`` *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.grading.G...
[ "def", "clear_lowest_numeric_score", "(", "self", ")", ":", "# Implemented from template for osid.grading.GradeSystemForm.clear_lowest_numeric_score", "if", "(", "self", ".", "get_lowest_numeric_score_metadata", "(", ")", ".", "is_read_only", "(", ")", "or", "self", ".", "g...
46.846154
23
def get_original_field_value(self, name): """ Returns original field value or None """ name = self.get_real_name(name) try: value = self.__original_data__[name] except KeyError: return None try: return value.export_original_da...
[ "def", "get_original_field_value", "(", "self", ",", "name", ")", ":", "name", "=", "self", ".", "get_real_name", "(", "name", ")", "try", ":", "value", "=", "self", ".", "__original_data__", "[", "name", "]", "except", "KeyError", ":", "return", "None", ...
24.4
14.4
def plot_roc_curve(y_true, y_probas, title='ROC Curves', curves=('micro', 'macro', 'each_class'), ax=None, figsize=None, cmap='nipy_spectral', title_fontsize="large", text_fontsize="medium"): """Generates the ROC curves from labels and predicted scores/probab...
[ "def", "plot_roc_curve", "(", "y_true", ",", "y_probas", ",", "title", "=", "'ROC Curves'", ",", "curves", "=", "(", "'micro'", ",", "'macro'", ",", "'each_class'", ")", ",", "ax", "=", "None", ",", "figsize", "=", "None", ",", "cmap", "=", "'nipy_spectr...
36.393103
22.593103
def is_valid_resource_name(rname, exception_type=None): """Validates the given resource name to ARM guidelines, individual services may be more restrictive. :param rname: The resource name being validated. :type rname: str :param exception_type: Raises this Exception if invalid. :type exception_typ...
[ "def", "is_valid_resource_name", "(", "rname", ",", "exception_type", "=", "None", ")", ":", "match", "=", "_ARMNAME_RE", ".", "match", "(", "rname", ")", "if", "match", ":", "return", "True", "if", "exception_type", ":", "raise", "exception_type", "(", ")",...
30.833333
18.888889
def _write_family(family, filename): """ Write a family to a csv file. :type family: :class:`eqcorrscan.core.match_filter.Family` :param family: Family to write to file :type filename: str :param filename: File to write to. """ with open(filename, 'w') as f: for detection in fam...
[ "def", "_write_family", "(", "family", ",", "filename", ")", ":", "with", "open", "(", "filename", ",", "'w'", ")", "as", "f", ":", "for", "detection", "in", "family", ".", "detections", ":", "det_str", "=", "''", "for", "key", "in", "detection", ".", ...
39.090909
15.363636
def load_from_file(module_path): """ Load a python module from its absolute filesystem path Borrowed from django-cms """ from imp import load_module, PY_SOURCE imported = None if module_path: with open(module_path, 'r') as openfile: imported = load_module('mod', openfil...
[ "def", "load_from_file", "(", "module_path", ")", ":", "from", "imp", "import", "load_module", ",", "PY_SOURCE", "imported", "=", "None", "if", "module_path", ":", "with", "open", "(", "module_path", ",", "'r'", ")", "as", "openfile", ":", "imported", "=", ...
28.692308
18.846154
def quick_scan(zap_helper, url, **options): """ Run a quick scan of a site by opening a URL, optionally spidering the URL, running an Active Scan, and reporting any issues found. This command contains most scan options as parameters, so you can do everything in one go. If any alerts are found ...
[ "def", "quick_scan", "(", "zap_helper", ",", "url", ",", "*", "*", "options", ")", ":", "if", "options", "[", "'self_contained'", "]", ":", "console", ".", "info", "(", "'Starting ZAP daemon'", ")", "with", "helpers", ".", "zap_error_handler", "(", ")", ":...
32.891304
21.804348
def _get_auth_packet(self, username, password, client): """ Get the pyrad authentication packet for the username/password and the given pyrad client. """ pkt = client.CreateAuthPacket(code=AccessRequest, User_Name=username) pkt["User-...
[ "def", "_get_auth_packet", "(", "self", ",", "username", ",", "password", ",", "client", ")", ":", "pkt", "=", "client", ".", "CreateAuthPacket", "(", "code", "=", "AccessRequest", ",", "User_Name", "=", "username", ")", "pkt", "[", "\"User-Password\"", "]",...
43.25
16.25
def string_in_list(tmp_str, strlist): # type: (AnyStr, List[AnyStr]) -> bool """Is tmp_str in strlist, case insensitive.""" new_str_list = strlist[:] for i, str_in_list in enumerate(new_str_list): new_str_list[i] = str_in_list.lower() return tmp_str.lower() in new_str...
[ "def", "string_in_list", "(", "tmp_str", ",", "strlist", ")", ":", "# type: (AnyStr, List[AnyStr]) -> bool", "new_str_list", "=", "strlist", "[", ":", "]", "for", "i", ",", "str_in_list", "in", "enumerate", "(", "new_str_list", ")", ":", "new_str_list", "[", "i"...
45.571429
6.428571
def sendp(x, inter=0, loop=0, iface=None, iface_hint=None, count=None, verbose=None, realtime=None, *args, **kargs): """Send packets at layer 2 sendp(packets, [inter=0], [loop=0], [verbose=conf.verb]) -> None""" if iface is None and iface_hint is not None: iface = conf.route.route(iface_hint)[0] __g...
[ "def", "sendp", "(", "x", ",", "inter", "=", "0", ",", "loop", "=", "0", ",", "iface", "=", "None", ",", "iface_hint", "=", "None", ",", "count", "=", "None", ",", "verbose", "=", "None", ",", "realtime", "=", "None", ",", "*", "args", ",", "*"...
73.666667
30.833333
def randrange(seq): """ Yields random values from @seq until @seq is empty """ seq = seq.copy() choose = rng().choice remove = seq.remove for x in range(len(seq)): y = choose(seq) remove(y) yield y
[ "def", "randrange", "(", "seq", ")", ":", "seq", "=", "seq", ".", "copy", "(", ")", "choose", "=", "rng", "(", ")", ".", "choice", "remove", "=", "seq", ".", "remove", "for", "x", "in", "range", "(", "len", "(", "seq", ")", ")", ":", "y", "="...
25.888889
16.555556
def bivconvolve (sx_a, sy_a, cxy_a, sx_b, sy_b, cxy_b): """Given two independent bivariate distributions, compute a bivariate distribution corresponding to their convolution. I'm sure this is worked out in a ton of places, but I got the equations from Pineau+ (2011A&A...527A.126P). Returns: (sx_c,...
[ "def", "bivconvolve", "(", "sx_a", ",", "sy_a", ",", "cxy_a", ",", "sx_b", ",", "sy_b", ",", "cxy_b", ")", ":", "_bivcheck", "(", "sx_a", ",", "sy_a", ",", "cxy_a", ")", "_bivcheck", "(", "sx_b", ",", "sy_b", ",", "cxy_b", ")", "sx_c", "=", "np", ...
31.052632
18.105263
def _kmedoids_run(X, n_clusters, distance, max_iter, tol, rng): """ Run a single trial of k-medoids clustering on dataset X, and given number of clusters """ membs = np.empty(shape=X.shape[0], dtype=int) centers = kmeans._kmeans_init(X, n_clusters, method='', rng=rng) sse_last = 9999.9 ...
[ "def", "_kmedoids_run", "(", "X", ",", "n_clusters", ",", "distance", ",", "max_iter", ",", "tol", ",", "rng", ")", ":", "membs", "=", "np", ".", "empty", "(", "shape", "=", "X", ".", "shape", "[", "0", "]", ",", "dtype", "=", "int", ")", "center...
35.842105
17.052632
def update_history(self, it, j=0, M=None, **kwargs): """Add the current state for all kwargs to the history """ # Create a new entry in the history for new variables (if they don't exist) if not np.any([k in self.history[j] for k in kwargs]): for k in kwargs: ...
[ "def", "update_history", "(", "self", ",", "it", ",", "j", "=", "0", ",", "M", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# Create a new entry in the history for new variables (if they don't exist)", "if", "not", "np", ".", "any", "(", "[", "k", "in", ...
47.461538
15.884615
def _process_for(self, node, **kwargs): """ Processes a for loop. e.g. {% for number in numbers %} {{ number }} {% endfor %} {% for key, value in somemap.items() %} {{ key }} -> {{ value }} {% %} """ # since...
[ "def", "_process_for", "(", "self", ",", "node", ",", "*", "*", "kwargs", ")", ":", "# since a for loop can introduce new names into the context", "# we need to remember the ones that existed outside the loop", "previous_stored_names", "=", "self", ".", "stored_names", ".", "...
34.47619
18.698413
def make_meta_dict_consistent(self): """ Remove the possibility of the main keys being undefined. """ if self.meta_dict is None: self.meta_dict = {} if "galaxy_info" not in self.meta_dict: self.meta_dict["galaxy_info"] = {} if "dependencies" not ...
[ "def", "make_meta_dict_consistent", "(", "self", ")", ":", "if", "self", ".", "meta_dict", "is", "None", ":", "self", ".", "meta_dict", "=", "{", "}", "if", "\"galaxy_info\"", "not", "in", "self", ".", "meta_dict", ":", "self", ".", "meta_dict", "[", "\"...
31.733333
14.133333
def two_param_shortcut(parser, token): """ Shortcut to transmogrify thumbnail """ bits = smart_split(token.contents) tagname = bits.next() try: imageurl = bits.next() param1 = bits.next() param2 = bits.next() param2 = param2.lstrip("#") except StopIteration: ...
[ "def", "two_param_shortcut", "(", "parser", ",", "token", ")", ":", "bits", "=", "smart_split", "(", "token", ".", "contents", ")", "tagname", "=", "bits", ".", "next", "(", ")", "try", ":", "imageurl", "=", "bits", ".", "next", "(", ")", "param1", "...
30.933333
14.933333
def predict_percentile(self, X, p=0.5): """ Returns the median lifetimes for the individuals, by default. If the survival curve of an individual does not cross 0.5, then the result is infinity. http://stats.stackexchange.com/questions/102986/percentile-loss-functions Parameters ...
[ "def", "predict_percentile", "(", "self", ",", "X", ",", "p", "=", "0.5", ")", ":", "subjects", "=", "_get_index", "(", "X", ")", "return", "qth_survival_times", "(", "p", ",", "self", ".", "predict_survival_function", "(", "X", ")", "[", "subjects", "]"...
34.423077
23.038462
def randomize(self, device=None, percent=100, silent=False): """ Writes random data to the beginning of each 4MB block on a block device this is useful when performance testing the backup process (Without any optional arguments will randomize the first 32k of each 4MB block on 1...
[ "def", "randomize", "(", "self", ",", "device", "=", "None", ",", "percent", "=", "100", ",", "silent", "=", "False", ")", ":", "volume", "=", "self", ".", "get_volume", "(", "device", ")", "# The number of blocks in the volume", "blocks", "=", "int", "(",...
42.617647
16.382353
def one_phase_dP_gravitational(angle, rho, L=1.0, g=g): r'''This function handles calculation of one-phase liquid-gas pressure drop due to gravitation for flow inside channels. This is either a differential calculation for a segment with an infinitesimal difference in elevation (if `L`=1 or a discrete ...
[ "def", "one_phase_dP_gravitational", "(", "angle", ",", "rho", ",", "L", "=", "1.0", ",", "g", "=", "g", ")", ":", "angle", "=", "radians", "(", "angle", ")", "return", "L", "*", "g", "*", "sin", "(", "angle", ")", "*", "rho" ]
28.243902
25.560976
def print_messages(domain, msg): """Debugging function to print all message language variants""" domain = Domain(domain) for lang in all_languages(): print(lang, ':', domain.get(lang, msg))
[ "def", "print_messages", "(", "domain", ",", "msg", ")", ":", "domain", "=", "Domain", "(", "domain", ")", "for", "lang", "in", "all_languages", "(", ")", ":", "print", "(", "lang", ",", "':'", ",", "domain", ".", "get", "(", "lang", ",", "msg", ")...
34.166667
12.666667
def _dump_queue_stats(self): ''' Dumps basic info about the queue lengths for the spider types ''' extras = {} keys = self.redis_conn.keys('*:*:queue') total_backlog = 0 for key in keys: elements = key.split(":") spider = elements[0] ...
[ "def", "_dump_queue_stats", "(", "self", ")", ":", "extras", "=", "{", "}", "keys", "=", "self", ".", "redis_conn", ".", "keys", "(", "'*:*:queue'", ")", "total_backlog", "=", "0", "for", "key", "in", "keys", ":", "elements", "=", "key", ".", "split", ...
33.533333
17.066667
def _create_storage_profile(self): """ Create the storage profile for the instance. Image reference can be a custom image name or a published urn. """ if self.image_publisher: storage_profile = { 'image_reference': { 'publisher': s...
[ "def", "_create_storage_profile", "(", "self", ")", ":", "if", "self", ".", "image_publisher", ":", "storage_profile", "=", "{", "'image_reference'", ":", "{", "'publisher'", ":", "self", ".", "image_publisher", ",", "'offer'", ":", "self", ".", "image_offer", ...
30.8125
15.375
def _create_models_for_relation_step(self, rel_model_name, rel_key, rel_value, model): """ Create a new model linked to the given model. Syntax: And `model` with `field` "`value`" has `new model` in the database: Example: .. code-block:: gherkin ...
[ "def", "_create_models_for_relation_step", "(", "self", ",", "rel_model_name", ",", "rel_key", ",", "rel_value", ",", "model", ")", ":", "model", "=", "get_model", "(", "model", ")", "lookup", "=", "{", "rel_key", ":", "rel_value", "}", "rel_model", "=", "ge...
25.606061
23.363636
def track_job(job_id): """ Tracking is done by requesting each job and then searching for whether the job has one of the following states: - "RUN", - "PEND", - "SSUSP", - "EXIT" based on the LSF documentation """ cmd = "bjobs -noheader -o stat {}".format(job_id) track_job_pro...
[ "def", "track_job", "(", "job_id", ")", ":", "cmd", "=", "\"bjobs -noheader -o stat {}\"", ".", "format", "(", "job_id", ")", "track_job_proc", "=", "subprocess", ".", "Popen", "(", "cmd", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "shell", "=", "...
30.066667
16.066667
def _configure(self, **kwargs): """Configure authentication endpoint. Optional kwargs may include: - cloud_environment (msrestazure.azure_cloud.Cloud): A targeted cloud environment - china (bool): Configure auth for China-based service, default is 'False'. ...
[ "def", "_configure", "(", "self", ",", "*", "*", "kwargs", ")", ":", "if", "kwargs", ".", "get", "(", "'china'", ")", ":", "err_msg", "=", "(", "\"china parameter is deprecated, \"", "\"please use \"", "\"cloud_environment=msrestazure.azure_cloud.AZURE_CHINA_CLOUD\"", ...
49.878049
22.463415
def get_corresponding_chains(self, from_pdb_id, from_chain_id, to_pdb_id): '''Should be called after get_mutations.''' chains = self.chain_map.get(from_pdb_id, {}).get(from_chain_id, {}).get(to_pdb_id, []) return sorted(chains)
[ "def", "get_corresponding_chains", "(", "self", ",", "from_pdb_id", ",", "from_chain_id", ",", "to_pdb_id", ")", ":", "chains", "=", "self", ".", "chain_map", ".", "get", "(", "from_pdb_id", ",", "{", "}", ")", ".", "get", "(", "from_chain_id", ",", "{", ...
62
27.5
def publish(self, tag, message): """ Publish a message down the socket """ payload = self.build_payload(tag, message) self.socket.send(payload)
[ "def", "publish", "(", "self", ",", "tag", ",", "message", ")", ":", "payload", "=", "self", ".", "build_payload", "(", "tag", ",", "message", ")", "self", ".", "socket", ".", "send", "(", "payload", ")" ]
41
6.25
def plot_mag(fignum, datablock, s, num, units, norm): """ plots magnetization against (de)magnetizing temperature or field Parameters _________________ fignum : matplotlib figure number for plotting datablock : nested list of [step, 0, 0, magnetization, 1,quality] s : string for title n...
[ "def", "plot_mag", "(", "fignum", ",", "datablock", ",", "s", ",", "num", ",", "units", ",", "norm", ")", ":", "global", "globals", ",", "graphmenu", "Ints", "=", "[", "]", "for", "plotrec", "in", "datablock", ":", "Ints", ".", "append", "(", "plotre...
32.067227
13.210084
def fetch_coords(self, query): """Pull down coordinate data from the endpoint.""" q = query.add_query_parameter(req='coord') return self._parse_messages(self.get_query(q).content)
[ "def", "fetch_coords", "(", "self", ",", "query", ")", ":", "q", "=", "query", ".", "add_query_parameter", "(", "req", "=", "'coord'", ")", "return", "self", ".", "_parse_messages", "(", "self", ".", "get_query", "(", "q", ")", ".", "content", ")" ]
50
10.5