text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def copy(src, dst): """ Handle the copying of a file or directory. The destination basedir _must_ exist. :param src: A string containing the path of the source to copy. If the source ends with a '/', will become a recursive directory copy of source. :param dst: A string containing the path t...
[ "def", "copy", "(", "src", ",", "dst", ")", ":", "try", ":", "shutil", ".", "copytree", "(", "src", ",", "dst", ")", "except", "OSError", "as", "exc", ":", "if", "exc", ".", "errno", "==", "errno", ".", "ENOTDIR", ":", "shutil", ".", "copy", "(",...
31.578947
0.001618
def weld_count(array): """Returns the length of the array. Parameters ---------- array : numpy.ndarray or WeldObject Input array. Returns ------- WeldObject Representation of this computation. """ obj_id, weld_obj = create_weld_object(array) weld_template = _w...
[ "def", "weld_count", "(", "array", ")", ":", "obj_id", ",", "weld_obj", "=", "create_weld_object", "(", "array", ")", "weld_template", "=", "_weld_count_code", "weld_obj", ".", "weld_code", "=", "weld_template", ".", "format", "(", "array", "=", "obj_id", ")",...
18.857143
0.002404
def transform_to_matrices(transform): """ Convert an SVG transform string to an array of matrices. > transform = "rotate(-10 50 100) translate(-36 45.5) skewX(40) scale(1 0.5)" Parameters ----------- transform : str Contains trans...
[ "def", "transform_to_matrices", "(", "transform", ")", ":", "# split the transform string in to components of:", "# (operation, args) i.e. (translate, '-1.0, 2.0')", "components", "=", "[", "[", "j", ".", "strip", "(", ")", "for", "j", "in", "i", ".", "strip", "(", ")...
33.044776
0.000439
def _translate(unistr, table): '''Replace characters using a table.''' if type(unistr) is str: try: unistr = unistr.decode('utf-8') # Python 3 returns AttributeError when .decode() is called on a str # This means it is already unicode. except AttributeError: ...
[ "def", "_translate", "(", "unistr", ",", "table", ")", ":", "if", "type", "(", "unistr", ")", "is", "str", ":", "try", ":", "unistr", "=", "unistr", ".", "decode", "(", "'utf-8'", ")", "# Python 3 returns AttributeError when .decode() is called on a str", "# Thi...
30.285714
0.001524
def spinn5_chip_coord(x, y, root_x=0, root_y=0): """Get the coordinates of a chip on its board. Given the coordinates of a chip in a multi-board system, calculates the coordinates of the chip within its board. .. note:: This function assumes the system is constructed from SpiNN-5 boards P...
[ "def", "spinn5_chip_coord", "(", "x", ",", "y", ",", "root_x", "=", "0", ",", "root_y", "=", "0", ")", ":", "dx", ",", "dy", "=", "SPINN5_ETH_OFFSET", "[", "(", "y", "-", "root_y", ")", "%", "12", "]", "[", "(", "x", "-", "root_x", ")", "%", ...
34.55
0.001408
def update_queue(self): """Update queue""" started = 0 for parent_id, threadlist in list(self.started_threads.items()): still_running = [] for thread in threadlist: if thread.isFinished(): end_callback = self.end_callbacks.pop(id...
[ "def", "update_queue", "(", "self", ")", ":", "started", "=", "0", "for", "parent_id", ",", "threadlist", "in", "list", "(", "self", ".", "started_threads", ".", "items", "(", ")", ")", ":", "still_running", "=", "[", "]", "for", "thread", "in", "threa...
46.032258
0.001373
def tokenize_line(line): """ Tokenize a line: * split tokens on whitespace * treat quoted strings as a single token * drop comments * handle escaped spaces and comment delimiters """ ret = [] escape = False quote = False tokbuf = "" ll = list(line) while len(ll) > 0: ...
[ "def", "tokenize_line", "(", "line", ")", ":", "ret", "=", "[", "]", "escape", "=", "False", "quote", "=", "False", "tokbuf", "=", "\"\"", "ll", "=", "list", "(", "line", ")", "while", "len", "(", "ll", ")", ">", "0", ":", "c", "=", "ll", ".", ...
23.71875
0.001898
def factor_returns(factor_data, demeaned=True, group_adjust=False, equal_weight=False, by_asset=False): """ Computes period wise returns for portfolio weighted by factor values. Parameters ---------- factor_data : pd.Da...
[ "def", "factor_returns", "(", "factor_data", ",", "demeaned", "=", "True", ",", "group_adjust", "=", "False", ",", "equal_weight", "=", "False", ",", "by_asset", "=", "False", ")", ":", "weights", "=", "factor_weights", "(", "factor_data", ",", "demeaned", "...
33.895833
0.000597
def get_batched(portal_type=None, uid=None, endpoint=None, **kw): """Get batched results """ # fetch the catalog results results = get_search_results(portal_type=portal_type, uid=uid, **kw) # fetch the batch params from the request size = req.get_batch_size() start = req.get_batch_start() ...
[ "def", "get_batched", "(", "portal_type", "=", "None", ",", "uid", "=", "None", ",", "endpoint", "=", "None", ",", "*", "*", "kw", ")", ":", "# fetch the catalog results", "results", "=", "get_search_results", "(", "portal_type", "=", "portal_type", ",", "ui...
32.75
0.001484
def record_ce_entries(self): # type: () -> bytes ''' Return a string representing the Rock Ridge entries in the Continuation Entry. Parameters: None. Returns: A string representing the Rock Ridge entry. ''' if not self._initialized: ...
[ "def", "record_ce_entries", "(", "self", ")", ":", "# type: () -> bytes", "if", "not", "self", ".", "_initialized", ":", "raise", "pycdlibexception", ".", "PyCdlibInternalError", "(", "'Rock Ridge extension not yet initialized'", ")", "return", "self", ".", "_record", ...
31.428571
0.011038
def get_attribute(self, name): """Gets the given attribute or property of the element. This method will first try to return the value of a property with the given name. If a property with that name doesn't exist, it returns the value of the attribute with the same name. If there's no at...
[ "def", "get_attribute", "(", "self", ",", "name", ")", ":", "attributeValue", "=", "''", "if", "self", ".", "_w3c", ":", "attributeValue", "=", "self", ".", "parent", ".", "execute_script", "(", "\"return (%s).apply(null, arguments);\"", "%", "getAttribute_js", ...
40.657143
0.002059
def train(args, params): ''' Train model ''' x_train, y_train, x_test, y_test = load_mnist_data(args) model = create_mnist_model(params) # nni model.fit(x_train, y_train, batch_size=args.batch_size, epochs=args.epochs, verbose=1, validation_data=(x_test, y_test), callbacks=[SendMet...
[ "def", "train", "(", "args", ",", "params", ")", ":", "x_train", ",", "y_train", ",", "x_test", ",", "y_test", "=", "load_mnist_data", "(", "args", ")", "model", "=", "create_mnist_model", "(", "params", ")", "# nni ", "model", ".", "fit", "(", "x_train"...
34.571429
0.01006
def submit(self, command_line, name = None, array = None, dependencies = [], exec_dir = None, log_dir = "logs", dry_run = False, verbosity = 0, stop_on_failure = False, **kwargs): """Submits a job that will be executed in the grid.""" # add job to database self.lock() job = add_job(self.session, command...
[ "def", "submit", "(", "self", ",", "command_line", ",", "name", "=", "None", ",", "array", "=", "None", ",", "dependencies", "=", "[", "]", ",", "exec_dir", "=", "None", ",", "log_dir", "=", "\"logs\"", ",", "dry_run", "=", "False", ",", "verbosity", ...
45.571429
0.029683
def file_set_visibility(object_id, input_params={}, always_retry=True, **kwargs): """ Invokes the /file-xxxx/setVisibility API method. For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Visibility#API-method%3A-%2Fclass-xxxx%2FsetVisibility """ return DXHTTPRequest('/%s/setVisib...
[ "def", "file_set_visibility", "(", "object_id", ",", "input_params", "=", "{", "}", ",", "always_retry", "=", "True", ",", "*", "*", "kwargs", ")", ":", "return", "DXHTTPRequest", "(", "'/%s/setVisibility'", "%", "object_id", ",", "input_params", ",", "always_...
54.857143
0.010256
def split_name(name): """Splits a (possibly versioned) name into unversioned name and version. Returns a tuple ``(unversioned_name, version)``, where ``version`` may be ``None``. """ s = name.rsplit('@', 1) if len(s) == 1: return s[0], None else: try: retur...
[ "def", "split_name", "(", "name", ")", ":", "s", "=", "name", ".", "rsplit", "(", "'@'", ",", "1", ")", "if", "len", "(", "s", ")", "==", "1", ":", "return", "s", "[", "0", "]", ",", "None", "else", ":", "try", ":", "return", "s", "[", "0",...
32.133333
0.002016
def range_is_obj(rng, rdfclass): """ Test to see if range for the class should be an object or a litteral """ if rng == 'rdfs_Literal': return False if hasattr(rdfclass, rng): mod_class = getattr(rdfclass, rng) for item in mod_class.cls_defs['rdf_type']: try: ...
[ "def", "range_is_obj", "(", "rng", ",", "rdfclass", ")", ":", "if", "rng", "==", "'rdfs_Literal'", ":", "return", "False", "if", "hasattr", "(", "rdfclass", ",", "rng", ")", ":", "mod_class", "=", "getattr", "(", "rdfclass", ",", "rng", ")", "for", "it...
33
0.001637
def rank(self): """ Returns the item's rank (if it has one) as a dict that includes required score, name, and level. """ if self._rank != {}: # Don't bother doing attribute lookups again return self._rank try: # The eater determining ...
[ "def", "rank", "(", "self", ")", ":", "if", "self", ".", "_rank", "!=", "{", "}", ":", "# Don't bother doing attribute lookups again", "return", "self", ".", "_rank", "try", ":", "# The eater determining the rank", "levelkey", ",", "typename", ",", "count", "=",...
29.241379
0.002283
def set_stage_for_epoch(self, epoch_start, name, attr='stage', save=True): """Change the stage for one specific epoch. Parameters ---------- epoch_start : int start time of the epoch, in seconds name : str description of the stage or qualifier. at...
[ "def", "set_stage_for_epoch", "(", "self", ",", "epoch_start", ",", "name", ",", "attr", "=", "'stage'", ",", "save", "=", "True", ")", ":", "if", "self", ".", "rater", "is", "None", ":", "raise", "IndexError", "(", "'You need to have at least one rater'", "...
34.447368
0.001486
def cli(conf): """ OpenVPN user_pass_verify method """ config = init_config(conf) nas_id = config.get('DEFAULT', 'nas_id') nas_addr = config.get('DEFAULT', 'nas_addr') secret = config.get('DEFAULT', 'radius_secret') radius_addr = config.get('DEFAULT', 'radius_addr') radius_auth_port = co...
[ "def", "cli", "(", "conf", ")", ":", "config", "=", "init_config", "(", "conf", ")", "nas_id", "=", "config", ".", "get", "(", "'DEFAULT'", ",", "'nas_id'", ")", "nas_addr", "=", "config", ".", "get", "(", "'DEFAULT'", ",", "'nas_addr'", ")", "secret",...
36.436364
0.011176
def addLocalHandlers (logger): """Adds logging handlers to logger to log to the following local resources: 1. The terminal 2. localhost:514 (i.e. syslogd) 3. localhost:2514 (i.e. the AIT GUI syslog-like handler) """ termlog = logging.StreamHandler() termlog.setFormatter(...
[ "def", "addLocalHandlers", "(", "logger", ")", ":", "termlog", "=", "logging", ".", "StreamHandler", "(", ")", "termlog", ".", "setFormatter", "(", "LogFormatter", "(", ")", ")", "logger", ".", "addHandler", "(", "termlog", ")", "logger", ".", "addHandler", ...
32.785714
0.021186
def getAssemblies(pth): """ Return the dependent assemblies of a binary. """ if not os.path.isfile(pth): pth = check_extract_from_egg(pth)[0][0] if pth.lower().endswith(".manifest"): return [] # check for manifest file manifestnm = pth + ".manifest" if os.path.isfile(mani...
[ "def", "getAssemblies", "(", "pth", ")", ":", "if", "not", "os", ".", "path", ".", "isfile", "(", "pth", ")", ":", "pth", "=", "check_extract_from_egg", "(", "pth", ")", "[", "0", "]", "[", "0", "]", "if", "pth", ".", "lower", "(", ")", ".", "e...
41.5
0.000471
def tx_tmpdir(base_dir, rollback_dirpath): """Context manager to create and remove a transactional temporary directory. """ # tmp_dir_base = join(base_dir, 'tx', str(uuid.uuid4())) # unique_attempts = 0 # while os.path.exists(tmp_dir_base): # if unique_attempts > 5: # break #...
[ "def", "tx_tmpdir", "(", "base_dir", ",", "rollback_dirpath", ")", ":", "# tmp_dir_base = join(base_dir, 'tx', str(uuid.uuid4()))", "# unique_attempts = 0", "# while os.path.exists(tmp_dir_base):", "# if unique_attempts > 5:", "# break", "# tmp_dir_base = join(base_dir, 'tx...
32.884615
0.002273
def _FlushAllRows(self, db_connection, table_name): """Copies rows from the given db into the output file then deletes them.""" for sql in db_connection.iterdump(): if (sql.startswith("CREATE TABLE") or sql.startswith("BEGIN TRANSACTION") or sql.startswith("COMMIT")): # These statements ...
[ "def", "_FlushAllRows", "(", "self", ",", "db_connection", ",", "table_name", ")", ":", "for", "sql", "in", "db_connection", ".", "iterdump", "(", ")", ":", "if", "(", "sql", ".", "startswith", "(", "\"CREATE TABLE\"", ")", "or", "sql", ".", "startswith", ...
53.5
0.01072
def objects_to_root(objects: List) -> Root: """ Convert a list of s3 ObjectSummaries into a directory tree. :param objects: The list of objects, e.g. the result of calling `.objects.all()` on a bucket. :return: The tree structure, contained within a root node. """ def _to_t...
[ "def", "objects_to_root", "(", "objects", ":", "List", ")", "->", "Root", ":", "def", "_to_tree", "(", "objs", ":", "Iterable", ")", "->", "Dict", ":", "\"\"\"\n Build a tree structure from a flat list of objects.\n\n :param objs: The raw iterable of S3 `ObjectS...
38.580645
0.000408
def get_digest(self): # type: () -> Digest """ Generates the digest used to do the actual signing. Signing keys can have variable length and tend to be quite long, which makes them not-well-suited for use in crypto algorithms. The digest is essentially the result of run...
[ "def", "get_digest", "(", "self", ")", ":", "# type: () -> Digest", "hashes_per_fragment", "=", "FRAGMENT_LENGTH", "//", "Hash", ".", "LEN", "key_fragments", "=", "self", ".", "iter_chunks", "(", "FRAGMENT_LENGTH", ")", "# The digest will contain one hash per key fragment...
37.462963
0.001445
def capture(self, data_buffer = None, log_time = False, debug_print = False, retry_reset = True): """Capture a frame of data. Captures 80x60 uint16 array of non-normalized (raw 12-bit) data. Returns that frame and a frame_id (which is currently just the sum of all pixels). The Lepton will return multiple, ...
[ "def", "capture", "(", "self", ",", "data_buffer", "=", "None", ",", "log_time", "=", "False", ",", "debug_print", "=", "False", ",", "retry_reset", "=", "True", ")", ":", "start", "=", "time", ".", "time", "(", ")", "if", "data_buffer", "is", "None", ...
40.647059
0.015544
def gtk(): """Reload GTK theme on the fly.""" # Here we call a Python 2 script to reload the GTK themes. # This is done because the Python 3 GTK/Gdk libraries don't # provide a way of doing this. if shutil.which("python2"): gtk_reload = os.path.join(MODULE_DIR, "scripts", "gtk_reload.py") ...
[ "def", "gtk", "(", ")", ":", "# Here we call a Python 2 script to reload the GTK themes.", "# This is done because the Python 3 GTK/Gdk libraries don't", "# provide a way of doing this.", "if", "shutil", ".", "which", "(", "\"python2\"", ")", ":", "gtk_reload", "=", "os", ".", ...
39
0.002278
def fit(self): """ Fits the model with random restarts. :return: """ self.model.optimize_restarts(num_restarts=self.num_restarts, verbose=False)
[ "def", "fit", "(", "self", ")", ":", "self", ".", "model", ".", "optimize_restarts", "(", "num_restarts", "=", "self", ".", "num_restarts", ",", "verbose", "=", "False", ")" ]
29.833333
0.016304
def _make_request_data(self, teststep_dict, entry_json): """ parse HAR entry request data, and make teststep request data Args: entry_json (dict): { "request": { "method": "POST", "postData": { ...
[ "def", "_make_request_data", "(", "self", ",", "teststep_dict", ",", "entry_json", ")", ":", "method", "=", "entry_json", "[", "\"request\"", "]", ".", "get", "(", "\"method\"", ")", "if", "method", "in", "[", "\"POST\"", ",", "\"PUT\"", ",", "\"PATCH\"", ...
34.912281
0.001955
def _build_cache_key(self, uri): """ Build sha1 hex cache key to handle key length and whitespace to be compatible with Memcached """ key = uri.clone(ext=None, version=None) if six.PY3: key = key.encode('utf-8') return sha1(key).hexdigest()
[ "def", "_build_cache_key", "(", "self", ",", "uri", ")", ":", "key", "=", "uri", ".", "clone", "(", "ext", "=", "None", ",", "version", "=", "None", ")", "if", "six", ".", "PY3", ":", "key", "=", "key", ".", "encode", "(", "'utf-8'", ")", "return...
29.3
0.009934
def sigmoid_grad(self, z): """Gradient of sigmoid function.""" return np.multiply(self.sigmoid(z), 1-self.sigmoid(z))
[ "def", "sigmoid_grad", "(", "self", ",", "z", ")", ":", "return", "np", ".", "multiply", "(", "self", ".", "sigmoid", "(", "z", ")", ",", "1", "-", "self", ".", "sigmoid", "(", "z", ")", ")" ]
43.666667
0.015038
def get_language_model_status(self, model_id, token=None, url=API_TRAIN_LANGUAGE_MODEL): """ Gets the status of your model, including whether the training has finished. :param model_id: string, the ID for a model you created previously. returns: a request object """ ...
[ "def", "get_language_model_status", "(", "self", ",", "model_id", ",", "token", "=", "None", ",", "url", "=", "API_TRAIN_LANGUAGE_MODEL", ")", ":", "auth", "=", "'Bearer '", "+", "self", ".", "check_for_token", "(", "token", ")", "h", "=", "{", "'Authorizati...
48.818182
0.012797
def open_required(func): """Decorator to specify that the J-Link DLL must be opened, and a J-Link connection must be established. Args: func (function): function being decorated Returns: The wrapper function. """ @functools.wraps(func) def wr...
[ "def", "open_required", "(", "func", ")", ":", "@", "functools", ".", "wraps", "(", "func", ")", "def", "wrapper", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "\"\"\"Wrapper function to check that the given ``JLink`` has been\n ope...
34.787879
0.001695
def _ExportEvents( self, storage_reader, output_module, deduplicate_events=True, event_filter=None, time_slice=None, use_time_slicer=False): """Exports events using an output module. Args: storage_reader (StorageReader): storage reader. output_module (OutputModule): output module. ...
[ "def", "_ExportEvents", "(", "self", ",", "storage_reader", ",", "output_module", ",", "deduplicate_events", "=", "True", ",", "event_filter", "=", "None", ",", "time_slice", "=", "None", ",", "use_time_slicer", "=", "False", ")", ":", "self", ".", "_status", ...
37.631068
0.008296
def get_default_config(): """ Produces a stock/out-of-the-box TidyPy configuration. :rtype: dict """ config = {} for name, cls in iteritems(get_tools()): config[name] = cls.get_default_config() try: workers = multiprocessing.cpu_count() - 1 except NotImplementedError:...
[ "def", "get_default_config", "(", ")", ":", "config", "=", "{", "}", "for", "name", ",", "cls", "in", "iteritems", "(", "get_tools", "(", ")", ")", ":", "config", "[", "name", "]", "=", "cls", ".", "get_default_config", "(", ")", "try", ":", "workers...
20.852941
0.001348
def getplan(self, size="150", axes=None, padding=None): """ Identify a plan for chunking values along each dimension. Generates an ndarray with the size (in number of elements) of chunks in each dimension. If provided, will estimate chunks for only a subset of axes, leaving all ...
[ "def", "getplan", "(", "self", ",", "size", "=", "\"150\"", ",", "axes", "=", "None", ",", "padding", "=", "None", ")", ":", "from", "numpy", "import", "dtype", "as", "gettype", "# initialize with all elements in one chunk", "plan", "=", "self", ".", "vshape...
32.974684
0.001118
def parseMemory(buffer, size): """parse an XML in-memory block and build a tree. """ ret = libxml2mod.xmlParseMemory(buffer, size) if ret is None:raise parserError('xmlParseMemory() failed') return xmlDoc(_obj=ret)
[ "def", "parseMemory", "(", "buffer", ",", "size", ")", ":", "ret", "=", "libxml2mod", ".", "xmlParseMemory", "(", "buffer", ",", "size", ")", "if", "ret", "is", "None", ":", "raise", "parserError", "(", "'xmlParseMemory() failed'", ")", "return", "xmlDoc", ...
45.2
0.013043
def count_resources(domain, token): """ Given the domain in question, generates counts for that domain of each of the different data types. Parameters ---------- domain: str A Socrata data portal domain. "data.seattle.gov" or "data.cityofnewyork.us" for example. token: str A Soc...
[ "def", "count_resources", "(", "domain", ",", "token", ")", ":", "resources", "=", "get_resources", "(", "domain", ",", "token", ")", "return", "dict", "(", "Counter", "(", "[", "r", "[", "'resource'", "]", "[", "'type'", "]", "for", "r", "in", "resour...
43.222222
0.008805
def irc(self, *args, **kwargs): """ Post IRC Message Post a message on IRC to a specific channel or user, or a specific user on a specific channel. Success of this API method does not imply the message was successfully posted. This API method merely inserts the IRC mess...
[ "def", "irc", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_makeApiCall", "(", "self", ".", "funcinfo", "[", "\"irc\"", "]", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
38.227273
0.00232
def validate_cbarpos(value): """Validate a colorbar position Parameters ---------- value: bool or str A string can be a combination of 'sh|sv|fl|fr|ft|fb|b|r' Returns ------- list list of strings with possible colorbar positions Raises ------ ValueError""" ...
[ "def", "validate_cbarpos", "(", "value", ")", ":", "patt", "=", "'sh|sv|fl|fr|ft|fb|b|r'", "if", "value", "is", "True", ":", "value", "=", "{", "'b'", "}", "elif", "not", "value", ":", "value", "=", "set", "(", ")", "elif", "isinstance", "(", "value", ...
26.84375
0.001124
def plot_ortho_double(image, image2, overlay=None, overlay2=None, reorient=True, # xyz arguments xyz=None, xyz_lines=True, xyz_color='red', xyz_alpha=0.6, xyz_linewidth=2, xyz_pad=5, # base image arguments cmap='Greys_r', alpha=1, cmap2='Greys_r', alpha2=1, # overlay arguments overlay_cmap='jet'...
[ "def", "plot_ortho_double", "(", "image", ",", "image2", ",", "overlay", "=", "None", ",", "overlay2", "=", "None", ",", "reorient", "=", "True", ",", "# xyz arguments", "xyz", "=", "None", ",", "xyz_lines", "=", "True", ",", "xyz_color", "=", "'red'", "...
40.83455
0.012505
def unpack_location(location): """ Returns (:Placeable:, :Vector:) tuple If :location: is :Placeable: it will get converted to (:Placeable:, :Vector: corresponding to the top) """ coordinates = None placeable = None if isinstance(location, Placeable): placeable, coordinates = lo...
[ "def", "unpack_location", "(", "location", ")", ":", "coordinates", "=", "None", "placeable", "=", "None", "if", "isinstance", "(", "location", ",", "Placeable", ")", ":", "placeable", ",", "coordinates", "=", "location", ".", "top", "(", ")", "elif", "isi...
27.7
0.001745
def _zforce(self,R,z,phi=0.,t=0.): """ NAME: zforce PURPOSE: evaluate vertical force K_z (R,z) INPUT: R - Cylindrical Galactocentric radius z - vertical height phi - azimuth t - time OUTPUT: K_z (R,z) ...
[ "def", "_zforce", "(", "self", ",", "R", ",", "z", ",", "phi", "=", "0.", ",", "t", "=", "0.", ")", ":", "if", "self", ".", "_new", ":", "#if R > 6.: return self._kp(R,z)", "if", "nu", ".", "fabs", "(", "z", ")", "<", "10.", "**", "-", "6.", ":...
42.473684
0.013931
def stop(self): """ Stop the consumer and return offset of last processed message. This cancels all outstanding operations. Also, if the deferred returned by `start` hasn't been called, it is called with a tuple consisting of the last processed offset and the last committed off...
[ "def", "stop", "(", "self", ")", ":", "if", "self", ".", "_start_d", "is", "None", ":", "raise", "RestopError", "(", "\"Stop called on non-running consumer\"", ")", "self", ".", "_stopping", "=", "True", "# Keep track of state for debugging", "self", ".", "_state"...
39.517857
0.000882
def get( self, app_id, metric_id, timespan=None, interval=None, aggregation=None, segment=None, top=None, orderby=None, filter=None, custom_headers=None, raw=False, **operation_config): """Retrieve metric data. Gets metric values for a single metric. :param app_id: ID of the applic...
[ "def", "get", "(", "self", ",", "app_id", ",", "metric_id", ",", "timespan", "=", "None", ",", "interval", "=", "None", ",", "aggregation", "=", "None", ",", "segment", "=", "None", ",", "top", "=", "None", ",", "orderby", "=", "None", ",", "filter",...
52.398438
0.001317
def top(self, n): "Return (count, obs) tuples for the n most frequent observations." return heapq.nlargest(n, [(v, k) for (k, v) in self.dictionary.items()])
[ "def", "top", "(", "self", ",", "n", ")", ":", "return", "heapq", ".", "nlargest", "(", "n", ",", "[", "(", "v", ",", "k", ")", "for", "(", "k", ",", "v", ")", "in", "self", ".", "dictionary", ".", "items", "(", ")", "]", ")" ]
57
0.017341
def squeezenet1_1(pretrained=False, **kwargs): r"""SqueezeNet 1.1 model from the `official SqueezeNet repo <https://github.com/DeepScale/SqueezeNet/tree/master/SqueezeNet_v1.1>`_. SqueezeNet 1.1 has 2.4x less computation and slightly fewer parameters than SqueezeNet 1.0, without sacrificing accuracy. ...
[ "def", "squeezenet1_1", "(", "pretrained", "=", "False", ",", "*", "*", "kwargs", ")", ":", "model", "=", "SqueezeNet", "(", "version", "=", "1.1", ",", "*", "*", "kwargs", ")", "if", "pretrained", ":", "model", ".", "load_state_dict", "(", "model_zoo", ...
43.153846
0.001745
def setProperty(self, name, value): """ Sets the property for this item to the inputed value for the given name. :param name | <str> value | <variant> """ if type(value) in (unicode, str): try: value = self._p...
[ "def", "setProperty", "(", "self", ",", "name", ",", "value", ")", ":", "if", "type", "(", "value", ")", "in", "(", "unicode", ",", "str", ")", ":", "try", ":", "value", "=", "self", ".", "_parsers", "[", "name", "]", "(", "value", ")", "except",...
30.928571
0.011211
def get_url(self, url, dest, makedirs=False, saltenv='base', no_cache=False, cachedir=None, source_hash=None): ''' Get a single file from a URL. ''' url_data = urlparse(url) url_scheme = url_data.scheme url_path = os.path.join( url_data.net...
[ "def", "get_url", "(", "self", ",", "url", ",", "dest", ",", "makedirs", "=", "False", ",", "saltenv", "=", "'base'", ",", "no_cache", "=", "False", ",", "cachedir", "=", "None", ",", "source_hash", "=", "None", ")", ":", "url_data", "=", "urlparse", ...
45.55477
0.000987
def __parse(self, raw_string): """ parse raw string, replace function and variable with {} Args: raw_string(str): string with functions or varialbes e.g. "ABC${func2($a, $b)}DE$c" Returns: string: "ABC{}DE{}" args: ["${func2($a, $b)}", "$c"] ...
[ "def", "__parse", "(", "self", ",", "raw_string", ")", ":", "self", ".", "_args", "=", "[", "]", "def", "escape_braces", "(", "origin_string", ")", ":", "return", "origin_string", ".", "replace", "(", "\"{\"", ",", "\"{{\"", ")", ".", "replace", "(", "...
37.291139
0.001984
def export_partlist_to_file(input, output, timeout=20, showgui=False): ''' call eagle and export sch or brd to partlist text file :param input: .sch or .brd file name :param output: text file name :param timeout: int :param showgui: Bool, True -> do not hide eagle GUI :rtype: None ''' ...
[ "def", "export_partlist_to_file", "(", "input", ",", "output", ",", "timeout", "=", "20", ",", "showgui", "=", "False", ")", ":", "input", "=", "norm_path", "(", "input", ")", "output", "=", "norm_path", "(", "output", ")", "commands", "=", "export_command...
32.875
0.001848
def custom_result(self, **options): """ Provides a context manager that can be used to customize the ``_all_docs`` behavior and wrap the output as a :class:`~cloudant.result.Result`. :param bool descending: Return documents in descending key order. :param endkey: Stop re...
[ "def", "custom_result", "(", "self", ",", "*", "*", "options", ")", ":", "rslt", "=", "Result", "(", "self", ".", "all_docs", ",", "*", "*", "options", ")", "yield", "rslt", "del", "rslt" ]
45.405405
0.001166
def get_extensions(cert_type): ''' Fetch X509 and CSR extension definitions from tls:extensions: (common|server|client) or set them to standard defaults. .. versionadded:: 2015.8.0 cert_type: The type of certificate such as ``server`` or ``client``. CLI Example: .. code-block:: b...
[ "def", "get_extensions", "(", "cert_type", ")", ":", "assert", "X509_EXT_ENABLED", ",", "(", "'X509 extensions are not supported in '", "'pyOpenSSL prior to version 0.15.1. Your '", "'version: {0}'", ".", "format", "(", "OpenSSL_version", ")", ")", "ext", "=", "{", "}", ...
27.898876
0.000778
def get_complexes(self, cplx_df): """Generate Complex Statements from the HPRD protein complexes data. Parameters ---------- cplx_df : pandas.DataFrame DataFrame loaded from the PROTEIN_COMPLEXES.txt file. """ # Group the agents for the complex logg...
[ "def", "get_complexes", "(", "self", ",", "cplx_df", ")", ":", "# Group the agents for the complex", "logger", ".", "info", "(", "'Processing complexes...'", ")", "for", "cplx_id", ",", "this_cplx", "in", "cplx_df", ".", "groupby", "(", "'CPLX_ID'", ")", ":", "a...
41.038462
0.001832
def cancel( self, accountID, orderSpecifier, **kwargs ): """ Cancel a pending Order in an Account Args: accountID: Account Identifier orderSpecifier: The Order Specifier Returns: v20...
[ "def", "cancel", "(", "self", ",", "accountID", ",", "orderSpecifier", ",", "*", "*", "kwargs", ")", ":", "request", "=", "Request", "(", "'PUT'", ",", "'/v3/accounts/{accountID}/orders/{orderSpecifier}/cancel'", ")", "request", ".", "set_path_param", "(", "'accou...
29.788136
0.001377
def format_data(self, data, scale=True): """ Function for converting a dict to an array suitable for sklearn. Parameters ---------- data : dict A dict of data, containing all elements of `analytes` as items. scale : bool Whether or not...
[ "def", "format_data", "(", "self", ",", "data", ",", "scale", "=", "True", ")", ":", "if", "len", "(", "self", ".", "analytes", ")", "==", "1", ":", "# if single analyte", "d", "=", "nominal_values", "(", "data", "[", "self", ".", "analytes", "[", "0...
32
0.001596
def calc_file_md5(filepath, chunk_size=None): """ Calculate a file's md5 checksum. Use the specified chunk_size for IO or the default 256KB :param filepath: :param chunk_size: :return: """ if chunk_size is None: chunk_size = 256 * 1024 md5sum = hashlib.md5() with io.open...
[ "def", "calc_file_md5", "(", "filepath", ",", "chunk_size", "=", "None", ")", ":", "if", "chunk_size", "is", "None", ":", "chunk_size", "=", "256", "*", "1024", "md5sum", "=", "hashlib", ".", "md5", "(", ")", "with", "io", ".", "open", "(", "filepath",...
28.157895
0.001808
def markdown(value, extensions=settings.MARKDOWN_EXTENSIONS, extension_configs=settings.MARKDOWN_EXTENSION_CONFIGS, safe=False): """ Render markdown over a given value, optionally using varios extensions. Default extensions could be defined which MARKDOWN_EXTENSIONS option. :retu...
[ "def", "markdown", "(", "value", ",", "extensions", "=", "settings", ".", "MARKDOWN_EXTENSIONS", ",", "extension_configs", "=", "settings", ".", "MARKDOWN_EXTENSION_CONFIGS", ",", "safe", "=", "False", ")", ":", "return", "mark_safe", "(", "markdown_module", ".", ...
38.461538
0.001953
def _get_peer_connection(self, blacklist=None): """Find a peer and connect to it. Returns a ``(peer, connection)`` tuple. Raises ``NoAvailablePeerError`` if no healthy peers are found. :param blacklist: If given, a set of hostports for peers that we must not try. "...
[ "def", "_get_peer_connection", "(", "self", ",", "blacklist", "=", "None", ")", ":", "blacklist", "=", "blacklist", "or", "set", "(", ")", "peer", "=", "None", "connection", "=", "None", "while", "connection", "is", "None", ":", "peer", "=", "self", ".",...
28.611111
0.001878
def _proxy(self): """ Generate an instance context for the instance, the context is capable of performing various actions. All instance actions are proxied to the context :returns: IpAccessControlListContext for this IpAccessControlListInstance :rtype: twilio.rest.api.v2010.acc...
[ "def", "_proxy", "(", "self", ")", ":", "if", "self", ".", "_context", "is", "None", ":", "self", ".", "_context", "=", "IpAccessControlListContext", "(", "self", ".", "_version", ",", "account_sid", "=", "self", ".", "_solution", "[", "'account_sid'", "]"...
42.8
0.009146
def status(name, runas=None): ''' Return the status for a service via systemd. If the name contains globbing, a dict mapping service name to True/False values is returned. .. versionchanged:: 2018.3.0 The service name can now be a glob (e.g. ``salt*``) Args: name (str): The nam...
[ "def", "status", "(", "name", ",", "runas", "=", "None", ")", ":", "contains_globbing", "=", "bool", "(", "re", ".", "search", "(", "r'\\*|\\?|\\[.+\\]'", ",", "name", ")", ")", "if", "contains_globbing", ":", "services", "=", "fnmatch", ".", "filter", "...
31.34
0.002475
def weekdays(start, end): """ Returns the number of weekdays between the inputted start and end dates. This would be the equivalent of doing (end - start) to get the number of calendar days between the two dates. :param start | <datetime.date> end | <datetime.date> ...
[ "def", "weekdays", "(", "start", ",", "end", ")", ":", "# don't bother calculating anything for the same inputted date", "if", "start", "==", "end", ":", "return", "int", "(", "start", ".", "isoweekday", "(", ")", "not", "in", "(", "6", ",", "7", ")", ")", ...
33.134615
0.001691
def _ThCond(rho, T, fase=None, drho=None): """Equation for the thermal conductivity Parameters ---------- rho : float Density, [kg/m³] T : float Temperature, [K] fase: dict, optional for calculate critical enhancement phase properties drho: float, optional for calcul...
[ "def", "_ThCond", "(", "rho", ",", "T", ",", "fase", "=", "None", ",", "drho", "=", "None", ")", ":", "d", "=", "rho", "/", "rhoc", "Tr", "=", "T", "/", "Tc", "# Eq 16", "no", "=", "[", "2.443221e-3", ",", "1.323095e-2", ",", "6.770357e-3", ",", ...
33.959596
0.000578
def get_client_cache_key(request_or_attempt: Union[HttpRequest, Any], credentials: dict = None) -> str: """ Build cache key name from request or AccessAttempt object. :param request_or_attempt: HttpRequest or AccessAttempt object :param credentials: credentials containing user information :return c...
[ "def", "get_client_cache_key", "(", "request_or_attempt", ":", "Union", "[", "HttpRequest", ",", "Any", "]", ",", "credentials", ":", "dict", "=", "None", ")", "->", "str", ":", "if", "isinstance", "(", "request_or_attempt", ",", "HttpRequest", ")", ":", "us...
41.8
0.001871
def _loss_lr_subject(self, data, labels, w, theta, bias): """Compute the Loss MLR for a single subject (without regularization) Parameters ---------- data : array, shape=[voxels, samples] The fMRI data of subject i for the classification task. labels : array of int...
[ "def", "_loss_lr_subject", "(", "self", ",", "data", ",", "labels", ",", "w", ",", "theta", ",", "bias", ")", ":", "if", "data", "is", "None", ":", "return", "0.0", "samples", "=", "data", ".", "shape", "[", "1", "]", "thetaT_wi_zi_plus_bias", "=", "...
30.512195
0.001549
def parse(readDataInstance): """ Returns a new L{NetMetaDataStreamEntry} object. @type readDataInstance: L{ReadData} @param readDataInstance: A L{ReadData} object with data to be parsed as a L{NetMetaDataStreamEntry}. @rtype: L{NetMetaDataStreamEntry} @r...
[ "def", "parse", "(", "readDataInstance", ")", ":", "n", "=", "NetMetaDataStreamEntry", "(", ")", "n", ".", "offset", ".", "value", "=", "readDataInstance", ".", "readDword", "(", ")", "n", ".", "size", ".", "value", "=", "readDataInstance", ".", "readDword...
38.933333
0.008361
def glob_files_locally(folder_path, pattern): """glob files in local folder based on the given pattern""" pattern = os.path.join( folder_path, pattern.lstrip('/')) if pattern else None len_folder_path = len(folder_path) + 1 for root, _, files in os.walk(folder_path): for f in files: ...
[ "def", "glob_files_locally", "(", "folder_path", ",", "pattern", ")", ":", "pattern", "=", "os", ".", "path", ".", "join", "(", "folder_path", ",", "pattern", ".", "lstrip", "(", "'/'", ")", ")", "if", "pattern", "else", "None", "len_folder_path", "=", "...
39.833333
0.002045
def get_file_para(path, path_in_arc=''): """ Generic method to read the file parameter file Helper function to consistently read the file parameter file, which can either be uncompressed or included in a zip archive. By default, the file name is to be expected as set in DEFAULT_FILE_NAMES['filepara'] ...
[ "def", "get_file_para", "(", "path", ",", "path_in_arc", "=", "''", ")", ":", "if", "type", "(", "path", ")", "is", "str", ":", "path", "=", "Path", "(", "path", ".", "rstrip", "(", "'\\\\'", ")", ")", "if", "zipfile", ".", "is_zipfile", "(", "str"...
37.961538
0.000329
def log_file_name(ext=False): """ Function : Creates a logfile name, named after this script and includes the number of seconds since the Epoch. An optional extension can be specified to make the logfile name more meaningful regarding its purpose. Args : ext - The extension to add to the log file...
[ "def", "log_file_name", "(", "ext", "=", "False", ")", ":", "script_name", "=", "os", ".", "path", ".", "splitext", "(", "os", ".", "path", ".", "basename", "(", "sys", ".", "argv", "[", "0", "]", ")", ")", "[", "0", "]", "val", "=", "script_name...
44.384615
0.016978
def set_current_client_working_directory(self, directory): """Set current client working directory.""" shellwidget = self.get_current_shellwidget() if shellwidget is not None: shellwidget.set_cwd(directory)
[ "def", "set_current_client_working_directory", "(", "self", ",", "directory", ")", ":", "shellwidget", "=", "self", ".", "get_current_shellwidget", "(", ")", "if", "shellwidget", "is", "not", "None", ":", "shellwidget", ".", "set_cwd", "(", "directory", ")" ]
48.4
0.00813
def occupation(self) -> str: """Get a random job. :return: The name of job. :Example: Programmer. """ jobs = self._data['occupation'] return self.random.choice(jobs)
[ "def", "occupation", "(", "self", ")", "->", "str", ":", "jobs", "=", "self", ".", "_data", "[", "'occupation'", "]", "return", "self", ".", "random", ".", "choice", "(", "jobs", ")" ]
21.8
0.008811
def user_create(username, login=None, domain='', database=None, roles=None, options=None, **kwargs): ''' Creates a new user. If login is not specified, the user will be created without a login. domain, if provided, will be prepended to username. options can only be a list of strings CLI Example: ...
[ "def", "user_create", "(", "username", ",", "login", "=", "None", ",", "domain", "=", "''", ",", "database", "=", "None", ",", "roles", "=", "None", ",", "options", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "domain", "and", "not", "logi...
32.692308
0.001713
def get_ip_addresses(): """Gets the ip addresses from ifconfig :return: (dict) of devices and aliases with the IPv4 address """ log = logging.getLogger(mod_logger + '.get_ip_addresses') command = ['/sbin/ifconfig'] try: result = run_command(command) except CommandError: rai...
[ "def", "get_ip_addresses", "(", ")", ":", "log", "=", "logging", ".", "getLogger", "(", "mod_logger", "+", "'.get_ip_addresses'", ")", "command", "=", "[", "'/sbin/ifconfig'", "]", "try", ":", "result", "=", "run_command", "(", "command", ")", "except", "Com...
28.818182
0.001017
def ca_bundle(self, ca_bundle): """ Sets the ca_bundle of this V1alpha1WebhookClientConfig. `caBundle` is a PEM encoded CA bundle which will be used to validate the webhook's server certificate. If unspecified, system trust roots on the apiserver are used. :param ca_bundle: The ca_bundl...
[ "def", "ca_bundle", "(", "self", ",", "ca_bundle", ")", ":", "if", "ca_bundle", "is", "not", "None", "and", "not", "re", ".", "search", "(", "'^(?:[A-Za-z0-9+\\/]{4})*(?:[A-Za-z0-9+\\/]{2}==|[A-Za-z0-9+\\/]{3}=)?$'", ",", "ca_bundle", ")", ":", "raise", "ValueError"...
60.083333
0.015027
def fill(self, value=b'\xff'): """Fill all empty space between segments with given value `value`. """ previous_segment_maximum_address = None fill_segments = [] for address, data in self._segments: maximum_address = address + len(data) if previous_segm...
[ "def", "fill", "(", "self", ",", "value", "=", "b'\\xff'", ")", ":", "previous_segment_maximum_address", "=", "None", "fill_segments", "=", "[", "]", "for", "address", ",", "data", "in", "self", ".", "_segments", ":", "maximum_address", "=", "address", "+", ...
36.083333
0.00225
def clgrad(obj, exe, arg, delta=DELTA): """ Returns numerical gradient function of given class method with respect to a class attribute Input: obj, general object exe (str), name of object method arg (str), name of object atribute delta(float, optional), finite differenc...
[ "def", "clgrad", "(", "obj", ",", "exe", ",", "arg", ",", "delta", "=", "DELTA", ")", ":", "f", ",", "x", "=", "get_method_and_copy_of_attribute", "(", "obj", ",", "exe", ",", "arg", ")", "def", "grad_f", "(", "*", "args", ",", "*", "*", "kwargs", ...
35.041667
0.002315
def route(self, path=None, method='GET', **kargs): """ Decorator: Bind a function to a GET request path. If the path parameter is None, the signature of the decorated function is used to generate the path. See yieldroutes() for details. The method parameter (def...
[ "def", "route", "(", "self", ",", "path", "=", "None", ",", "method", "=", "'GET'", ",", "*", "*", "kargs", ")", ":", "if", "isinstance", "(", "method", ",", "str", ")", ":", "#TODO: Test this", "method", "=", "method", ".", "split", "(", "';'", ")...
42.954545
0.008282
def put(self, key): """Put and return the only unique identifier possible, its url """ self._consul_request('PUT', self._key_url(key['name']), json=key) return key['name']
[ "def", "put", "(", "self", ",", "key", ")", ":", "self", ".", "_consul_request", "(", "'PUT'", ",", "self", ".", "_key_url", "(", "key", "[", "'name'", "]", ")", ",", "json", "=", "key", ")", "return", "key", "[", "'name'", "]" ]
39.8
0.009852
def inFootprint(config, pixels, nside=None): """ Open each valid filename for the set of pixels and determine the set of subpixels with valid data. """ config = Config(config) nside_catalog = config['coords']['nside_catalog'] nside_likelihood = config['coords']['nside_likelihood'] ns...
[ "def", "inFootprint", "(", "config", ",", "pixels", ",", "nside", "=", "None", ")", ":", "config", "=", "Config", "(", "config", ")", "nside_catalog", "=", "config", "[", "'coords'", "]", "[", "'nside_catalog'", "]", "nside_likelihood", "=", "config", "[",...
44.257143
0.01832
def _lookup_symbol_strict(self, ownership_map, multi_country, symbol, as_of_date): """ Resolve a symbol to an asset object without fuzzy matching. Parameters ---------...
[ "def", "_lookup_symbol_strict", "(", "self", ",", "ownership_map", ",", "multi_country", ",", "symbol", ",", "as_of_date", ")", ":", "# split the symbol into the components, if there are no", "# company/share class parts then share_class_symbol will be empty", "company_symbol", ","...
39.967742
0.001181
def load_cookies_file(cookies_file): """ Load cookies file. We pre-pend the file with the special Netscape header because the cookie loader is very particular about this string. """ logging.debug('Loading cookie file %s into memory.', cookies_file) cookies = StringIO() cookies.write('...
[ "def", "load_cookies_file", "(", "cookies_file", ")", ":", "logging", ".", "debug", "(", "'Loading cookie file %s into memory.'", ",", "cookies_file", ")", "cookies", "=", "StringIO", "(", ")", "cookies", ".", "write", "(", "'# Netscape HTTP Cookie File'", ")", "coo...
27.75
0.002179
def _onlooker_phase(self): '''Well-performing bees (chosen probabilistically based on fitness score) have a value merged with a second random bee ''' self.__verify_ready() self._logger.log('debug', 'Onlooker bee phase') modified = [] for _ in self._employers: ...
[ "def", "_onlooker_phase", "(", "self", ")", ":", "self", ".", "__verify_ready", "(", ")", "self", ".", "_logger", ".", "log", "(", "'debug'", ",", "'Onlooker bee phase'", ")", "modified", "=", "[", "]", "for", "_", "in", "self", ".", "_employers", ":", ...
37.206897
0.001807
def smoothEstimate(self, nodeShape, estimatedNodeCount): """ Smooth out fluctuations in the estimate for this node compared to previous runs. Returns an integer. """ weightedEstimate = (1 - self.betaInertia) * estimatedNodeCount + \ self.betaInertia * s...
[ "def", "smoothEstimate", "(", "self", ",", "nodeShape", ",", "estimatedNodeCount", ")", ":", "weightedEstimate", "=", "(", "1", "-", "self", ".", "betaInertia", ")", "*", "estimatedNodeCount", "+", "self", ".", "betaInertia", "*", "self", ".", "previousWeighte...
51.555556
0.008475
def transition_matrix_reversible_pisym(C, return_statdist=False, **kwargs): r""" Estimates reversible transition matrix as follows: ..:math: p_{ij} = c_{ij} / c_i where c_i = sum_j c_{ij} \pi_j = \sum_j \pi_i p_{ij} x_{ij} = \pi_i p_{ij} + \pi_j p_{ji} p^{rev}_{ij} = x_{ij} ...
[ "def", "transition_matrix_reversible_pisym", "(", "C", ",", "return_statdist", "=", "False", ",", "*", "*", "kwargs", ")", ":", "# nonreversible estimate", "T_nonrev", "=", "transition_matrix_non_reversible", "(", "C", ")", "from", "msmtools", ".", "analysis", "impo...
32.3
0.002254
def tmpl_first(text, count=1, skip=0, sep=u'; ', join_str=u'; '): """ * synopsis: ``%first{text}`` or ``%first{text,count,skip}`` or \ ``%first{text,count,skip,sep,join}`` * description: Returns the first item, separated by ; . You can use \ %first{text,count,skip}, where...
[ "def", "tmpl_first", "(", "text", ",", "count", "=", "1", ",", "skip", "=", "0", ",", "sep", "=", "u'; '", ",", "join_str", "=", "u'; '", ")", ":", "skip", "=", "int", "(", "skip", ")", "count", "=", "skip", "+", "int", "(", "count", ")", "retu...
51.052632
0.002024
def batch_indices_iterator(self, batch_size, **kwargs): """ Create an iterator that generates mini-batch sample indices The generated mini-batches indices take the form of nested lists of either: - 1D NumPy integer arrays - slices The list nesting structure with...
[ "def", "batch_indices_iterator", "(", "self", ",", "batch_size", ",", "*", "*", "kwargs", ")", ":", "if", "not", "self", ".", "_random_access", ":", "raise", "TypeError", "(", "'batch_indices_iterator method not supported as '", "'one or more of the underlying data source...
33.892857
0.002049
def url(self): """The reconstructed request URL (absolute).""" if self._url is None: self._url = request_uri(self.environ, include_query=1) return self._url
[ "def", "url", "(", "self", ")", ":", "if", "self", ".", "_url", "is", "None", ":", "self", ".", "_url", "=", "request_uri", "(", "self", ".", "environ", ",", "include_query", "=", "1", ")", "return", "self", ".", "_url" ]
37.6
0.010417
def jacobian(f, x, param): """ Calculates the jacobian matrix for d/dx_i (f(x)) """ N = len(x) M = len(param) J = np.zeros((N, M)) for i, x_i in enumerate(x): for j in range(M): parameters=[] for k, p_k in enumerate(param): parameters.appe...
[ "def", "jacobian", "(", "f", ",", "x", ",", "param", ")", ":", "N", "=", "len", "(", "x", ")", "M", "=", "len", "(", "param", ")", "J", "=", "np", ".", "zeros", "(", "(", "N", ",", "M", ")", ")", "for", "i", ",", "x_i", "in", "enumerate",...
27.722222
0.00969
def have(cmd): """Determine whether supplied argument is a command on the PATH.""" try: # Python 3.3+ only from shutil import which except ImportError: def which(cmd): """ Given a command, return the path which conforms to the given mode on the PA...
[ "def", "have", "(", "cmd", ")", ":", "try", ":", "# Python 3.3+ only", "from", "shutil", "import", "which", "except", "ImportError", ":", "def", "which", "(", "cmd", ")", ":", "\"\"\"\n Given a command, return the path which conforms to the given mode\n ...
35.292683
0.000672
def unwind(self): """ Get a list of all ancestors in descending order of level, including a new instance of self """ return [ QuadKey(self.key[:l+1]) for l in reversed(range(len(self.key))) ]
[ "def", "unwind", "(", "self", ")", ":", "return", "[", "QuadKey", "(", "self", ".", "key", "[", ":", "l", "+", "1", "]", ")", "for", "l", "in", "reversed", "(", "range", "(", "len", "(", "self", ".", "key", ")", ")", ")", "]" ]
53.25
0.032407
def execute(self): """ Execute the actions necessary to perform a `molecule lint` and returns None. :return: None """ self.print_info() linters = [ l for l in [ self._config.lint, self._config.verifier.lint, ...
[ "def", "execute", "(", "self", ")", ":", "self", ".", "print_info", "(", ")", "linters", "=", "[", "l", "for", "l", "in", "[", "self", ".", "_config", ".", "lint", ",", "self", ".", "_config", ".", "verifier", ".", "lint", ",", "self", ".", "_con...
23.222222
0.009195
async def sendSticker(self, chat_id, sticker, disable_notification=None, reply_to_message_id=None, reply_markup=None): """ See: https://core.telegram.org/bots/api#sendsticker :param sticker: Same as ``photo`` in :meth...
[ "async", "def", "sendSticker", "(", "self", ",", "chat_id", ",", "sticker", ",", "disable_notification", "=", "None", ",", "reply_to_message_id", "=", "None", ",", "reply_markup", "=", "None", ")", ":", "p", "=", "_strip", "(", "locals", "(", ")", ",", "...
44.909091
0.011905
def printBlastRecord(record): """ Print a BLAST record. @param record: A BioPython C{Bio.Blast.Record.Blast} instance. """ for key in sorted(record.__dict__.keys()): if key not in ['alignments', 'descriptions', 'reference']: print('%s: %r' % (key, record.__dict__[key])) prin...
[ "def", "printBlastRecord", "(", "record", ")", ":", "for", "key", "in", "sorted", "(", "record", ".", "__dict__", ".", "keys", "(", ")", ")", ":", "if", "key", "not", "in", "[", "'alignments'", ",", "'descriptions'", ",", "'reference'", "]", ":", "prin...
47.857143
0.000976
def com_google_fonts_check_font_copyright(ttFont): """Copyright notices match canonical pattern in fonts""" import re from fontbakery.utils import get_name_entry_strings failed = False for string in get_name_entry_strings(ttFont, NameID.COPYRIGHT_NOTICE): does_match = re.search(r'Copyright [0-9]{4} The ....
[ "def", "com_google_fonts_check_font_copyright", "(", "ttFont", ")", ":", "import", "re", "from", "fontbakery", ".", "utils", "import", "get_name_entry_strings", "failed", "=", "False", "for", "string", "in", "get_name_entry_strings", "(", "ttFont", ",", "NameID", "....
41.727273
0.011715
def OnMenu(self, event): """Menu event handler""" msgtype = self.ids_msgs[event.GetId()] post_command_event(self.parent, msgtype)
[ "def", "OnMenu", "(", "self", ",", "event", ")", ":", "msgtype", "=", "self", ".", "ids_msgs", "[", "event", ".", "GetId", "(", ")", "]", "post_command_event", "(", "self", ".", "parent", ",", "msgtype", ")" ]
30
0.012987
def _guess_vc_legacy(self): """ Locate Visual C for versions prior to 2017 """ default = r'Microsoft Visual Studio %0.1f\VC' % self.vc_ver return os.path.join(self.ProgramFilesx86, default)
[ "def", "_guess_vc_legacy", "(", "self", ")", ":", "default", "=", "r'Microsoft Visual Studio %0.1f\\VC'", "%", "self", ".", "vc_ver", "return", "os", ".", "path", ".", "join", "(", "self", ".", "ProgramFilesx86", ",", "default", ")" ]
37.333333
0.008734
def read_knmi_dataset(directory): """Reads files from a directory and merges the time series Please note: For each station, a separate directory must be provided! data availability: www.knmi.nl/nederland-nu/klimatologie/uurgegevens Args: directory: directory including the files Returns: ...
[ "def", "read_knmi_dataset", "(", "directory", ")", ":", "filemask", "=", "'%s*.txt'", "%", "directory", "filelist", "=", "glob", ".", "glob", "(", "filemask", ")", "columns_hourly", "=", "[", "'temp'", ",", "'precip'", ",", "'glob'", ",", "'hum'", ",", "'w...
28.821429
0.001199
def timeRange( start: datetime.time, end: datetime.time, step: float) -> Iterator[datetime.datetime]: """ Iterator that waits periodically until certain time points are reached while yielding those time points. Args: start: Start time, can be specified as datetime.datetime, ...
[ "def", "timeRange", "(", "start", ":", "datetime", ".", "time", ",", "end", ":", "datetime", ".", "time", ",", "step", ":", "float", ")", "->", "Iterator", "[", "datetime", ".", "datetime", "]", ":", "assert", "step", ">", "0", "start", "=", "_fillDa...
33.24
0.00117
def create(self, stage_url, tileset, name=None, patch=False, bypass=False): """Create a tileset Note: this step is refered to as "upload" in the API docs; This class's upload() method is a high-level function which acts like the Studio upload form. Returns a response object whe...
[ "def", "create", "(", "self", ",", "stage_url", ",", "tileset", ",", "name", "=", "None", ",", "patch", "=", "False", ",", "bypass", "=", "False", ")", ":", "tileset", "=", "self", ".", "_validate_tileset", "(", "tileset", ")", "username", ",", "_name"...
32.77193
0.00104
def prtcols(items, vpad=6): ''' After computing the size of our rows and columns based on the terminal size and length of the largest element, use zip to aggregate our column lists into row lists and then iterate over the row lists and print them. ''' from os import get_terminal_size items =...
[ "def", "prtcols", "(", "items", ",", "vpad", "=", "6", ")", ":", "from", "os", "import", "get_terminal_size", "items", "=", "list", "(", "items", ")", "# copy list so we don't mutate it", "width", ",", "height", "=", "get_terminal_size", "(", ")", "height", ...
41.941176
0.001372