text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def update( self, filepath, cache=False, remove=False, bumpversion=None, prerelease=None, dependencies=None, metadata=None, message=None): ''' Enter a new version to a DataArchive Paramet...
[ "def", "update", "(", "self", ",", "filepath", ",", "cache", "=", "False", ",", "remove", "=", "False", ",", "bumpversion", "=", "None", ",", "prerelease", "=", "None", ",", "dependencies", "=", "None", ",", "metadata", "=", "None", ",", "message", "="...
30.489583
0.000662
def update_css(self, css_in=None, clear_css=False): """Add additional CSS rules, optionally replacing all.""" if clear_css: self.matchers = {} # CSS is changing, so clear processing state self.clear_state() if css_in is None: return try: ...
[ "def", "update_css", "(", "self", ",", "css_in", "=", "None", ",", "clear_css", "=", "False", ")", ":", "if", "clear_css", ":", "self", ".", "matchers", "=", "{", "}", "# CSS is changing, so clear processing state", "self", ".", "clear_state", "(", ")", "if"...
44.758621
0.000377
def example_all(): """ Use a bunch of methods on a file. """ my_file = FileAsObj() my_file.filename = '/tmp/example_file.txt' my_file.add('# First change!') my_file.save() my_file = FileAsObj('/tmp/example_file.txt') my_file.unique = True my_file.sorted = True my_file.add('1'...
[ "def", "example_all", "(", ")", ":", "my_file", "=", "FileAsObj", "(", ")", "my_file", ".", "filename", "=", "'/tmp/example_file.txt'", "my_file", ".", "add", "(", "'# First change!'", ")", "my_file", ".", "save", "(", ")", "my_file", "=", "FileAsObj", "(", ...
27.5
0.001351
def getInitialSample(self, wmg): """ Generate an initial sample for the Markov chain. This function will return a list containing integer representations of each candidate in order of their rank in the current vote, from first to last. The list will be a complete strict ordering over t...
[ "def", "getInitialSample", "(", "self", ",", "wmg", ")", ":", "V", "=", "copy", ".", "deepcopy", "(", "wmg", ".", "keys", "(", ")", ")", "random", ".", "shuffle", "(", "V", ")", "return", "V" ]
53.375
0.012658
def show_tree(model=None): """Display the model tree window. Args: model: :class:`Model <modelx.core.model.Model>` object. Defaults to the current model. Warnings: For this function to work with Spyder, *Graphics backend* option of Spyder must be set to *inline*. ""...
[ "def", "show_tree", "(", "model", "=", "None", ")", ":", "if", "model", "is", "None", ":", "model", "=", "mx", ".", "cur_model", "(", ")", "view", "=", "get_modeltree", "(", "model", ")", "app", "=", "QApplication", ".", "instance", "(", ")", "if", ...
27.842105
0.001828
def GetHostNumCpuCores(self): '''Undocumented.''' counter = c_uint() ret = vmGuestLib.VMGuestLib_GetHostNumCpuCores(self.handle.value, byref(counter)) if ret != VMGUESTLIB_ERROR_SUCCESS: raise VMGuestLibException(ret) return counter.value
[ "def", "GetHostNumCpuCores", "(", "self", ")", ":", "counter", "=", "c_uint", "(", ")", "ret", "=", "vmGuestLib", ".", "VMGuestLib_GetHostNumCpuCores", "(", "self", ".", "handle", ".", "value", ",", "byref", "(", "counter", ")", ")", "if", "ret", "!=", "...
45.5
0.014388
def get_moments(model,x): ''' Moments (mean and sdev.) of a GP model at x ''' input_dim = model.X.shape[1] x = reshape(x,input_dim) fmin = min(model.predict(model.X)[0]) m, v = model.predict(x) s = np.sqrt(np.clip(v, 0, np.inf)) return (m,s, fmin)
[ "def", "get_moments", "(", "model", ",", "x", ")", ":", "input_dim", "=", "model", ".", "X", ".", "shape", "[", "1", "]", "x", "=", "reshape", "(", "x", ",", "input_dim", ")", "fmin", "=", "min", "(", "model", ".", "predict", "(", "model", ".", ...
24.909091
0.014085
def parse_attributes( fields ): """Parse list of key=value strings into a dict""" attributes = {} for field in fields: pair = field.split( '=' ) attributes[ pair[0] ] = pair[1] return attributes
[ "def", "parse_attributes", "(", "fields", ")", ":", "attributes", "=", "{", "}", "for", "field", "in", "fields", ":", "pair", "=", "field", ".", "split", "(", "'='", ")", "attributes", "[", "pair", "[", "0", "]", "]", "=", "pair", "[", "1", "]", ...
31.428571
0.030973
def bin_kb_dense(M, positions, length=10, contigs=None): """Perform binning with a fixed genomic length in kilobase pairs (kb). Fragments will be binned such that their total length is closest to the specified input. If a contig list is specified, binning will be performed such that fragments never ...
[ "def", "bin_kb_dense", "(", "M", ",", "positions", ",", "length", "=", "10", ",", "contigs", "=", "None", ")", ":", "unit", "=", "10", "**", "3", "ul", "=", "unit", "*", "length", "unit", "=", "positions", "/", "ul", "n", "=", "len", "(", "positi...
34.5
0.001282
def calculate_moment(psd_f, psd_amp, fmin, fmax, f0, funct, norm=None, vary_fmax=False, vary_density=None): """ Function for calculating one of the integrals used to construct a template bank placement metric. The integral calculated will be \int funct(x) * (psd_x)**(-7./3.) * delt...
[ "def", "calculate_moment", "(", "psd_f", ",", "psd_amp", ",", "fmin", ",", "fmax", ",", "f0", ",", "funct", ",", "norm", "=", "None", ",", "vary_fmax", "=", "False", ",", "vary_density", "=", "None", ")", ":", "# Must ensure deltaF in psd_f is constant", "ps...
42.361111
0.000961
def energy_density(self, strain, convert_GPa_to_eV=True): """ Calculates the elastic energy density due to a strain """ return sum([c.energy_density(strain, convert_GPa_to_eV) for c in self])
[ "def", "energy_density", "(", "self", ",", "strain", ",", "convert_GPa_to_eV", "=", "True", ")", ":", "return", "sum", "(", "[", "c", ".", "energy_density", "(", "strain", ",", "convert_GPa_to_eV", ")", "for", "c", "in", "self", "]", ")" ]
39.666667
0.00823
def get_domain_listing(self, domain, sort='hot', period=None, *args, **kwargs): """Return a get_content generator for submissions by domain. Corresponds to the submissions provided by ``https://www.reddit.com/domain/{domain}``. :param domain: The domain to ge...
[ "def", "get_domain_listing", "(", "self", ",", "domain", ",", "sort", "=", "'hot'", ",", "period", "=", "None", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# Verify arguments", "if", "sort", "not", "in", "(", "'controversial'", ",", "'hot'", ...
46.909091
0.001899
def encode_gen(line, encoding="utf-8"): """Encodes all Unicode strings in line to encoding Parameters ---------- line: Iterable of Unicode strings \tDate to be encoded encoding: String, defaults to "utf-8" \tTarget encoding """ for ele in line: if isinstance(ele, types.Uni...
[ "def", "encode_gen", "(", "line", ",", "encoding", "=", "\"utf-8\"", ")", ":", "for", "ele", "in", "line", ":", "if", "isinstance", "(", "ele", ",", "types", ".", "UnicodeType", ")", ":", "yield", "ele", ".", "encode", "(", "encoding", ")", "else", "...
22.882353
0.002469
def match_rows(rows1, rows2, key, sort_keys=True): """ Yield triples of `(value, left_rows, right_rows)` where `left_rows` and `right_rows` are lists of rows that share the same column value for *key*. This means that both *rows1* and *rows2* must have a column with the same name *key*. .. warn...
[ "def", "match_rows", "(", "rows1", ",", "rows2", ",", "key", ",", "sort_keys", "=", "True", ")", ":", "matched", "=", "OrderedDict", "(", ")", "for", "i", ",", "rows", "in", "enumerate", "(", "[", "rows1", ",", "rows2", "]", ")", ":", "for", "row",...
35.277778
0.000766
def wrap_sequence(sequence, books=None, tensor_shape=None): """Creates an input layer representing the given sequence of tensors. Args: sequence: A sequence of tensors. books: The bookkeeper. tensor_shape: An optional shape that will be set on the Tensor or verified to match the tensor. Returns...
[ "def", "wrap_sequence", "(", "sequence", ",", "books", "=", "None", ",", "tensor_shape", "=", "None", ")", ":", "if", "books", "is", "None", ":", "books", "=", "bookkeeper", ".", "for_default_graph", "(", ")", "my_sequence", "=", "[", "wrap", "(", "t", ...
34.3125
0.008865
def _create_toolbar_handler(self, get_match_fuzzy, get_enable_vi_bindings, get_show_completion_columns, get_show_help): """Create the toolbar handler. :type get_fuzzy_match: callable :param fuzzy_match: Gets the fuzzy matching config. :type get_enable_vi...
[ "def", "_create_toolbar_handler", "(", "self", ",", "get_match_fuzzy", ",", "get_enable_vi_bindings", ",", "get_show_completion_columns", ",", "get_show_help", ")", ":", "assert", "callable", "(", "get_match_fuzzy", ")", "assert", "callable", "(", "get_enable_vi_bindings"...
37.325
0.000979
def submatrix(dmat, indices_col, n_neighbors): """Return a submatrix given an orginal matrix and the indices to keep. Parameters ---------- mat: array, shape (n_samples, n_samples) Original matrix. indices_col: array, shape (n_samples, n_neighbors) Indices to keep. Each row consist...
[ "def", "submatrix", "(", "dmat", ",", "indices_col", ",", "n_neighbors", ")", ":", "n_samples_transform", ",", "n_samples_fit", "=", "dmat", ".", "shape", "submat", "=", "np", ".", "zeros", "(", "(", "n_samples_transform", ",", "n_neighbors", ")", ",", "dtyp...
31.64
0.001227
def broken_faces(mesh, color=None): """ Return the index of faces in the mesh which break the watertight status of the mesh. Parameters -------------- mesh: Trimesh object color: (4,) uint8, will set broken faces to this color None, will not alter mesh colors Returns ...
[ "def", "broken_faces", "(", "mesh", ",", "color", "=", "None", ")", ":", "adjacency", "=", "nx", ".", "from_edgelist", "(", "mesh", ".", "face_adjacency", ")", "broken", "=", "[", "k", "for", "k", ",", "v", "in", "dict", "(", "adjacency", ".", "degre...
30.807692
0.001211
def sleep(self): """Wait for the sleep time of the last response, to avoid being rate limited.""" if self.next_time and time.time() < self.next_time: time.sleep(self.next_time - time.time())
[ "def", "sleep", "(", "self", ")", ":", "if", "self", ".", "next_time", "and", "time", ".", "time", "(", ")", "<", "self", ".", "next_time", ":", "time", ".", "sleep", "(", "self", ".", "next_time", "-", "time", ".", "time", "(", ")", ")" ]
37
0.008811
def save_new_site(site_name, sitedir, srcdir, port, address, site_url, passwords): """ Add a site's configuration to the source dir and site dir """ cp = ConfigParser.SafeConfigParser() cp.read([srcdir + '/.datacats-environment']) section_name = 'site_' + site_name if not cp.has_se...
[ "def", "save_new_site", "(", "site_name", ",", "sitedir", ",", "srcdir", ",", "port", ",", "address", ",", "site_url", ",", "passwords", ")", ":", "cp", "=", "ConfigParser", ".", "SafeConfigParser", "(", ")", "cp", ".", "read", "(", "[", "srcdir", "+", ...
29.78125
0.002033
def batch_scan_layers(self, cells: np.ndarray = None, genes: np.ndarray = None, axis: int = 0, batch_size: int = 1000, layers: Iterable = None) -> Iterable[Tuple[int, np.ndarray, Dict]]: """ **DEPRECATED** - Use `scan` instead """ deprecated("'batch_scan_layers' is deprecated. Use 'scan' instead") if cells is...
[ "def", "batch_scan_layers", "(", "self", ",", "cells", ":", "np", ".", "ndarray", "=", "None", ",", "genes", ":", "np", ".", "ndarray", "=", "None", ",", "axis", ":", "int", "=", "0", ",", "batch_size", ":", "int", "=", "1000", ",", "layers", ":", ...
34.909091
0.027862
def _configure_logging(verbose=False, debug=False): """Configure the log global, message format, and verbosity settings.""" overall_level = logging.DEBUG if debug else logging.INFO logging.basicConfig( format=('{levelname[0]}{asctime}.{msecs:03.0f} {thread} ' '{filename}:{lineno}] {m...
[ "def", "_configure_logging", "(", "verbose", "=", "False", ",", "debug", "=", "False", ")", ":", "overall_level", "=", "logging", ".", "DEBUG", "if", "debug", "else", "logging", ".", "INFO", "logging", ".", "basicConfig", "(", "format", "=", "(", "'{leveln...
47.428571
0.001477
def upload_file_to_container(block_blob_client, container_name, file_path): """Uploads a local file to an Azure Blob storage container. :param block_blob_client: A blob service client. :type block_blob_client: `azure.storage.blob.BlockBlobService` :param str container_name: The name of the Azure Blob s...
[ "def", "upload_file_to_container", "(", "block_blob_client", ",", "container_name", ",", "file_path", ")", ":", "blob_name", "=", "os", ".", "path", ".", "basename", "(", "file_path", ")", "_log", ".", "info", "(", "'Uploading file {} to container [{}]...'", ".", ...
43.8
0.001489
def add (self, defn): """Adds the given Command Definition to this Command Dictionary.""" self[defn.name] = defn self.colnames[defn.name] = defn
[ "def", "add", "(", "self", ",", "defn", ")", ":", "self", "[", "defn", ".", "name", "]", "=", "defn", "self", ".", "colnames", "[", "defn", ".", "name", "]", "=", "defn" ]
43.5
0.022599
def overlap(a, b): """Check if two ranges overlap. Parameters ---------- a : range The first range. b : range The second range. Returns ------- overlaps : bool Do these ranges overlap. Notes ----- This function does not support ranges with step != ...
[ "def", "overlap", "(", "a", ",", "b", ")", ":", "_check_steps", "(", "a", ",", "b", ")", "return", "a", ".", "stop", ">=", "b", ".", "start", "and", "b", ".", "stop", ">=", "a", ".", "start" ]
18.285714
0.002475
def add_zone_condition(self, droppable_id, zone_id, match=True): """stub""" self.my_osid_object_form._my_map['zoneConditions'].append( {'droppableId': droppable_id, 'zoneId': zone_id, 'match': match}) self.my_osid_object_form._my_map['zoneConditions'].sort(key=lambda k: k['zoneId'])
[ "def", "add_zone_condition", "(", "self", ",", "droppable_id", ",", "zone_id", ",", "match", "=", "True", ")", ":", "self", ".", "my_osid_object_form", ".", "_my_map", "[", "'zoneConditions'", "]", ".", "append", "(", "{", "'droppableId'", ":", "droppable_id",...
63
0.009404
def call_multiple_modules(module_gen): """Call each module module_gen should be a iterator """ for args_seq in module_gen: module_name_or_path = args_seq[0] with replace_sys_args(args_seq): if re.match(VALID_PACKAGE_RE, module_name_or_path): runpy.run_module(...
[ "def", "call_multiple_modules", "(", "module_gen", ")", ":", "for", "args_seq", "in", "module_gen", ":", "module_name_or_path", "=", "args_seq", "[", "0", "]", "with", "replace_sys_args", "(", "args_seq", ")", ":", "if", "re", ".", "match", "(", "VALID_PACKAGE...
35.928571
0.001938
def getHighOrderSequenceChunk(it, switchover=1000, w=40, n=2048): """ Given an iteration index, returns a list of vectors to be appended to the input stream, as well as a string label identifying the sequence. This version generates a bunch of high order sequences. The first element always provides sufficient...
[ "def", "getHighOrderSequenceChunk", "(", "it", ",", "switchover", "=", "1000", ",", "w", "=", "40", ",", "n", "=", "2048", ")", ":", "if", "it", "%", "10", "==", "3", ":", "s", "=", "numpy", ".", "random", ".", "randint", "(", "5", ")", "if", "...
24.75
0.036929
def load_tag(corpus, path): """ Iterate over all speakers on load them. Collect all utterance-idx and create a subset of them. """ tag_idx = os.path.basename(path) data_path = os.path.join(path, 'by_book') tag_utt_ids = [] for gender_path in MailabsReader...
[ "def", "load_tag", "(", "corpus", ",", "path", ")", ":", "tag_idx", "=", "os", ".", "path", ".", "basename", "(", "path", ")", "data_path", "=", "os", ".", "path", ".", "join", "(", "path", ",", "'by_book'", ")", "tag_utt_ids", "=", "[", "]", "for"...
42.454545
0.001396
def parse_update(prs, conn): """Update a record. Arguments: prs: parser object of argparse conn: dictionary of connection information """ prs_update = prs.add_parser( 'update', help='update record of specific zone') set_option(prs_update, 'domain') set_option(prs_upda...
[ "def", "parse_update", "(", "prs", ",", "conn", ")", ":", "prs_update", "=", "prs", ".", "add_parser", "(", "'update'", ",", "help", "=", "'update record of specific zone'", ")", "set_option", "(", "prs_update", ",", "'domain'", ")", "set_option", "(", "prs_up...
26.333333
0.002445
def apply_mask(matrix, mask_pattern, matrix_size, is_encoding_region): """\ Applies the provided mask pattern on the `matrix`. ISO/IEC 18004:2015(E) -- 7.8.2 Data mask patterns (page 50) :param tuple matrix: A tuple of bytearrays :param mask_pattern: A mask pattern (a function) :param int matr...
[ "def", "apply_mask", "(", "matrix", ",", "mask_pattern", ",", "matrix_size", ",", "is_encoding_region", ")", ":", "for", "i", "in", "range", "(", "matrix_size", ")", ":", "for", "j", "in", "range", "(", "matrix_size", ")", ":", "if", "is_encoding_region", ...
40.5
0.001508
def stdout(self): """ The job stdout :return: string or None """ streams = self._payload.get('streams', None) return streams[0] if streams is not None and len(streams) >= 1 else ''
[ "def", "stdout", "(", "self", ")", ":", "streams", "=", "self", ".", "_payload", ".", "get", "(", "'streams'", ",", "None", ")", "return", "streams", "[", "0", "]", "if", "streams", "is", "not", "None", "and", "len", "(", "streams", ")", ">=", "1",...
31.714286
0.008772
def unparse_range(obj): """Unparse a range argument. Args: obj: An article range. There are a number of valid formats; an integer specifying a single article or a tuple specifying an article range. If the range doesn't give a start article then all articles up to the...
[ "def", "unparse_range", "(", "obj", ")", ":", "if", "isinstance", "(", "obj", ",", "(", "int", ",", "long", ")", ")", ":", "return", "str", "(", "obj", ")", "if", "isinstance", "(", "obj", ",", "tuple", ")", ":", "arg", "=", "str", "(", "obj", ...
31.566667
0.001025
def preprocess( self, nb: "NotebookNode", resources: dict ) -> Tuple["NotebookNode", dict]: """Preprocess the entire Notebook.""" for index, cell in enumerate(nb.cells): if "## Solution" in cell.source: nb.cells[index + 1].source = "" return nb, resources
[ "def", "preprocess", "(", "self", ",", "nb", ":", "\"NotebookNode\"", ",", "resources", ":", "dict", ")", "->", "Tuple", "[", "\"NotebookNode\"", ",", "dict", "]", ":", "for", "index", ",", "cell", "in", "enumerate", "(", "nb", ".", "cells", ")", ":", ...
34.666667
0.009375
def divrank(G, alpha=0.25, d=0.85, personalization=None, max_iter=100, tol=1.0e-6, nstart=None, weight='weight', dangling=None): ''' Returns the DivRank (Diverse Rank) of the nodes in the graph. This code is based on networkx.pagerank. Args: (diff from pagerank) alpha: con...
[ "def", "divrank", "(", "G", ",", "alpha", "=", "0.25", ",", "d", "=", "0.85", ",", "personalization", "=", "None", ",", "max_iter", "=", "100", ",", "tol", "=", "1.0e-6", ",", "nstart", "=", "None", ",", "weight", "=", "'weight'", ",", "dangling", ...
35.236559
0.00089
def update_variables(self) -> None: """Assign the current objects |ChangeItem.value| to the values of the target variables. We use the `LahnH` project in the following: >>> from hydpy.core.examples import prepare_full_example_2 >>> hp, pub, TestIO = prepare_full_example_2() ...
[ "def", "update_variables", "(", "self", ")", "->", "None", ":", "value", "=", "self", ".", "value", "for", "variable", "in", "self", ".", "device2target", ".", "values", "(", ")", ":", "self", ".", "update_variable", "(", "variable", ",", "value", ")" ]
37.318182
0.000791
def open_street_map_geoloc_link(data): """ Get a link to open street map pointing on this IP's geolocation. Args: data (str/tuple): IP address or (latitude, longitude). Returns: str: a link to open street map pointing on this IP's geolocation. """ if isinstance(data, str): ...
[ "def", "open_street_map_geoloc_link", "(", "data", ")", ":", "if", "isinstance", "(", "data", ",", "str", ")", ":", "lat_lon", "=", "ip_geoloc", "(", "data", ")", "if", "lat_lon", "is", "None", ":", "return", "''", "lat", ",", "lon", "=", "lat_lon", "e...
29.368421
0.001736
def outgoing(cls, hostport, process_name=None, serve_hostport=None, handler=None, tchannel=None): """Initiate a new connection to the given host. :param hostport: String in the form ``$host:$port`` specifying the target host :param process_name: Process ...
[ "def", "outgoing", "(", "cls", ",", "hostport", ",", "process_name", "=", "None", ",", "serve_hostport", "=", "None", ",", "handler", "=", "None", ",", "tchannel", "=", "None", ")", ":", "host", ",", "port", "=", "hostport", ".", "rsplit", "(", "\":\""...
39.26
0.001491
def encrypt(base_field, key=None, ttl=None): """ A decorator for creating encrypted model fields. :type base_field: models.Field[T] :param bytes key: This is an optional argument. Allows for specifying an instance specific encryption key. :param int ttl: This is an optional argument. ...
[ "def", "encrypt", "(", "base_field", ",", "key", "=", "None", ",", "ttl", "=", "None", ")", ":", "if", "not", "isinstance", "(", "base_field", ",", "models", ".", "Field", ")", ":", "assert", "key", "is", "None", "assert", "ttl", "is", "None", "retur...
38.304348
0.001107
def reactToAMQPMessage(message, send_back): """ React to given (AMQP) message. `message` is usually expected to be :py:func:`collections.namedtuple` structure filled with all necessary data. Args: message (\*Request class): only :class:`.ConversionRequest` class is ...
[ "def", "reactToAMQPMessage", "(", "message", ",", "send_back", ")", ":", "if", "_instanceof", "(", "message", ",", "ConversionRequest", ")", ":", "return", "convert", "(", "message", ".", "input_format", ",", "message", ".", "output_format", ",", "message", "....
35.870968
0.001751
async def remove(self, *, node_id: str, force: bool = False) -> Mapping[str, Any]: """ Remove a node from a swarm. Args: node_id: The ID or name of the node """ params = {"force": force} response = await self.docker._query_json( "nodes/{node_id}...
[ "async", "def", "remove", "(", "self", ",", "*", ",", "node_id", ":", "str", ",", "force", ":", "bool", "=", "False", ")", "->", "Mapping", "[", "str", ",", "Any", "]", ":", "params", "=", "{", "\"force\"", ":", "force", "}", "response", "=", "aw...
28.428571
0.009732
def write_task_metadata( self, declaration_datetime=None, flight_date=None, task_number=None, turnpoints=None, text=None): """ Write the task declaration metadata record:: writer.write_task_metadata( datetime.datetime(2014, 4, 13, 12, 53, 02), ...
[ "def", "write_task_metadata", "(", "self", ",", "declaration_datetime", "=", "None", ",", "flight_date", "=", "None", ",", "task_number", "=", "None", ",", "turnpoints", "=", "None", ",", "text", "=", "None", ")", ":", "if", "declaration_datetime", "is", "No...
37.492537
0.000776
def _create_rpmmacros(runas='root'): ''' Create the .rpmmacros file in user's home directory ''' home = os.path.expanduser('~') rpmbuilddir = os.path.join(home, 'rpmbuild') if not os.path.isdir(rpmbuilddir): __salt__['file.makedirs_perms'](name=rpmbuilddir, user=runas, group='mock') ...
[ "def", "_create_rpmmacros", "(", "runas", "=", "'root'", ")", ":", "home", "=", "os", ".", "path", ".", "expanduser", "(", "'~'", ")", "rpmbuilddir", "=", "os", ".", "path", ".", "join", "(", "home", ",", "'rpmbuild'", ")", "if", "not", "os", ".", ...
40.181818
0.00221
def input_list_parser(infile_list): """Always return a list of files with varying input. >>> input_list_parser(['/path/to/folder/']) ['/path/to/folder/file1.txt', '/path/to/folder/file2.txt', '/path/to/folder/file3.txt'] >>> input_list_parser(['/path/to/file.txt']) ['/path/to/file.txt'] >>> i...
[ "def", "input_list_parser", "(", "infile_list", ")", ":", "final_list_of_files", "=", "[", "]", "for", "x", "in", "infile_list", ":", "# If the input is a folder", "if", "op", ".", "isdir", "(", "x", ")", ":", "os", ".", "chdir", "(", "x", ")", "final_list...
22.911765
0.002463
def roll_sparse(x, shift, axis=0): '''Sparse matrix roll This operation is equivalent to ``numpy.roll``, but operates on sparse matrices. Parameters ---------- x : scipy.sparse.spmatrix or np.ndarray The sparse matrix input shift : int The number of positions to roll the speci...
[ "def", "roll_sparse", "(", "x", ",", "shift", ",", "axis", "=", "0", ")", ":", "if", "not", "scipy", ".", "sparse", ".", "isspmatrix", "(", "x", ")", ":", "return", "np", ".", "roll", "(", "x", ",", "shift", ",", "axis", "=", "axis", ")", "# sh...
25.477612
0.001692
def fit_condition_threshold_models(self, model_names, model_objs, input_columns, output_column="Matched", output_threshold=0.5, num_folds=5, threshold_score="ets"): """ Fit models to predict hail/no-hail and use cross-validation to determine the probaility threshol...
[ "def", "fit_condition_threshold_models", "(", "self", ",", "model_names", ",", "model_objs", ",", "input_columns", ",", "output_column", "=", "\"Matched\"", ",", "output_threshold", "=", "0.5", ",", "num_folds", "=", "5", ",", "threshold_score", "=", "\"ets\"", ")...
53.46
0.011019
def _MergeOptional(self, a, b): """Tries to merge two values which may be None. If both values are not None, they are required to be the same and the merge is trivial. If one of the values is None and the other is not None, the merge results in the one which is not None. If both are None, the merge ...
[ "def", "_MergeOptional", "(", "self", ",", "a", ",", "b", ")", ":", "if", "a", "and", "b", ":", "if", "a", "!=", "b", ":", "raise", "MergeError", "(", "\"values must be identical if both specified \"", "\"('%s' vs '%s')\"", "%", "(", "transitfeed", ".", "Enc...
32.416667
0.002497
async def send(self, request: ClientRequest, **kwargs: Any) -> AsyncClientResponse: # type: ignore """Send the request using this HTTP sender. """ requests_kwargs = self._configure_send(request, **kwargs) return await super(AsyncRequestsHTTPSender, self).send(request, **requests_kwargs)
[ "async", "def", "send", "(", "self", ",", "request", ":", "ClientRequest", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "AsyncClientResponse", ":", "# type: ignore", "requests_kwargs", "=", "self", ".", "_configure_send", "(", "request", ",", "*", "*", ...
63.2
0.0125
def multi( children: Union[List[_Yieldable], Dict[Any, _Yieldable]], quiet_exceptions: "Union[Type[Exception], Tuple[Type[Exception], ...]]" = (), ) -> "Union[Future[List], Future[Dict]]": """Runs multiple asynchronous operations in parallel. ``children`` may either be a list or a dict whose values are...
[ "def", "multi", "(", "children", ":", "Union", "[", "List", "[", "_Yieldable", "]", ",", "Dict", "[", "Any", ",", "_Yieldable", "]", "]", ",", "quiet_exceptions", ":", "\"Union[Type[Exception], Tuple[Type[Exception], ...]]\"", "=", "(", ")", ",", ")", "->", ...
41.367347
0.000964
def set_ipv4(self, ip): """ Sets the IP address (ifr_addr) of the device parameter 'ip' should be string representation of IP address This does the same as ifconfig. """ sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) bin_ip = socket.inet_aton(ip) ...
[ "def", "set_ipv4", "(", "self", ",", "ip", ")", ":", "sock", "=", "socket", ".", "socket", "(", "socket", ".", "AF_INET", ",", "socket", ".", "SOCK_STREAM", ")", "bin_ip", "=", "socket", ".", "inet_aton", "(", "ip", ")", "ifreq", "=", "struct", ".", ...
56.272727
0.011129
def dump_feature(self, feature_name, feature, force_extraction=True): """ Dumps a list of lists or ndarray of features into database (allows to copy features from a pre-existing .txt/.csv/.whatever file, for example) Parameters ---------- feature : list of lists or ndarr...
[ "def", "dump_feature", "(", "self", ",", "feature_name", ",", "feature", ",", "force_extraction", "=", "True", ")", ":", "dump_feature_base", "(", "self", ".", "dbpath", ",", "self", ".", "_set_object", ",", "self", ".", "points_amt", ",", "feature_name", ",...
39.647059
0.008696
def get_polygon_pattern_rules(declarations, dirs): """ Given a list of declarations, return a list of output.Rule objects. Optionally provide an output directory for local copies of image files. """ property_map = {'polygon-pattern-file': 'file', 'polygon-pattern-width': 'width', ...
[ "def", "get_polygon_pattern_rules", "(", "declarations", ",", "dirs", ")", ":", "property_map", "=", "{", "'polygon-pattern-file'", ":", "'file'", ",", "'polygon-pattern-width'", ":", "'width'", ",", "'polygon-pattern-height'", ":", "'height'", ",", "'polygon-pattern-ty...
49.533333
0.014521
def register_plugin(self): """Register plugin in Spyder's main window""" self.main.add_dockwidget(self) self.findinfiles.result_browser.sig_edit_goto.connect( self.main.editor.load) self.findinfiles.find_options.redirect_stdio...
[ "def", "register_plugin", "(", "self", ")", ":", "self", ".", "main", ".", "add_dockwidget", "(", "self", ")", "self", ".", "findinfiles", ".", "result_browser", ".", "sig_edit_goto", ".", "connect", "(", "self", ".", "main", ".", "editor", ".", "load", ...
58.125
0.00141
def initialize( plugins, exclude_files_regex=None, exclude_lines_regex=None, path='.', scan_all_files=False, ): """Scans the entire codebase for secrets, and returns a SecretsCollection object. :type plugins: tuple of detect_secrets.plugins.base.BasePlugin :param plugins: rules to i...
[ "def", "initialize", "(", "plugins", ",", "exclude_files_regex", "=", "None", ",", "exclude_lines_regex", "=", "None", ",", "path", "=", "'.'", ",", "scan_all_files", "=", "False", ",", ")", ":", "output", "=", "SecretsCollection", "(", "plugins", ",", "excl...
25.62
0.000752
def attribute_value(self, doc: Document, attribute_name: str): """ Access data using attribute name rather than the numeric indices Returns: the value for the attribute """ return doc.cdr_document.get(self.header_translation_table[attribute_name])
[ "def", "attribute_value", "(", "self", ",", "doc", ":", "Document", ",", "attribute_name", ":", "str", ")", ":", "return", "doc", ".", "cdr_document", ".", "get", "(", "self", ".", "header_translation_table", "[", "attribute_name", "]", ")" ]
35.25
0.010381
def _set_config(config): """Set gl configuration""" pyglet_config = pyglet.gl.Config() pyglet_config.red_size = config['red_size'] pyglet_config.green_size = config['green_size'] pyglet_config.blue_size = config['blue_size'] pyglet_config.alpha_size = config['alpha_size'] pyglet_config.acc...
[ "def", "_set_config", "(", "config", ")", ":", "pyglet_config", "=", "pyglet", ".", "gl", ".", "Config", "(", ")", "pyglet_config", ".", "red_size", "=", "config", "[", "'red_size'", "]", "pyglet_config", ".", "green_size", "=", "config", "[", "'green_size'"...
35.7
0.001364
def get_func_result_cachekey(func_, args_=tuple(), kwargs_={}): """ TODO: recursive partial definitions kwargs = {} args = ([],) """ import utool as ut # Rectify partials and whatnot true_args = args_ true_kwargs = kwargs_ true_func = func_ if isinstance(func_, partial): ...
[ "def", "get_func_result_cachekey", "(", "func_", ",", "args_", "=", "tuple", "(", ")", ",", "kwargs_", "=", "{", "}", ")", ":", "import", "utool", "as", "ut", "# Rectify partials and whatnot", "true_args", "=", "args_", "true_kwargs", "=", "kwargs_", "true_fun...
33.410256
0.002237
def load_protocols(filename, _integer_base=10): """"Parse /etc/protocols and return values as a dictionary.""" spaces = re.compile(b"[ \t]+|\n") dct = DADict(_name=filename) try: with open(filename, "rb") as fdesc: for line in fdesc: try: shrp = li...
[ "def", "load_protocols", "(", "filename", ",", "_integer_base", "=", "10", ")", ":", "spaces", "=", "re", ".", "compile", "(", "b\"[ \\t]+|\\n\"", ")", "dct", "=", "DADict", "(", "_name", "=", "filename", ")", "try", ":", "with", "open", "(", "filename",...
36.964286
0.000942
def render(self, title=''): """ Render the Bloch sphere and its data sets in on given figure and axes. """ if self._rendered: self.axes.clear() self._rendered = True # Figure instance for Bloch sphere plot if not self._ext_fig: self.fig =...
[ "def", "render", "(", "self", ",", "title", "=", "''", ")", ":", "if", "self", ".", "_rendered", ":", "self", ".", "axes", ".", "clear", "(", ")", "self", ".", "_rendered", "=", "True", "# Figure instance for Bloch sphere plot", "if", "not", "self", ".",...
30.583333
0.001761
def keyboard_field(value, args=None): """ Format keyboard /command field. """ qs = QueryDict(args) per_line = qs.get('per_line', 1) field = qs.get("field", "slug") command = qs.get("command") convert = lambda element: "/" + command + " " + str(getattr(element, field)) group = lambda...
[ "def", "keyboard_field", "(", "value", ",", "args", "=", "None", ")", ":", "qs", "=", "QueryDict", "(", "args", ")", "per_line", "=", "qs", ".", "get", "(", "'per_line'", ",", "1", ")", "field", "=", "qs", ".", "get", "(", "\"field\"", ",", "\"slug...
36.866667
0.012346
def configure_singlecolor_image(self, scale=False): """ configures the single color image according to the requested parameters :return: nothing, just updates self.image """ # determine which channel to use self.image = self.data[self.singlecolorvar.get()] # scal...
[ "def", "configure_singlecolor_image", "(", "self", ",", "scale", "=", "False", ")", ":", "# determine which channel to use", "self", ".", "image", "=", "self", ".", "data", "[", "self", ".", "singlecolorvar", ".", "get", "(", ")", "]", "# scale the image by requ...
41.578947
0.002475
def array2root(arr, filename, treename='tree', mode='update'): """Convert a numpy array into a ROOT TTree and save it in a ROOT TFile. Fields of basic types, strings, and fixed-size subarrays of basic types are supported. ``np.object`` and ``np.float16`` are currently not supported. Parameters ---...
[ "def", "array2root", "(", "arr", ",", "filename", ",", "treename", "=", "'tree'", ",", "mode", "=", "'update'", ")", ":", "_librootnumpy", ".", "array2root", "(", "arr", ",", "filename", ",", "treename", ",", "mode", ")" ]
34.508475
0.000478
def query(action=None, command=None, args=None, method='GET', location=None, data=None): ''' Make a web call to Joyent ''' user = config.get_cloud_config_value( 'user', get_configured_provider(), __opts__, search_global=False ) if not us...
[ "def", "query", "(", "action", "=", "None", ",", "command", "=", "None", ",", "args", "=", "None", ",", "method", "=", "'GET'", ",", "location", "=", "None", ",", "data", "=", "None", ")", ":", "user", "=", "config", ".", "get_cloud_config_value", "(...
29.896825
0.001799
def get_field_names(self, declared_fields, info): """ Returns the list of all field names that should be created when instantiating this serializer class. This is based on the default set of fields, but also takes into account the `Meta.fields` or `Meta.exclude` options if they h...
[ "def", "get_field_names", "(", "self", ",", "declared_fields", ",", "info", ")", ":", "fields", "=", "getattr", "(", "self", ".", "Meta", ",", "'fields'", ",", "None", ")", "exclude", "=", "getattr", "(", "self", ".", "Meta", ",", "'exclude'", ",", "No...
41.5
0.001148
def smart_reroot(treefile, outgroupfile, outfile, format=0): """ simple function to reroot Newick format tree using ete2 Tree reading format options see here: http://packages.python.org/ete2/tutorial/tutorial_trees.html#reading-newick-trees """ tree = Tree(treefile, format=format) leaves = ...
[ "def", "smart_reroot", "(", "treefile", ",", "outgroupfile", ",", "outfile", ",", "format", "=", "0", ")", ":", "tree", "=", "Tree", "(", "treefile", ",", "format", "=", "format", ")", "leaves", "=", "[", "t", ".", "name", "for", "t", "in", "tree", ...
32.125
0.001889
def items(self): """ Returns a :class:`GramGenerator` that produces key,value tuples. """ return GramGenerator(self.path, self.elem, ignore_hash=self.ignore_hash)
[ "def", "items", "(", "self", ")", ":", "return", "GramGenerator", "(", "self", ".", "path", ",", "self", ".", "elem", ",", "ignore_hash", "=", "self", ".", "ignore_hash", ")" ]
36.333333
0.008969
def vgpmap_magic(dir_path=".", results_file="sites.txt", crd="", sym='ro', size=8, rsym="g^", rsize=8, fmt="pdf", res="c", proj="ortho", flip=False, anti=False, fancy=False, ell=False, ages=False, lat_0=0, lon_0=0, save_plots=True, int...
[ "def", "vgpmap_magic", "(", "dir_path", "=", "\".\"", ",", "results_file", "=", "\"sites.txt\"", ",", "crd", "=", "\"\"", ",", "sym", "=", "'ro'", ",", "size", "=", "8", ",", "rsym", "=", "\"g^\"", ",", "rsize", "=", "8", ",", "fmt", "=", "\"pdf\"", ...
37.022026
0.000811
def _is_suffix(self, t): """Return true if t is a suffix.""" return t not in NOT_SUFFIX and (t.replace('.', '') in SUFFIXES or t.replace('.', '') in SUFFIXES_LOWER)
[ "def", "_is_suffix", "(", "self", ",", "t", ")", ":", "return", "t", "not", "in", "NOT_SUFFIX", "and", "(", "t", ".", "replace", "(", "'.'", ",", "''", ")", "in", "SUFFIXES", "or", "t", ".", "replace", "(", "'.'", ",", "''", ")", "in", "SUFFIXES_...
59.333333
0.016667
def removeRef(self, attr): """Remove the given attribute from the Ref table maintained internally. """ if attr is None: attr__o = None else: attr__o = attr._o ret = libxml2mod.xmlRemoveRef(self._o, attr__o) return ret
[ "def", "removeRef", "(", "self", ",", "attr", ")", ":", "if", "attr", "is", "None", ":", "attr__o", "=", "None", "else", ":", "attr__o", "=", "attr", ".", "_o", "ret", "=", "libxml2mod", ".", "xmlRemoveRef", "(", "self", ".", "_o", ",", "attr__o", ...
37.428571
0.014925
def generate(args=None, namespace=None, file=None): """ Genereate DDL from data sources named. :args: String or list of strings to be parsed for arguments :namespace: Namespace to extract arguments from :file: Write to this open file object (default stdout) """ if hasattr(args, 's...
[ "def", "generate", "(", "args", "=", "None", ",", "namespace", "=", "None", ",", "file", "=", "None", ")", ":", "if", "hasattr", "(", "args", ",", "'split'", ")", ":", "args", "=", "args", ".", "split", "(", ")", "args", "=", "parser", ".", "pars...
43.439024
0.001647
def add_history(self, filename, color_scheme, font, wrap): """ Add new history tab. Args: filename (str): file to be loaded in a new tab. """ filename = encoding.to_unicode_from_fs(filename) if filename in self.filenames: return editor = c...
[ "def", "add_history", "(", "self", ",", "filename", ",", "color_scheme", ",", "font", ",", "wrap", ")", ":", "filename", "=", "encoding", ".", "to_unicode_from_fs", "(", "filename", ")", "if", "filename", "in", "self", ".", "filenames", ":", "return", "edi...
35.085714
0.001585
def get_parts_by_class(self, cls): """ Return all parts of this package that are instances of cls (where cls is passed directly to isinstance, so can be a class or sequence of classes). """ return (part for part in self.parts.values() if isinstance(part, cls))
[ "def", "get_parts_by_class", "(", "self", ",", "cls", ")", ":", "return", "(", "part", "for", "part", "in", "self", ".", "parts", ".", "values", "(", ")", "if", "isinstance", "(", "part", ",", "cls", ")", ")" ]
38
0.029412
def get_content(self, offset, size): """Return the specified number of bytes from the current section.""" return _bfd.section_get_content(self.bfd, self._ptr, offset, size)
[ "def", "get_content", "(", "self", ",", "offset", ",", "size", ")", ":", "return", "_bfd", ".", "section_get_content", "(", "self", ".", "bfd", ",", "self", ".", "_ptr", ",", "offset", ",", "size", ")" ]
62
0.010638
def corr(x, y, tail='two-sided', method='pearson'): """(Robust) correlation between two variables. Parameters ---------- x, y : array_like First and second set of observations. x and y must be independent. tail : string Specify whether to return 'one-sided' or 'two-sided' p-value. ...
[ "def", "corr", "(", "x", ",", "y", ",", "tail", "=", "'two-sided'", ",", "method", "=", "'pearson'", ")", ":", "x", "=", "np", ".", "asarray", "(", "x", ")", "y", "=", "np", ".", "asarray", "(", "y", ")", "# Check size", "if", "x", ".", "size",...
36.004608
0.000125
def stop(self): """Stop pipeline.""" urllib.request.urlcleanup() self._player.set_state(Gst.State.NULL) self.state = STATE_IDLE self._tags = {}
[ "def", "stop", "(", "self", ")", ":", "urllib", ".", "request", ".", "urlcleanup", "(", ")", "self", ".", "_player", ".", "set_state", "(", "Gst", ".", "State", ".", "NULL", ")", "self", ".", "state", "=", "STATE_IDLE", "self", ".", "_tags", "=", "...
29.666667
0.010929
def _update_gecos(name, key, value): ''' Common code to change a user's GECOS information ''' if not isinstance(value, six.string_types): value = six.text_type(value) pre_info = _get_gecos(name) if not pre_info: return False if value == pre_info[key]: return True ...
[ "def", "_update_gecos", "(", "name", ",", "key", ",", "value", ")", ":", "if", "not", "isinstance", "(", "value", ",", "six", ".", "string_types", ")", ":", "value", "=", "six", ".", "text_type", "(", "value", ")", "pre_info", "=", "_get_gecos", "(", ...
32.352941
0.001767
def disengage(self): ''' Home the magnet ''' if self._driver and self._driver.is_connected(): self._driver.home() self._engaged = False
[ "def", "disengage", "(", "self", ")", ":", "if", "self", ".", "_driver", "and", "self", ".", "_driver", ".", "is_connected", "(", ")", ":", "self", ".", "_driver", ".", "home", "(", ")", "self", ".", "_engaged", "=", "False" ]
26.428571
0.010471
def __update(self): """Load the IRQ file and update the internal dict.""" self.reset() if not os.path.exists(self.IRQ_FILE): # Correct issue #947: IRQ file do not exist on OpenVZ container return self.stats try: with open(self.IRQ_FILE) as irq_proc: ...
[ "def", "__update", "(", "self", ")", ":", "self", ".", "reset", "(", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "self", ".", "IRQ_FILE", ")", ":", "# Correct issue #947: IRQ file do not exist on OpenVZ container", "return", "self", ".", "stats", ...
39.666667
0.001491
def remote_file_exists(self): """Verify whether the file (scene) exists on AWS Storage.""" url = join(self.base_url, 'index.html') return super(AWSDownloader, self).remote_file_exists(url)
[ "def", "remote_file_exists", "(", "self", ")", ":", "url", "=", "join", "(", "self", ".", "base_url", ",", "'index.html'", ")", "return", "super", "(", "AWSDownloader", ",", "self", ")", ".", "remote_file_exists", "(", "url", ")" ]
52.25
0.009434
def Create(self,name,description=None): """Creates a new group >>> clc.v2.Datacenter(location="WA1").RootGroup().Create("Test3","Description3") <clc.APIv2.group.Group object at 0x10cc76c90> >>> print _ Test5 """ if not description: description = name r = clc.v2.API.Call( 'POST', 'groups/%s' %...
[ "def", "Create", "(", "self", ",", "name", ",", "description", "=", "None", ")", ":", "if", "not", "description", ":", "description", "=", "name", "r", "=", "clc", ".", "v2", ".", "API", ".", "Call", "(", "'POST'", ",", "'groups/%s'", "%", "(", "se...
27.388889
0.043137
def detach_attrs_factory(f): """Returns detach_attrs(key, value, fmt, meta) action that detaches attributes attached to elements of type f (e.g. pandocfilters.Math, etc). Attributes provided natively by pandoc will be left as is.""" # Get the name and standard length name = f.__closure__[0].cell_co...
[ "def", "detach_attrs_factory", "(", "f", ")", ":", "# Get the name and standard length", "name", "=", "f", ".", "__closure__", "[", "0", "]", ".", "cell_contents", "n", "=", "f", ".", "__closure__", "[", "1", "]", ".", "cell_contents", "def", "detach_attrs", ...
40.409091
0.001099
def create_tool(self, task): """ Creates a new GPTool for the toolbox. """ gp_tool = dict(taskName=task.name, taskDisplayName=task.display_name, taskDescription=task.description, canRunInBackground=True, ...
[ "def", "create_tool", "(", "self", ",", "task", ")", ":", "gp_tool", "=", "dict", "(", "taskName", "=", "task", ".", "name", ",", "taskDisplayName", "=", "task", ".", "display_name", ",", "taskDescription", "=", "task", ".", "description", ",", "canRunInBa...
52.272727
0.00854
def stop(self): """Stop the daemon.""" if self.pidfile is None: raise DaemonError('Cannot stop daemon without PID file') pid = self._read_pidfile() if pid is None: # I don't think this should be a fatal error self._emit_warning('{prog} is not running'...
[ "def", "stop", "(", "self", ")", ":", "if", "self", ".", "pidfile", "is", "None", ":", "raise", "DaemonError", "(", "'Cannot stop daemon without PID file'", ")", "pid", "=", "self", ".", "_read_pidfile", "(", ")", "if", "pid", "is", "None", ":", "# I don't...
33.689655
0.00199
def _copy_data(instream, outstream): """Copy data from one stream to another. :type instream: :class:`io.BytesIO` or :class:`io.StringIO` or file :param instream: A byte stream or open file to read from. :param file outstream: The file descriptor of a tmpfile to write to. """ sent = 0 whil...
[ "def", "_copy_data", "(", "instream", ",", "outstream", ")", ":", "sent", "=", "0", "while", "True", ":", "if", "(", "(", "_py3k", "and", "isinstance", "(", "instream", ",", "str", ")", ")", "or", "(", "not", "_py3k", "and", "isinstance", "(", "instr...
41.360465
0.001922
def parse_month_year(date_string): """ >>> parse_month_year('01/10/2012') (10, 2012) """ match = re.match('\d{2}/(?P<month>\d{2})/(?P<year>\d{4})$', date_string.lower()) if not match: raise ValueError("Not format 'dd/mm/yyyy': '{}'".format(date_string)) month = i...
[ "def", "parse_month_year", "(", "date_string", ")", ":", "match", "=", "re", ".", "match", "(", "'\\d{2}/(?P<month>\\d{2})/(?P<year>\\d{4})$'", ",", "date_string", ".", "lower", "(", ")", ")", "if", "not", "match", ":", "raise", "ValueError", "(", "\"Not format ...
32.666667
0.009926
def option_group_exists(name, tags=None, region=None, key=None, keyid=None, profile=None): ''' Check to see if an RDS option group exists. CLI example:: salt myminion boto_rds.option_group_exists myoptiongr region=us-east-1 ''' conn = _get_conn(region=region, key=ke...
[ "def", "option_group_exists", "(", "name", ",", "tags", "=", "None", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "conn", "=", "_get_conn", "(", "region", "=", "region", ",", ...
33.4375
0.001818
def retry(func): """ Decorator to handle API retries and exceptions. Defaults to three retries. Args: func (function): function for decoration Returns: decorated function """ def retried_func(*args, **kwargs): max_tries = 3 tries = 0 while True: ...
[ "def", "retry", "(", "func", ")", ":", "def", "retried_func", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "max_tries", "=", "3", "tries", "=", "0", "while", "True", ":", "try", ":", "resp", "=", "func", "(", "*", "args", ",", "*", "*",...
29.866667
0.001441
def ensure_keyword_args(kwargs, mandatory=(), optional=()): """Checks whether dictionary of keyword arguments satisfies conditions. :param kwargs: Dictionary of keyword arguments, received via ``*kwargs`` :param mandatory: Iterable of mandatory argument names :param optional: Iterable of optional argum...
[ "def", "ensure_keyword_args", "(", "kwargs", ",", "mandatory", "=", "(", ")", ",", "optional", "=", "(", ")", ")", ":", "from", "taipan", ".", "strings", "import", "ensure_string", "ensure_mapping", "(", "kwargs", ")", "mandatory", "=", "list", "(", "map",...
35.641026
0.0007
def bytes_to_str(byteVal, decimals=1): """ Convert bytes to a human readable string. :param byteVal: Value to convert in bytes :type byteVal: int or float :param decimal: Number of decimal to display :type decimal: int :returns: Number of byte with the best unit of measure :rtype: str...
[ "def", "bytes_to_str", "(", "byteVal", ",", "decimals", "=", "1", ")", ":", "for", "unit", ",", "byte", "in", "BYTES", ":", "if", "(", "byteVal", ">=", "byte", ")", ":", "if", "decimals", "==", "0", ":", "return", "'%s %s'", "%", "(", "int", "(", ...
29.842105
0.001709
def emit(_): """Serialize metrics to the memory mapped buffer.""" if not initialized: raise NotInitialized view = { 'version': __version__, 'counters': {}, 'gauges': {}, 'histograms': {}, 'meters': {}, 'timers': {}, } for (ty, module, name), ...
[ "def", "emit", "(", "_", ")", ":", "if", "not", "initialized", ":", "raise", "NotInitialized", "view", "=", "{", "'version'", ":", "__version__", ",", "'counters'", ":", "{", "}", ",", "'gauges'", ":", "{", "}", ",", "'histograms'", ":", "{", "}", ",...
31.090909
0.000945
def freeze(name, **kwargs): ''' Freeze the named container path path to the container parent directory default: /var/lib/lxc (system) .. versionadded:: 2015.8.0 start : False If ``True`` and the container is stopped, the container will be started before attempt...
[ "def", "freeze", "(", "name", ",", "*", "*", "kwargs", ")", ":", "use_vt", "=", "kwargs", ".", "get", "(", "'use_vt'", ",", "None", ")", "path", "=", "kwargs", ".", "get", "(", "'path'", ",", "None", ")", "_ensure_exists", "(", "name", ",", "path",...
26
0.000789
def create_mssql_pyodbc(self, **kwargs): """ :rtype: Engine """ return self._ce( self._ccs(self.DialectAndDriver.mssql_pyodbc), **kwargs )
[ "def", "create_mssql_pyodbc", "(", "self", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_ce", "(", "self", ".", "_ccs", "(", "self", ".", "DialectAndDriver", ".", "mssql_pyodbc", ")", ",", "*", "*", "kwargs", ")" ]
26.285714
0.010526
def _convertToElementList(elements_list): """ Take a list of element node indexes deliminated by -1 and convert it into a list element node indexes list. """ elements = [] current_element = [] for node_index in elements_list: if node_index == -1: elements.append(current_e...
[ "def", "_convertToElementList", "(", "elements_list", ")", ":", "elements", "=", "[", "]", "current_element", "=", "[", "]", "for", "node_index", "in", "elements_list", ":", "if", "node_index", "==", "-", "1", ":", "elements", ".", "append", "(", "current_el...
28.533333
0.002262
def shot_duration_data(shot, role): """Return the data for duration :param shot: the shot that holds the data :type shot: :class:`jukeboxcore.djadapter.models.Shot` :param role: item data role :type role: QtCore.Qt.ItemDataRole :returns: data for the duration :rtype: depending on role :...
[ "def", "shot_duration_data", "(", "shot", ",", "role", ")", ":", "if", "role", "==", "QtCore", ".", "Qt", ".", "DisplayRole", ":", "return", "str", "(", "shot", ".", "duration", ")" ]
30.769231
0.002427
def _get(self, uri): """ Handles the communication with the API when getting a specific resource managed by this class. """ resp, resp_body = self.api.method_get(uri) return self.resource_class(self, resp_body, self.response_key, loaded=True)
[ "def", "_get", "(", "self", ",", "uri", ")", ":", "resp", ",", "resp_body", "=", "self", ".", "api", ".", "method_get", "(", "uri", ")", "return", "self", ".", "resource_class", "(", "self", ",", "resp_body", ",", "self", ".", "response_key", ",", "l...
37.375
0.009804
def omit(indices, from_, strict=False): """Returns a subsequence from given tuple, omitting specified indices. :param indices: Iterable of indices to exclude :param strict: Whether ``indices`` are required to exist in the tuple :return: Tuple without elements of specified indices :raise IndexErro...
[ "def", "omit", "(", "indices", ",", "from_", ",", "strict", "=", "False", ")", ":", "from", "taipan", ".", "collections", ".", "sets", "import", "remove_subset", "ensure_iterable", "(", "indices", ")", "ensure_sequence", "(", "from_", ")", "if", "strict", ...
31.607143
0.001096
def _catch_errors(a_func, to_catch): """Updates a_func to wrap exceptions with GaxError Args: a_func (callable): A callable. to_catch (list[Exception]): Configures the exceptions to wrap. Returns: Callable: A function that will wrap certain exceptions with GaxError """ def ...
[ "def", "_catch_errors", "(", "a_func", ",", "to_catch", ")", ":", "def", "inner", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "\"\"\"Wraps specified exceptions\"\"\"", "try", ":", "return", "a_func", "(", "*", "args", ",", "*", "*", "kwargs", ")...
32.25
0.001506
def _merge_layout_objs(obj, subobj): """ Merge layout objects recursively Note: This function mutates the input obj dict, but it does not mutate the subobj dict Parameters ---------- obj: dict dict into which the sub-figure dict will be merged subobj: dict dict that sil...
[ "def", "_merge_layout_objs", "(", "obj", ",", "subobj", ")", ":", "for", "prop", ",", "val", "in", "subobj", ".", "items", "(", ")", ":", "if", "isinstance", "(", "val", ",", "dict", ")", "and", "prop", "in", "obj", ":", "# recursion", "_merge_layout_o...
28.148148
0.001272
def process_request(self, req, resp): """ Do response processing """ # req.stream corresponds to the WSGI wsgi.input environ variable, # and allows you to read bytes from the request body. # # See also: PEP 3333 if req.content_length in (None, 0): ...
[ "def", "process_request", "(", "self", ",", "req", ",", "resp", ")", ":", "# req.stream corresponds to the WSGI wsgi.input environ variable,", "# and allows you to read bytes from the request body.", "#", "# See also: PEP 3333", "if", "req", ".", "content_length", "in", "(", ...
37.970588
0.002266
def quit(self, event): """Quit the game.""" self.logger.info("Quitting.") self.on_exit() sys.exit()
[ "def", "quit", "(", "self", ",", "event", ")", ":", "self", ".", "logger", ".", "info", "(", "\"Quitting.\"", ")", "self", ".", "on_exit", "(", ")", "sys", ".", "exit", "(", ")" ]
25.4
0.015267