text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def get_primary_key_columns(self): """ Returns the primary key columns. :rtype: list """ if not self.has_primary_key(): raise DBALException('Table "%s" has no primary key.' % self.get_name()) return self.get_primary_key().get_columns()
[ "def", "get_primary_key_columns", "(", "self", ")", ":", "if", "not", "self", ".", "has_primary_key", "(", ")", ":", "raise", "DBALException", "(", "'Table \"%s\" has no primary key.'", "%", "self", ".", "get_name", "(", ")", ")", "return", "self", ".", "get_p...
28.8
0.010101
def hdrmap(xmethod, dmethod, opt): """Return ``hdrmap`` argument for ``.IterStatsConfig`` initialiser. """ hdr = {'Itn': 'Iter', 'Fnc': 'ObjFun', 'DFid': 'DFid', u('ℓ1'): 'RegL1', 'Cnstr': 'Cnstr'} if xmethod == 'admm': hdr.update({'r_X': 'XPrRsdl', 's_X': 'XDlRsdl', u('ρ_X'): 'XRho'...
[ "def", "hdrmap", "(", "xmethod", ",", "dmethod", ",", "opt", ")", ":", "hdr", "=", "{", "'Itn'", ":", "'Iter'", ",", "'Fnc'", ":", "'ObjFun'", ",", "'DFid'", ":", "'DFid'", ",", "u", "(", "'ℓ1'):", " ", "'", "egL1', ", "'", "nstr': ", "'", "nstr'}"...
38.565217
0.0011
def evaluate(op, op_str, a, b, use_numexpr=True, **eval_kwargs): """ evaluate and return the expression of the op on a and b Parameters ---------- op : the actual operand op_str: the string version of the op a : left operand b : right operand...
[ "def", "evaluate", "(", "op", ",", "op_str", ",", "a", ",", "b", ",", "use_numexpr", "=", "True", ",", "*", "*", "eval_kwargs", ")", ":", "use_numexpr", "=", "use_numexpr", "and", "_bool_arith_check", "(", "op_str", ",", "a", ",", "b", ")", "if", "us...
31.944444
0.001689
def _execute_for_run_dates(self, run_dates, ti_status, executor, pickle_id, start_date, session=None): """ Computes the dag runs and their respective task instances for the given run dates and executes the task instances. Returns a list of execution dates o...
[ "def", "_execute_for_run_dates", "(", "self", ",", "run_dates", ",", "ti_status", ",", "executor", ",", "pickle_id", ",", "start_date", ",", "session", "=", "None", ")", ":", "for", "next_run_date", "in", "run_dates", ":", "dag_run", "=", "self", ".", "_get_...
44.394737
0.00232
def tolist(val): """Convert a value that may be a list or a (possibly comma-separated) string into a list. The exception: None is returned as None, not [None]. >>> tolist(["one", "two"]) ['one', 'two'] >>> tolist("hello") ['hello'] >>> tolist("separate,values, with, commas, spaces , are ...
[ "def", "tolist", "(", "val", ")", ":", "if", "val", "is", "None", ":", "return", "None", "try", ":", "# might already be a list", "val", ".", "extend", "(", "[", "]", ")", "return", "val", "except", "AttributeError", ":", "pass", "# might be a string", "tr...
27.48
0.001406
def check_cv(cv=3, y=None, classifier=False): """Dask aware version of ``sklearn.model_selection.check_cv`` Same as the scikit-learn version, but works if ``y`` is a dask object. """ if cv is None: cv = 3 # If ``cv`` is not an integer, the scikit-learn implementation doesn't # touch th...
[ "def", "check_cv", "(", "cv", "=", "3", ",", "y", "=", "None", ",", "classifier", "=", "False", ")", ":", "if", "cv", "is", "None", ":", "cv", "=", "3", "# If ``cv`` is not an integer, the scikit-learn implementation doesn't", "# touch the ``y`` object, so passing o...
39.842105
0.00129
def startstop(inst_id, cmdtodo): """Start or Stop the Specified Instance. Args: inst_id (str): instance-id to perform command against cmdtodo (str): command to perform (start or stop) Returns: response (dict): reponse returned from AWS after performing speci...
[ "def", "startstop", "(", "inst_id", ",", "cmdtodo", ")", ":", "tar_inst", "=", "EC2R", ".", "Instance", "(", "inst_id", ")", "thecmd", "=", "getattr", "(", "tar_inst", ",", "cmdtodo", ")", "response", "=", "thecmd", "(", ")", "return", "response" ]
29.933333
0.00216
def raise_205(instance): """Abort the current request with a 205 (Reset Content) response code. Clears out the body of the response. :param instance: Resource instance (used to access the response) :type instance: :class:`webob.resource.Resource` :raises: :class:`webob.exceptions.ResponseException`...
[ "def", "raise_205", "(", "instance", ")", ":", "instance", ".", "response", ".", "status", "=", "205", "instance", ".", "response", ".", "body", "=", "''", "instance", ".", "response", ".", "body_raw", "=", "None", "raise", "ResponseException", "(", "insta...
40.25
0.002024
def _compile_mothur_script(self): """Returns a Mothur batch script as a string""" def format_opts(*opts): """Formats a series of options for a Mothur script""" return ', '.join(filter(None, map(str, opts))) vars = { 'in': self._input_filename, 'uni...
[ "def", "_compile_mothur_script", "(", "self", ")", ":", "def", "format_opts", "(", "*", "opts", ")", ":", "\"\"\"Formats a series of options for a Mothur script\"\"\"", "return", "', '", ".", "join", "(", "filter", "(", "None", ",", "map", "(", "str", ",", "opts...
36.708333
0.002212
def delete(self, **kwargs): """Delete the list. :param kwargs: Extra request options :type kwargs: :class:`~python:dict` :return: Boolean to indicate if the request was successful :rtype: :class:`~python:bool` """ return self._client['users/*/lists/*'].delete(s...
[ "def", "delete", "(", "self", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_client", "[", "'users/*/lists/*'", "]", ".", "delete", "(", "self", ".", "username", ",", "self", ".", "id", ",", "*", "*", "kwargs", ")" ]
31.090909
0.008523
def cart_to_polar(arr_c): """Return cartesian vectors in their polar representation. Parameters ---------- arr_c: array, shape (a1, a2, ..., d) Cartesian vectors, with last axis indexing the dimension. Returns ------- arr_p: array, shape of arr_c Polar vectors, using (radiu...
[ "def", "cart_to_polar", "(", "arr_c", ")", ":", "if", "arr_c", ".", "shape", "[", "-", "1", "]", "==", "1", ":", "arr_p", "=", "arr_c", ".", "copy", "(", ")", "elif", "arr_c", ".", "shape", "[", "-", "1", "]", "==", "2", ":", "arr_p", "=", "n...
33.518519
0.001074
def download_member_shared(cls, member_data, target_member_dir, source=None, max_size=MAX_SIZE_DEFAULT, id_filename=False): """ Download files to sync a local dir to match OH member shared data. Files are downloaded to match their "basename" on Open Humans. ...
[ "def", "download_member_shared", "(", "cls", ",", "member_data", ",", "target_member_dir", ",", "source", "=", "None", ",", "max_size", "=", "MAX_SIZE_DEFAULT", ",", "id_filename", "=", "False", ")", ":", "logging", ".", "debug", "(", "'Download member shared data...
47.727273
0.0014
def iterate(self, train=None, valid=None, max_updates=None, **kwargs): r'''Optimize a loss iteratively using a training and validation dataset. This method yields a series of monitor values to the caller. After every optimization epoch, a pair of monitor dictionaries is generated: one e...
[ "def", "iterate", "(", "self", ",", "train", "=", "None", ",", "valid", "=", "None", ",", "max_updates", "=", "None", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_compile", "(", "*", "*", "kwargs", ")", "if", "valid", "is", "None", ":", "val...
41.145161
0.001914
def _min_fitting_element(self, lower_limit): """Returns the smallest element greater than or equal to the limit""" no_steps = -(-(lower_limit - self._start) // abs(self._step)) return self._start + abs(self._step) * no_steps
[ "def", "_min_fitting_element", "(", "self", ",", "lower_limit", ")", ":", "no_steps", "=", "-", "(", "-", "(", "lower_limit", "-", "self", ".", "_start", ")", "//", "abs", "(", "self", ".", "_step", ")", ")", "return", "self", ".", "_start", "+", "ab...
61.25
0.008065
def _extract_cookies(self, response: Response): '''Load the cookie headers from the Response.''' self._cookie_jar.extract_cookies( response, response.request, self._get_cookie_referrer_host() )
[ "def", "_extract_cookies", "(", "self", ",", "response", ":", "Response", ")", ":", "self", ".", "_cookie_jar", ".", "extract_cookies", "(", "response", ",", "response", ".", "request", ",", "self", ".", "_get_cookie_referrer_host", "(", ")", ")" ]
45
0.008734
def kmc(args): """ %prog kmc folder Run kmc3 on Illumina reads. """ p = OptionParser(kmc.__doc__) p.add_option("-k", default=21, type="int", help="Kmer size") p.add_option("--ci", default=2, type="int", help="Exclude kmers with less than ci counts") p.add_option("--cs",...
[ "def", "kmc", "(", "args", ")", ":", "p", "=", "OptionParser", "(", "kmc", ".", "__doc__", ")", "p", ".", "add_option", "(", "\"-k\"", ",", "default", "=", "21", ",", "type", "=", "\"int\"", ",", "help", "=", "\"Kmer size\"", ")", "p", ".", "add_op...
33.56
0.000579
def _check_table(self): """Ensure that an incorrect table doesn't exist If a bad (old) table does exist, return False """ cursor = self._db.execute("PRAGMA table_info(%s)"%self.table) lines = cursor.fetchall() if not lines: # table does not exist ...
[ "def", "_check_table", "(", "self", ")", ":", "cursor", "=", "self", ".", "_db", ".", "execute", "(", "\"PRAGMA table_info(%s)\"", "%", "self", ".", "table", ")", "lines", "=", "cursor", ".", "fetchall", "(", ")", "if", "not", "lines", ":", "# table does...
31.769231
0.008226
def main(): """ script to find a list of recipes for a group of people with specific likes and dislikes. Output of script best ingred = ['Tea', 'Tofu', 'Cheese', 'Cucumber', 'Salad', 'Chocolate'] worst ingred = ['Fish', 'Lamb', 'Pie', 'Asparagus', 'Chicken', 'Turnips'] ...
[ "def", "main", "(", ")", ":", "s", "=", "rawdata", ".", "content", ".", "DataFiles", "(", ")", "all_ingredients", "=", "list", "(", "s", ".", "get_collist_by_name", "(", "data_files", "[", "1", "]", "[", "'file'", "]", ",", "data_files", "[", "1", "]...
35
0.012746
def _values(self): """Getter for series values (flattened)""" return [ val for serie in self.series for val in serie.values if val is not None ]
[ "def", "_values", "(", "self", ")", ":", "return", "[", "val", "for", "serie", "in", "self", ".", "series", "for", "val", "in", "serie", ".", "values", "if", "val", "is", "not", "None", "]" ]
31.166667
0.010417
def get_object2(self, mpath, path=None, accept="*/*"): """A lower-level version of `get_object` that returns the response object (which includes the headers). ... @returns (res, content) {2-tuple} `content` is None if `path` was provided """ log.debug('GetObj...
[ "def", "get_object2", "(", "self", ",", "mpath", ",", "path", "=", "None", ",", "accept", "=", "\"*/*\"", ")", ":", "log", ".", "debug", "(", "'GetObject %r'", ",", "mpath", ")", "headers", "=", "{", "\"Accept\"", ":", "accept", "}", "res", ",", "con...
41.176471
0.001396
def decrypt(self, text, appid): """对解密后的明文进行补位删除 @param text: 密文 @return: 删除填充补位后的明文 """ try: cryptor = AES.new(self.key, self.mode, self.key[:16]) # 使用BASE64对密文进行解码,然后AES-CBC解密 plain_text = cryptor.decrypt(base64.b64decode(text)) exce...
[ "def", "decrypt", "(", "self", ",", "text", ",", "appid", ")", ":", "try", ":", "cryptor", "=", "AES", ".", "new", "(", "self", ".", "key", ",", "self", ".", "mode", ",", "self", ".", "key", "[", ":", "16", "]", ")", "# 使用BASE64对密文进行解码,然后AES-CBC解密"...
31.967742
0.001959
def handle_subports(self, subports, event_type): """Subport data model change from the server.""" LOG.debug("Subports event received: %(event_type)s. " "Subports: %(subports)s", {'event_type': event_type, 'subports': subports}) # update the cache. if...
[ "def", "handle_subports", "(", "self", ",", "subports", ",", "event_type", ")", ":", "LOG", ".", "debug", "(", "\"Subports event received: %(event_type)s. \"", "\"Subports: %(subports)s\"", ",", "{", "'event_type'", ":", "event_type", ",", "'subports'", ":", "subports...
40.48
0.001931
def convert_data_to_dtype(data, data_type, mot_float_type='float'): """Convert the given input data to the correct numpy type. Args: data (ndarray): The value to convert to the correct numpy type data_type (str): the data type we need to convert the data to mot_float_type (str): the dat...
[ "def", "convert_data_to_dtype", "(", "data", ",", "data_type", ",", "mot_float_type", "=", "'float'", ")", ":", "scalar_dtype", "=", "ctype_to_dtype", "(", "data_type", ",", "mot_float_type", ")", "if", "isinstance", "(", "data", ",", "numbers", ".", "Number", ...
39.5
0.001373
def retrieve(self,aclass): """Look for a specifc class/name in the packet""" resu=[] for x in self.payload: try: if isinstance(aclass,str): if x.name == aclass: resu.append(x) else: if isi...
[ "def", "retrieve", "(", "self", ",", "aclass", ")", ":", "resu", "=", "[", "]", "for", "x", "in", "self", ".", "payload", ":", "try", ":", "if", "isinstance", "(", "aclass", ",", "str", ")", ":", "if", "x", ".", "name", "==", "aclass", ":", "re...
29.0625
0.016667
def random_name_filepath(path_full, length_random=5): '''Take a filepath, add randome characters to its basename, and return the new filepath :param filename: either a filename or filepath :param length_random: length of random string to be generated ''' path_full_pre_extension, extension = os....
[ "def", "random_name_filepath", "(", "path_full", ",", "length_random", "=", "5", ")", ":", "path_full_pre_extension", ",", "extension", "=", "os", ".", "path", ".", "splitext", "(", "path_full", ")", "random_str", "=", "random_str_uuid", "(", "length_random", ")...
45.8
0.002141
def substr(self, startPos, length): """ Return a :class:`Column` which is a substring of the column. :param startPos: start position (int or Column) :param length: length of the substring (int or Column) >>> df.select(df.name.substr(1, 3).alias("col")).collect() [Row(c...
[ "def", "substr", "(", "self", ",", "startPos", ",", "length", ")", ":", "if", "type", "(", "startPos", ")", "!=", "type", "(", "length", ")", ":", "raise", "TypeError", "(", "\"startPos and length must be the same type. \"", "\"Got {startPos_t} and {length_t}, respe...
38.72
0.002016
def loopless_fva_iter(model, reaction, solution=False, zero_cutoff=None): """Plugin to get a loopless FVA solution from single FVA iteration. Assumes the following about `model` and `reaction`: 1. the model objective is set to be `reaction` 2. the model has been optimized and contains the minimum/maxim...
[ "def", "loopless_fva_iter", "(", "model", ",", "reaction", ",", "solution", "=", "False", ",", "zero_cutoff", "=", "None", ")", ":", "zero_cutoff", "=", "normalize_cutoff", "(", "model", ",", "zero_cutoff", ")", "current", "=", "model", ".", "objective", "."...
35.5
0.000351
def bind_tcp_socket(address): """Takes (host, port) and returns (socket_object, (host, port)). If the passed-in port is None, bind an unused port and return it. """ host, port = address for res in set(socket.getaddrinfo(host, port, socket.AF_INET, socket.SOCK_S...
[ "def", "bind_tcp_socket", "(", "address", ")", ":", "host", ",", "port", "=", "address", "for", "res", "in", "set", "(", "socket", ".", "getaddrinfo", "(", "host", ",", "port", ",", "socket", ".", "AF_INET", ",", "socket", ".", "SOCK_STREAM", ",", "0",...
36.909091
0.0012
def get_matrix_from_list(self, rows, columns, matrix_list, rowBased=True): """Create a new Matrix instance from a matrix_list. :note: This method is used to create a Matrix instance using cpython. :param integer rows: The height of the Matrix. :param integer columns: The widt...
[ "def", "get_matrix_from_list", "(", "self", ",", "rows", ",", "columns", ",", "matrix_list", ",", "rowBased", "=", "True", ")", ":", "resultMatrix", "=", "Matrix", "(", "columns", ",", "rows", ",", "matrix_list", ",", "rowBased", ")", "return", "resultMatrix...
58.882353
0.001967
def ProcessFileData(filename, file_extension, lines, error, extra_check_functions=None): """Performs lint checks and reports any errors to the given error function. Args: filename: Filename of the file that is being processed. file_extension: The extension (dot not included) of the file...
[ "def", "ProcessFileData", "(", "filename", ",", "file_extension", ",", "lines", ",", "error", ",", "extra_check_functions", "=", "None", ")", ":", "lines", "=", "(", "[", "'// marker so line numbers and indices both start at 1'", "]", "+", "lines", "+", "[", "'// ...
42.2
0.009727
def delete_bulk_device_enrollment(self, enrollment_identities, **kwargs): # noqa: E501 """Bulk delete # noqa: E501 With bulk delete, you can upload a `CSV` file containing a number of enrollment IDs to be deleted. **Example usage:** ``` curl -X POST \\ -H 'Authorization: Bearer <valid access token>'...
[ "def", "delete_bulk_device_enrollment", "(", "self", ",", "enrollment_identities", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'asynchronous'", ")", ":", "retur...
100.380952
0.00094
def setOverlayTextureColorSpace(self, ulOverlayHandle, eTextureColorSpace): """ Sets the colorspace the overlay texture's data is in. Defaults to 'auto'. If the texture needs to be resolved, you should call SetOverlayTexture with the appropriate colorspace instead. """ fn = sel...
[ "def", "setOverlayTextureColorSpace", "(", "self", ",", "ulOverlayHandle", ",", "eTextureColorSpace", ")", ":", "fn", "=", "self", ".", "function_table", ".", "setOverlayTextureColorSpace", "result", "=", "fn", "(", "ulOverlayHandle", ",", "eTextureColorSpace", ")", ...
48.333333
0.009029
def as_es2_command(command): """ Modify a desktop command so it works on es2. """ if command[0] == 'FUNC': return (command[0], re.sub(r'^gl([A-Z])', lambda m: m.group(1).lower(), command[1])) + command[2:] if command[0] == 'SHADERS': return command[:2] + convert_shaders(...
[ "def", "as_es2_command", "(", "command", ")", ":", "if", "command", "[", "0", "]", "==", "'FUNC'", ":", "return", "(", "command", "[", "0", "]", ",", "re", ".", "sub", "(", "r'^gl([A-Z])'", ",", "lambda", "m", ":", "m", ".", "group", "(", "1", ")...
36.083333
0.002252
def add_project(self, task, params={}, **options): """Adds the task to the specified project, in the optional location specified. If no location arguments are given, the task will be added to the end of the project. `addProject` can also be used to reorder a task within a proje...
[ "def", "add_project", "(", "self", ",", "task", ",", "params", "=", "{", "}", ",", "*", "*", "options", ")", ":", "path", "=", "\"/tasks/%s/addProject\"", "%", "(", "task", ")", "return", "self", ".", "client", ".", "post", "(", "path", ",", "params"...
50.433333
0.008431
def drain(self, tab_key): ''' Return all messages in waiting for the websocket connection. ''' self.log.debug("Draining transport") ret = [] while len(self.messages[tab_key]): ret.append(self.messages[tab_key].pop(0)) self.log.debug("Polling socket") tmp = self.___recv(tab_key) while tmp is not N...
[ "def", "drain", "(", "self", ",", "tab_key", ")", ":", "self", ".", "log", ".", "debug", "(", "\"Draining transport\"", ")", "ret", "=", "[", "]", "while", "len", "(", "self", ".", "messages", "[", "tab_key", "]", ")", ":", "ret", ".", "append", "(...
23.388889
0.03653
def list_build_set_records(id=None, name=None, page_size=200, page_index=0, sort="", q=""): """ List all build set records for a BuildConfigurationSet """ content = list_build_set_records_raw(id, name, page_size, page_index, sort, q) if content: return utils.format_json_list(content)
[ "def", "list_build_set_records", "(", "id", "=", "None", ",", "name", "=", "None", ",", "page_size", "=", "200", ",", "page_index", "=", "0", ",", "sort", "=", "\"\"", ",", "q", "=", "\"\"", ")", ":", "content", "=", "list_build_set_records_raw", "(", ...
43.714286
0.009615
def memoize(obj): """ Memoize objects to trade memory for execution speed Use a limited size cache to store the value, which takes into account The calling args and kwargs See https://wiki.python.org/moin/PythonDecoratorLibrary#Memoize """ cache = obj.cache = {} @functools....
[ "def", "memoize", "(", "obj", ")", ":", "cache", "=", "obj", ".", "cache", "=", "{", "}", "@", "functools", ".", "wraps", "(", "obj", ")", "def", "memoizer", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "key", "=", "str", "(", "args", ...
29.904762
0.001543
def basic_get(self, queue='', no_ack=False, ticket=None): """ direct access to a queue This method provides a direct access to the messages in a queue using a synchronous dialogue that is designed for specific types of application where synchronous functionality is more ...
[ "def", "basic_get", "(", "self", ",", "queue", "=", "''", ",", "no_ack", "=", "False", ",", "ticket", "=", "None", ")", ":", "args", "=", "AMQPWriter", "(", ")", "if", "ticket", "is", "not", "None", ":", "args", ".", "write_short", "(", "ticket", "...
36.655172
0.000916
def accumulate(self, buf): '''add in some more bytes''' accum = self.crc for b in buf: tmp = b ^ (accum & 0xff) tmp = (tmp ^ (tmp<<4)) & 0xFF accum = (accum>>8) ^ (tmp<<8) ^ (tmp<<3) ^ (tmp>>4) self.crc = accum
[ "def", "accumulate", "(", "self", ",", "buf", ")", ":", "accum", "=", "self", ".", "crc", "for", "b", "in", "buf", ":", "tmp", "=", "b", "^", "(", "accum", "&", "0xff", ")", "tmp", "=", "(", "tmp", "^", "(", "tmp", "<<", "4", ")", ")", "&",...
33.875
0.02518
def dir_df_boot(dir_df, nb=5000, par=False): """ Performs a bootstrap for direction DataFrame with optional parametric bootstrap Parameters _________ dir_df : Pandas DataFrame with columns: dir_dec : mean declination dir_inc : mean inclination Required for parametric bootstrap...
[ "def", "dir_df_boot", "(", "dir_df", ",", "nb", "=", "5000", ",", "par", "=", "False", ")", ":", "N", "=", "dir_df", ".", "dir_dec", ".", "values", ".", "shape", "[", "0", "]", "# number of data points", "BDIs", "=", "[", "]", "for", "k", "in", "ra...
42.090909
0.001583
def quasiparticle_weight(self): """Calculates quasiparticle weight""" return np.array([self.expected(op)**2 for op in self.oper['O']])
[ "def", "quasiparticle_weight", "(", "self", ")", ":", "return", "np", ".", "array", "(", "[", "self", ".", "expected", "(", "op", ")", "**", "2", "for", "op", "in", "self", ".", "oper", "[", "'O'", "]", "]", ")" ]
49.333333
0.013333
def Network_setBlockedURLs(self, urls): """ Function path: Network.setBlockedURLs Domain: Network Method name: setBlockedURLs WARNING: This function is marked 'Experimental'! Parameters: Required arguments: 'urls' (type: array) -> URL patterns to block. Wildcards ('*') are allowed. No ...
[ "def", "Network_setBlockedURLs", "(", "self", ",", "urls", ")", ":", "assert", "isinstance", "(", "urls", ",", "(", "list", ",", "tuple", ")", ")", ",", "\"Argument 'urls' must be of type '['list', 'tuple']'. Received type: '%s'\"", "%", "type", "(", "urls", ")", ...
30.5
0.046105
def run_agent(device_type): """Run a simple GPG-agent server.""" p = argparse.ArgumentParser() p.add_argument('--homedir', default=os.environ.get('GNUPGHOME')) p.add_argument('-v', '--verbose', default=0, action='count') p.add_argument('--server', default=False, action='store_true', ...
[ "def", "run_agent", "(", "device_type", ")", ":", "p", "=", "argparse", ".", "ArgumentParser", "(", ")", "p", ".", "add_argument", "(", "'--homedir'", ",", "default", "=", "os", ".", "environ", ".", "get", "(", "'GNUPGHOME'", ")", ")", "p", ".", "add_a...
44.345455
0.000401
def fulfill(self): """ Evaluate the promise and return the result. Returns: The result of the `Promise` (second return value from the `check_func`) Raises: BrokenPromise: the `Promise` was not satisfied within the time or attempt limits. """ is_...
[ "def", "fulfill", "(", "self", ")", ":", "is_fulfilled", ",", "result", "=", "self", ".", "_check_fulfilled", "(", ")", "if", "is_fulfilled", ":", "return", "result", "else", ":", "raise", "BrokenPromise", "(", "self", ")" ]
28.25
0.008565
def get(self, session, **kwargs): '''taobao.fenxiao.products.get 查询产品列表 查询供应商的产品数据 - 入参传入pids将优先查询,即只按这个条件查询。 - 入参传入sku_number将优先查询(没有传入pids),即只按这个条件查询(最多显示50条) - 入参fields传skus将查询sku的数据,不传该参数默认不查询,返回产品的其它信息。 - 入参fields传入images将查询多图数据,不传只返回主图数据。 - 入参fi...
[ "def", "get", "(", "self", ",", "session", ",", "*", "*", "kwargs", ")", ":", "request", "=", "TOPRequest", "(", "'taobao.fenxiao.products.get'", ")", "for", "k", ",", "v", "in", "kwargs", ".", "iteritems", "(", ")", ":", "if", "k", "not", "in", "(",...
48.25
0.01906
def intent_verified(hub, callback_url, mode, topic_url, lease_seconds): """ 5.3 Hub Verifies Intent of the Subscriber""" challenge = uuid4() params = { 'hub.mode': mode, 'hub.topic': topic_url, 'hub.challenge': challenge, 'hub.lease_seconds': lease_seconds, } try: ...
[ "def", "intent_verified", "(", "hub", ",", "callback_url", ",", "mode", ",", "topic_url", ",", "lease_seconds", ")", ":", "challenge", "=", "uuid4", "(", ")", "params", "=", "{", "'hub.mode'", ":", "mode", ",", "'hub.topic'", ":", "topic_url", ",", "'hub.c...
35.65
0.001366
def histogram(data, bins=None, binsize=1., min=None, max=None, rev=False, use_weave=True, verbose=0): """ Similar to IDL histogram. For reverse indices, the fast version uses weave from scipy. This is the default. If scipy is not available a slower version is used. """ if not have_s...
[ "def", "histogram", "(", "data", ",", "bins", "=", "None", ",", "binsize", "=", "1.", ",", "min", "=", "None", ",", "max", "=", "None", ",", "rev", "=", "False", ",", "use_weave", "=", "True", ",", "verbose", "=", "0", ")", ":", "if", "not", "h...
26.530303
0.009361
def search(cls, term, fields=()): """Generic SQL search function that uses SQL ``LIKE`` to search the database for matching records. The records are sorted by their relavancey to the search term. The query searches and sorts on the folling criteria, in order, where the target st...
[ "def", "search", "(", "cls", ",", "term", ",", "fields", "=", "(", ")", ")", ":", "if", "not", "any", "(", "(", "cls", ".", "_meta", ".", "search_fields", ",", "fields", ")", ")", ":", "raise", "AttributeError", "(", "\"A list of searchable fields must b...
37.345238
0.000621
def get_candidates(self, docs=None, split=0, sort=False): """Return a list of lists of the candidates associated with this extractor. Each list of the return will contain the candidates for one of the candidate classes associated with the CandidateExtractor. :param docs: If provided, r...
[ "def", "get_candidates", "(", "self", ",", "docs", "=", "None", ",", "split", "=", "0", ",", "sort", "=", "False", ")", ":", "result", "=", "[", "]", "if", "docs", ":", "docs", "=", "docs", "if", "isinstance", "(", "docs", ",", "(", "list", ",", ...
40.525424
0.002042
def logvalue(self, key, value): """Add log entry to request log info""" if not hasattr(self, 'logvalues'): self.logvalues = {} self.logvalues[key] = value
[ "def", "logvalue", "(", "self", ",", "key", ",", "value", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'logvalues'", ")", ":", "self", ".", "logvalues", "=", "{", "}", "self", ".", "logvalues", "[", "key", "]", "=", "value" ]
37.2
0.010526
def supported_types_for_region(region_code): """Returns the types for a given region which the library has metadata for. Will not include FIXED_LINE_OR_MOBILE (if numbers in this region could be classified as FIXED_LINE_OR_MOBILE, both FIXED_LINE and MOBILE would be present) and UNKNOWN. No types ...
[ "def", "supported_types_for_region", "(", "region_code", ")", ":", "if", "not", "_is_valid_region_code", "(", "region_code", ")", ":", "return", "set", "(", ")", "metadata", "=", "PhoneMetadata", ".", "metadata_for_region", "(", "region_code", ".", "upper", "(", ...
42.923077
0.001754
def parent(self): """ Parent of current object :rtype: Collection """ parent = list(self.graph.objects(self.asNode(), RDF_NAMESPACES.DTS.parent)) if parent: return self.parent_class(parent[0]) return None
[ "def", "parent", "(", "self", ")", ":", "parent", "=", "list", "(", "self", ".", "graph", ".", "objects", "(", "self", ".", "asNode", "(", ")", ",", "RDF_NAMESPACES", ".", "DTS", ".", "parent", ")", ")", "if", "parent", ":", "return", "self", ".", ...
28.555556
0.011321
def _fix_vi_cursor_position(self, event): """ After every command, make sure that if we are in Vi navigation mode, we never put the cursor after the last character of a line. (Unless it's an empty line.) """ cli = self._cli_ref() if cli: buff = cli.cur...
[ "def", "_fix_vi_cursor_position", "(", "self", ",", "event", ")", ":", "cli", "=", "self", ".", "_cli_ref", "(", ")", "if", "cli", ":", "buff", "=", "cli", ".", "current_buffer", "preferred_column", "=", "buff", ".", "preferred_column", "if", "(", "ViNavig...
41.210526
0.002497
def cpt2seg(file_name, sym=False, discrete=False): """Reads a .cpt palette and returns a segmented colormap. sym : If True, the returned colormap contains the palette and a mirrored copy. For example, a blue-red-green palette would return a blue-red-green-green-red-blue colormap. discrete : If t...
[ "def", "cpt2seg", "(", "file_name", ",", "sym", "=", "False", ",", "discrete", "=", "False", ")", ":", "dic", "=", "{", "}", "# io\r", "# f = scipy.io.open(file_name, 'r')\r", "# rgb = f.read_array(f)\r", "#Check flags:\r", "# with open(file_name) as f:\r", ...
34.196721
0.014911
def moderate_view(self, request, object_id, extra_context=None): """ Handles moderate object tool through a somewhat hacky changelist view whose queryset is altered via CommentAdmin.get_changelist to only list comments for the object under review. """ opts = self.model._m...
[ "def", "moderate_view", "(", "self", ",", "request", ",", "object_id", ",", "extra_context", "=", "None", ")", ":", "opts", "=", "self", ".", "model", ".", "_meta", "app_label", "=", "opts", ".", "app_label", "view", "=", "CommentAdmin", "(", "model", "=...
36.333333
0.002234
def randomized_pca(gn, n_components=10, copy=True, iterated_power=3, random_state=None, scaler='patterson', ploidy=2): """Perform principal components analysis of genotype data, via an approximate truncated singular value decomposition using randomization to speed up the computation. ...
[ "def", "randomized_pca", "(", "gn", ",", "n_components", "=", "10", ",", "copy", "=", "True", ",", "iterated_power", "=", "3", ",", "random_state", "=", "None", ",", "scaler", "=", "'patterson'", ",", "ploidy", "=", "2", ")", ":", "# set up the model", "...
36.83871
0.000426
def _create_B(self,Y): """ Creates OLS coefficient matrix Parameters ---------- Y : np.array The dependent variables Y Returns ---------- The coefficient matrix B """ Z = self._create_Z(Y) return np.dot(np.dot(Y,np.t...
[ "def", "_create_B", "(", "self", ",", "Y", ")", ":", "Z", "=", "self", ".", "_create_Z", "(", "Y", ")", "return", "np", ".", "dot", "(", "np", ".", "dot", "(", "Y", ",", "np", ".", "transpose", "(", "Z", ")", ")", ",", "np", ".", "linalg", ...
24
0.02139
def browseMaps( self ): """ Brings up a web browser with the address in a Google map. """ url = self.urlTemplate() params = urllib.urlencode({self.urlQueryKey(): self.location()}) url = url % {'params': params} webbrowser.open(url)
[ "def", "browseMaps", "(", "self", ")", ":", "url", "=", "self", ".", "urlTemplate", "(", ")", "params", "=", "urllib", ".", "urlencode", "(", "{", "self", ".", "urlQueryKey", "(", ")", ":", "self", ".", "location", "(", ")", "}", ")", "url", "=", ...
33.555556
0.022581
def enable_refresh(index_name): ''' Enable refresh and force merge. To be used after indexing. See: https://www.elastic.co/guide/en/elasticsearch/reference/master/indices-update-settings.html#bulk ''' # noqa refresh_interval = current_app.config['ELASTICSEARCH_REFRESH_INTERVAL'] es.indices.put...
[ "def", "enable_refresh", "(", "index_name", ")", ":", "# noqa", "refresh_interval", "=", "current_app", ".", "config", "[", "'ELASTICSEARCH_REFRESH_INTERVAL'", "]", "es", ".", "indices", ".", "put_settings", "(", "index", "=", "index_name", ",", "body", "=", "{"...
42.818182
0.002079
def credit_card_account_query(self, number, date): """CC Statement request""" return self.authenticated_query(self._ccreq(number, date))
[ "def", "credit_card_account_query", "(", "self", ",", "number", ",", "date", ")", ":", "return", "self", ".", "authenticated_query", "(", "self", ".", "_ccreq", "(", "number", ",", "date", ")", ")" ]
50
0.013158
def get_instance( model, method="file", img_dir=None, data_dir=None, bucket=None ): """Return an instance of ConsumeStore.""" global _instances if not isinstance(model, ConsumeModel): raise TypeError( "get_instance() expects a parker.ConsumeModel derivative." ) i...
[ "def", "get_instance", "(", "model", ",", "method", "=", "\"file\"", ",", "img_dir", "=", "None", ",", "data_dir", "=", "None", ",", "bucket", "=", "None", ")", ":", "global", "_instances", "if", "not", "isinstance", "(", "model", ",", "ConsumeModel", ")...
25.242424
0.001156
def updateFinancialItems(): ''' Every hour, create any necessary revenue items and expense items for activities that need them. ''' if not getConstant('general__enableCronTasks'): return logger.info('Creating automatically-generated financial items.') if getConstant('financial__aut...
[ "def", "updateFinancialItems", "(", ")", ":", "if", "not", "getConstant", "(", "'general__enableCronTasks'", ")", ":", "return", "logger", ".", "info", "(", "'Creating automatically-generated financial items.'", ")", "if", "getConstant", "(", "'financial__autoGenerateExpe...
37.125
0.001642
def _viewport_default(self): """ Trait initialiser """ viewport = Viewport(component=self.canvas, enable_zoom=True) viewport.tools.append(ViewportPanTool(viewport)) return viewport
[ "def", "_viewport_default", "(", "self", ")", ":", "viewport", "=", "Viewport", "(", "component", "=", "self", ".", "canvas", ",", "enable_zoom", "=", "True", ")", "viewport", ".", "tools", ".", "append", "(", "ViewportPanTool", "(", "viewport", ")", ")", ...
34.666667
0.00939
def add(parent, idx, value): """Add a value to a dict.""" if isinstance(parent, dict): if idx in parent: raise JSONPatchError("Item already exists") parent[idx] = value elif isinstance(parent, list): if idx == "" or idx == "~": parent.append(value) else: parent.insert(int(idx), v...
[ "def", "add", "(", "parent", ",", "idx", ",", "value", ")", ":", "if", "isinstance", "(", "parent", ",", "dict", ")", ":", "if", "idx", "in", "parent", ":", "raise", "JSONPatchError", "(", "\"Item already exists\"", ")", "parent", "[", "idx", "]", "=",...
28.846154
0.020672
def get_assessments_taken_by_ids(self, assessment_taken_ids): """Gets an ``AssessmentTakenList`` corresponding to the given ``IdList``. In plenary mode, the returned list contains all of the assessments specified in the ``Id`` list, in the order of the list, including duplicates, or an ...
[ "def", "get_assessments_taken_by_ids", "(", "self", ",", "assessment_taken_ids", ")", ":", "# Implemented from template for", "# osid.resource.ResourceLookupSession.get_resources_by_ids", "# NOTE: This implementation currently ignores plenary view", "collection", "=", "JSONClientValidated"...
49.738095
0.002347
def ServiceWorker_unregister(self, scopeURL): """ Function path: ServiceWorker.unregister Domain: ServiceWorker Method name: unregister Parameters: Required arguments: 'scopeURL' (type: string) -> No description No return value. """ assert isinstance(scopeURL, (str,) ), "Argumen...
[ "def", "ServiceWorker_unregister", "(", "self", ",", "scopeURL", ")", ":", "assert", "isinstance", "(", "scopeURL", ",", "(", "str", ",", ")", ")", ",", "\"Argument 'scopeURL' must be of type '['str']'. Received type: '%s'\"", "%", "type", "(", "scopeURL", ")", "sub...
28
0.051823
def vectors(self): """ :rtype: dict """ vectors = {} for anopheles in self.et.findall("anopheles"): vectors[anopheles.attrib["mosquito"]] = Vector(anopheles) return vectors
[ "def", "vectors", "(", "self", ")", ":", "vectors", "=", "{", "}", "for", "anopheles", "in", "self", ".", "et", ".", "findall", "(", "\"anopheles\"", ")", ":", "vectors", "[", "anopheles", ".", "attrib", "[", "\"mosquito\"", "]", "]", "=", "Vector", ...
28.125
0.008621
def _get_seal_key_ntlm1(negotiate_flags, exported_session_key): """ 3.4.5.3 SEALKEY Calculates the seal_key used to seal (encrypt) messages. This for authentication where NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY has not been negotiated. Will weaken the keys if NTLMSSP_NEGOTIATE_56 is not negot...
[ "def", "_get_seal_key_ntlm1", "(", "negotiate_flags", ",", "exported_session_key", ")", ":", "if", "negotiate_flags", "&", "NegotiateFlags", ".", "NTLMSSP_NEGOTIATE_56", ":", "seal_key", "=", "exported_session_key", "[", ":", "7", "]", "+", "b\"\\xa0\"", "else", ":"...
41.421053
0.001242
def read_python_code(filename): "Returns the given Python source file's compiled content." file = open(filename, "rt") try: source = file.read() finally: file.close() # Python 2.6 and below did not support passing strings to exec() & # compile() functions containing line separato...
[ "def", "read_python_code", "(", "filename", ")", ":", "file", "=", "open", "(", "filename", ",", "\"rt\"", ")", "try", ":", "source", "=", "file", ".", "read", "(", ")", "finally", ":", "file", ".", "close", "(", ")", "# Python 2.6 and below did not suppor...
43.571429
0.001605
def finish (self): """Wait for checker threads to finish.""" if not self.urlqueue.empty(): # This happens when all checker threads died. self.cancel() for t in self.threads: t.stop()
[ "def", "finish", "(", "self", ")", ":", "if", "not", "self", ".", "urlqueue", ".", "empty", "(", ")", ":", "# This happens when all checker threads died.", "self", ".", "cancel", "(", ")", "for", "t", "in", "self", ".", "threads", ":", "t", ".", "stop", ...
33.714286
0.012397
def compress_file(inputfile, filename): """ Compress input file using gzip and change its name. :param inputfile: File to compress :type inputfile: ``file`` like object :param filename: File's name :type filename: ``str`` :returns: Tuple with compressed file and new file's name :rtype...
[ "def", "compress_file", "(", "inputfile", ",", "filename", ")", ":", "outputfile", "=", "create_spooled_temporary_file", "(", ")", "new_filename", "=", "filename", "+", "'.gz'", "zipfile", "=", "gzip", ".", "GzipFile", "(", "filename", "=", "filename", ",", "f...
31.636364
0.001395
def write_string(self, value): """ Write the specified unicode string to the display. To control multiline behavior, use newline (``\\n``) and carriage return (``\\r``) characters. Lines that are too long automatically continue on next line, as long as ``auto_linebreaks...
[ "def", "write_string", "(", "self", ",", "value", ")", ":", "encoded", "=", "self", ".", "codec", ".", "encode", "(", "value", ")", "# type: List[int]", "ignored", "=", "False", "for", "[", "char", ",", "lookahead", "]", "in", "c", ".", "sliding_window",...
37.4375
0.000813
def get_metadata(realizations, kind): """ :param list realizations: realization objects :param str kind: kind of data, i.e. a key in the datastore :returns: a dictionary with smlt_path, gsimlt_path, statistics, quantile_value """ metadata = {} if kind.startswith('rlz-...
[ "def", "get_metadata", "(", "realizations", ",", "kind", ")", ":", "metadata", "=", "{", "}", "if", "kind", ".", "startswith", "(", "'rlz-'", ")", ":", "rlz", "=", "realizations", "[", "int", "(", "kind", "[", "4", ":", "]", ")", "]", "metadata", "...
33.208333
0.00122
def path_wrapper(func): """return the given infer function wrapped to handle the path Used to stop inference if the node has already been looked at for a given `InferenceContext` to prevent infinite recursion """ @functools.wraps(func) def wrapped(node, context=None, _func=func, **kwargs): ...
[ "def", "path_wrapper", "(", "func", ")", ":", "@", "functools", ".", "wraps", "(", "func", ")", "def", "wrapped", "(", "node", ",", "context", "=", "None", ",", "_func", "=", "func", ",", "*", "*", "kwargs", ")", ":", "\"\"\"wrapper function handling con...
32.176471
0.000887
def persistentValues(self): """ Return a dictionary of all attributes which will be/have been/are being stored in the database. """ return dict((k, getattr(self, k)) for (k, attr) in self.getSchema())
[ "def", "persistentValues", "(", "self", ")", ":", "return", "dict", "(", "(", "k", ",", "getattr", "(", "self", ",", "k", ")", ")", "for", "(", "k", ",", "attr", ")", "in", "self", ".", "getSchema", "(", ")", ")" ]
39.166667
0.008333
def _apply_policy_config(policy_spec, policy_dict): '''Applies a policy dictionary to a policy spec''' log.trace('policy_dict = %s', policy_dict) if policy_dict.get('name'): policy_spec.name = policy_dict['name'] if policy_dict.get('description'): policy_spec.description = policy_dict['d...
[ "def", "_apply_policy_config", "(", "policy_spec", ",", "policy_dict", ")", ":", "log", ".", "trace", "(", "'policy_dict = %s'", ",", "policy_dict", ")", "if", "policy_dict", ".", "get", "(", "'name'", ")", ":", "policy_spec", ".", "name", "=", "policy_dict", ...
53.638298
0.00039
def get_definition(self): """ Get the dict with the basic fields used to describe a metrics: id, name and desc :return: a dict with the definition """ def_ = { "id": self.id, "name": self.name, "desc": self.desc } return def_
[ "def", "get_definition", "(", "self", ")", ":", "def_", "=", "{", "\"id\"", ":", "self", ".", "id", ",", "\"name\"", ":", "self", ".", "name", ",", "\"desc\"", ":", "self", ".", "desc", "}", "return", "def_" ]
27.909091
0.009464
def get_objectives_by_ids(self, objective_ids=None): """Gets an ObjectiveList corresponding to the given IdList. In plenary mode, the returned list contains all of the objectives specified in the Id list, in the order of the list, including duplicates, or an error results if an Id in the...
[ "def", "get_objectives_by_ids", "(", "self", ",", "objective_ids", "=", "None", ")", ":", "if", "objective_ids", "is", "None", ":", "raise", "NullArgument", "(", ")", "url_path", "=", "construct_url", "(", "'objectives_by_ids'", ",", "obj_ids", "=", "objective_i...
43.55814
0.001044
def safe_load_sensors(self): """Load sensors safely from file.""" try: loaded = self._load_sensors() except (EOFError, ValueError): _LOGGER.error('Bad file contents: %s', self.persistence_file) loaded = False if not loaded: _LOGGER.warning(...
[ "def", "safe_load_sensors", "(", "self", ")", ":", "try", ":", "loaded", "=", "self", ".", "_load_sensors", "(", ")", "except", "(", "EOFError", ",", "ValueError", ")", ":", "_LOGGER", ".", "error", "(", "'Bad file contents: %s'", ",", "self", ".", "persis...
47.882353
0.00241
def deblock(f): """Decompress a single block from a compressed Plan 9 image file. Each block starts with 2 decimal strings of 12 bytes each. Yields a sequence of (row, data) pairs where row is the total number of rows processed according to the file format and data is the decompressed data for a se...
[ "def", "deblock", "(", "f", ")", ":", "row", "=", "int", "(", "f", ".", "read", "(", "12", ")", ")", "size", "=", "int", "(", "f", ".", "read", "(", "12", ")", ")", "if", "not", "(", "0", "<=", "size", "<=", "6000", ")", ":", "raise", "Er...
37.708333
0.000539
def kill_all(job_queue, reason='None given', states=None): """Terminates/cancels all RUNNING, RUNNABLE, and STARTING jobs.""" if states is None: states = ['STARTING', 'RUNNABLE', 'RUNNING'] batch = boto3.client('batch') runnable = batch.list_jobs(jobQueue=job_queue, jobStatus='RUNNABLE') job...
[ "def", "kill_all", "(", "job_queue", ",", "reason", "=", "'None given'", ",", "states", "=", "None", ")", ":", "if", "states", "is", "None", ":", "states", "=", "[", "'STARTING'", ",", "'RUNNABLE'", ",", "'RUNNING'", "]", "batch", "=", "boto3", ".", "c...
42.347826
0.001004
def proc_info(pid, attrs=None): ''' Return a dictionary of information for a process id (PID). CLI Example: .. code-block:: bash salt '*' ps.proc_info 2322 salt '*' ps.proc_info 2322 attrs='["pid", "name"]' pid PID of process to query. attrs Optional list of ...
[ "def", "proc_info", "(", "pid", ",", "attrs", "=", "None", ")", ":", "try", ":", "proc", "=", "psutil", ".", "Process", "(", "pid", ")", "return", "proc", ".", "as_dict", "(", "attrs", ")", "except", "(", "psutil", ".", "NoSuchProcess", ",", "psutil"...
26.916667
0.001495
def image_summary(seqs, name, num=None): """Visualizes sequences as TensorBoard summaries. Args: seqs: A tensor of shape [n, t, h, w, c]. name: String name of this summary. num: Integer for the number of examples to visualize. Defaults to all examples. """ seqs = tf.clip_by_value(seqs, 0., 1....
[ "def", "image_summary", "(", "seqs", ",", "name", ",", "num", "=", "None", ")", ":", "seqs", "=", "tf", ".", "clip_by_value", "(", "seqs", ",", "0.", ",", "1.", ")", "seqs", "=", "tf", ".", "unstack", "(", "seqs", "[", ":", "num", "]", ")", "jo...
33.444444
0.011309
def resolve_fragment(self, document, fragment): """ Resolve a ``fragment`` within the referenced ``document``. :argument document: the referrant document :argument str fragment: a URI fragment to resolve within it """ fragment = fragment.lstrip(u"/") parts = un...
[ "def", "resolve_fragment", "(", "self", ",", "document", ",", "fragment", ")", ":", "fragment", "=", "fragment", ".", "lstrip", "(", "u\"/\"", ")", "parts", "=", "unquote", "(", "fragment", ")", ".", "split", "(", "u\"/\"", ")", "if", "fragment", "else",...
31.517241
0.002123
def getAllSensors(self): """ Retrieve all the user's own sensors by iterating over the SensorsGet function @return (list) - Array of sensors """ j = 0 sensors = [] parameters = {'page':0, 'per_page':1000, 'owned':1} while True...
[ "def", "getAllSensors", "(", "self", ")", ":", "j", "=", "0", "sensors", "=", "[", "]", "parameters", "=", "{", "'page'", ":", "0", ",", "'per_page'", ":", "1000", ",", "'owned'", ":", "1", "}", "while", "True", ":", "parameters", "[", "'page'", "]...
30.666667
0.01054
def aead_filename(aead_dir, key_handle, public_id): """ Return the filename of the AEAD for this public_id. """ parts = [aead_dir, key_handle] + pyhsm.util.group(public_id, 2) + [public_id] return os.path.join(*parts)
[ "def", "aead_filename", "(", "aead_dir", ",", "key_handle", ",", "public_id", ")", ":", "parts", "=", "[", "aead_dir", ",", "key_handle", "]", "+", "pyhsm", ".", "util", ".", "group", "(", "public_id", ",", "2", ")", "+", "[", "public_id", "]", "return...
38.666667
0.008439
def generic_loss(top_out, targets, model_hparams, vocab_size, weights_fn): """Compute loss numerator and denominator for one shard of output.""" del vocab_size # unused arg logits = top_out logits = common_attention.maybe_upcast(logits, hparams=model_hparams) cutoff = getattr(model_hparams, "video_modality_l...
[ "def", "generic_loss", "(", "top_out", ",", "targets", ",", "model_hparams", ",", "vocab_size", ",", "weights_fn", ")", ":", "del", "vocab_size", "# unused arg", "logits", "=", "top_out", "logits", "=", "common_attention", ".", "maybe_upcast", "(", "logits", ","...
40.583333
0.014056
def remove_pattern(root, pat, verbose=True): """ Given a directory, and a pattern of files like "garbage.txt" or "*pyc" inside it, remove them. Try not to delete the whole OS while you're at it. """ print("removing pattern", root, pat) combined = root + pat print('combined', combined) ...
[ "def", "remove_pattern", "(", "root", ",", "pat", ",", "verbose", "=", "True", ")", ":", "print", "(", "\"removing pattern\"", ",", "root", ",", "pat", ")", "combined", "=", "root", "+", "pat", "print", "(", "'combined'", ",", "combined", ")", "items", ...
31.555556
0.001709
def _normalize_select(self, query): """ If the query contains the :select operator, we enforce :sys properties. The SDK requires sys.type to function properly, but as other of our SDKs require more parts of the :sys properties, we decided that every SDK should include the complet...
[ "def", "_normalize_select", "(", "self", ",", "query", ")", ":", "if", "'select'", "not", "in", "query", ":", "return", "if", "isinstance", "(", "query", "[", "'select'", "]", ",", "string_class", "(", ")", ")", ":", "query", "[", "'select'", "]", "=",...
35.434783
0.002389
def solve_gcp(V,E): """solve_gcp -- solve the graph coloring problem with bisection and fixed-k model Parameters: - V: set/list of nodes in the graph - E: set/list of edges in the graph Returns tuple with number of colors used, and dictionary mapping colors to vertices """ LB = 0 ...
[ "def", "solve_gcp", "(", "V", ",", "E", ")", ":", "LB", "=", "0", "UB", "=", "len", "(", "V", ")", "color", "=", "{", "}", "while", "UB", "-", "LB", ">", "1", ":", "K", "=", "int", "(", "(", "UB", "+", "LB", ")", "/", "2", ")", "gcp", ...
29.6875
0.010194
def l2(Ks, dim, X_rhos, Y_rhos, required, clamp=True, to_self=False): r''' Estimates the L2 distance between distributions, via \int (p - q)^2 = \int p^2 - \int p q - \int q p + \int q^2. \int pq and \int qp are estimated with the linear function (in both directions), while \int p^2 and \int q^...
[ "def", "l2", "(", "Ks", ",", "dim", ",", "X_rhos", ",", "Y_rhos", ",", "required", ",", "clamp", "=", "True", ",", "to_self", "=", "False", ")", ":", "n_X", "=", "len", "(", "X_rhos", ")", "n_Y", "=", "len", "(", "Y_rhos", ")", "linears", "=", ...
32.972222
0.000818
def transition_to_rollback_complete(self): """Transition to rollback complete""" assert self.state in [AQStateMachineStates.rollback] self.state = AQStateMachineStates.rollback_complate
[ "def", "transition_to_rollback_complete", "(", "self", ")", ":", "assert", "self", ".", "state", "in", "[", "AQStateMachineStates", ".", "rollback", "]", "self", ".", "state", "=", "AQStateMachineStates", ".", "rollback_complate" ]
51.5
0.009569
def setArticleThreshold(self, value): """ what is the minimum total weight that an article has to have in order to get it among the results? @param value: threshold to use """ assert isinstance(value, int) assert value >= 0 self.topicPage["articleTreshWgt"] = valu...
[ "def", "setArticleThreshold", "(", "self", ",", "value", ")", ":", "assert", "isinstance", "(", "value", ",", "int", ")", "assert", "value", ">=", "0", "self", ".", "topicPage", "[", "\"articleTreshWgt\"", "]", "=", "value" ]
39.25
0.009346
def add_relations(self, relations): """Add multiple relations to a bijection""" for source, destination in relations: self.add_relation(source, destination)
[ "def", "add_relations", "(", "self", ",", "relations", ")", ":", "for", "source", ",", "destination", "in", "relations", ":", "self", ".", "add_relation", "(", "source", ",", "destination", ")" ]
45.25
0.01087
def _parse_standard_flag(read_buffer, mask_length): """Construct standard flag, standard mask data from the file. Specifically working on Reader Requirements box. Parameters ---------- fptr : file object File object for JP2K file. mask_length : int Length of standard mask flag ...
[ "def", "_parse_standard_flag", "(", "read_buffer", ",", "mask_length", ")", ":", "# The mask length tells us the format string to use when unpacking", "# from the buffer read from file.", "mask_format", "=", "{", "1", ":", "'B'", ",", "2", ":", "'H'", ",", "4", ":", "'I...
34.892857
0.000996
def flip_labels(obj): """ Rename fields x to y and y to x Parameters ---------- obj : dict_like Object with labels to rename """ def sub(a, b): """ Substitute all keys that start with a to b """ for label in list(obj.keys()): if label.star...
[ "def", "flip_labels", "(", "obj", ")", ":", "def", "sub", "(", "a", ",", "b", ")", ":", "\"\"\"\n Substitute all keys that start with a to b\n \"\"\"", "for", "label", "in", "list", "(", "obj", ".", "keys", "(", ")", ")", ":", "if", "label", "....
21.227273
0.002049
def prepare_headers(self, headers, metadata, queue_derive=True): """Convert a dictionary of metadata into S3 compatible HTTP headers, and append headers to ``headers``. :type metadata: dict :param metadata: Metadata to be converted into S3 HTTP Headers and appen...
[ "def", "prepare_headers", "(", "self", ",", "headers", ",", "metadata", ",", "queue_derive", "=", "True", ")", ":", "if", "not", "metadata", ".", "get", "(", "'scanner'", ")", ":", "scanner", "=", "'Internet Archive Python library {0}'", ".", "format", "(", ...
46.755102
0.001283
def _add_to_filemenu(): """Helper function for the above :func:add_to_filemenu() This function is serialised into a string and passed on to evalDeferred above. """ import os import pyblish from maya import cmds # This must be duplicated here, due to this function # not being avai...
[ "def", "_add_to_filemenu", "(", ")", ":", "import", "os", "import", "pyblish", "from", "maya", "import", "cmds", "# This must be duplicated here, due to this function", "# not being available through the above `evalDeferred`", "for", "item", "in", "(", "\"pyblishOpeningDivider\...
31.307692
0.000794
def post_transport_log(self, call): """Prints the result "Returned Data: \n%s" % (call.result)of an API call""" output = "Returned Data: \n{}".format(call.result) LOGGER.debug(output)
[ "def", "post_transport_log", "(", "self", ",", "call", ")", ":", "output", "=", "\"Returned Data: \\n{}\"", ".", "format", "(", "call", ".", "result", ")", "LOGGER", ".", "debug", "(", "output", ")" ]
51
0.014493
def node_to_point_geometry(node): """ Reads the node and returns the point geometry, upper depth and lower depth """ assert "pointGeometry" in node.tag for subnode in node.nodes: if "Point" in subnode.tag: # Position lon, lat = map(float, subnode.nodes[0].text.split()...
[ "def", "node_to_point_geometry", "(", "node", ")", ":", "assert", "\"pointGeometry\"", "in", "node", ".", "tag", "for", "subnode", "in", "node", ".", "nodes", ":", "if", "\"Point\"", "in", "subnode", ".", "tag", ":", "# Position", "lon", ",", "lat", "=", ...
34.947368
0.001466