text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def to_string(self, value): """String gets serialized and deserialized without quote marks.""" if isinstance(value, six.binary_type): value = value.decode('utf-8') return self.to_json(value)
[ "def", "to_string", "(", "self", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "six", ".", "binary_type", ")", ":", "value", "=", "value", ".", "decode", "(", "'utf-8'", ")", "return", "self", ".", "to_json", "(", "value", ")" ]
44.4
0.00885
def formatex(ex, msg='[!?] Caught exception', prefix=None, key_list=[], locals_=None, iswarning=False, tb=False, N=0, keys=None, colored=None): r""" Formats an exception with relevant info Args: ex (Exception): exception to print msg (unicode): a message to displa...
[ "def", "formatex", "(", "ex", ",", "msg", "=", "'[!?] Caught exception'", ",", "prefix", "=", "None", ",", "key_list", "=", "[", "]", ",", "locals_", "=", "None", ",", "iswarning", "=", "False", ",", "tb", "=", "False", ",", "N", "=", "0", ",", "ke...
39.580247
0.001522
def adsorb_both_surfaces(self, molecule, repeat=None, min_lw=5.0, reorient=True, find_args={}): """ Function that generates all adsorption structures for a given molecular adsorbate on both surfaces of a slab. This is useful for calculating surface energy whe...
[ "def", "adsorb_both_surfaces", "(", "self", ",", "molecule", ",", "repeat", "=", "None", ",", "min_lw", "=", "5.0", ",", "reorient", "=", "True", ",", "find_args", "=", "{", "}", ")", ":", "# Get the adsorbed surfaces first", "adslabs", "=", "self", ".", "...
46.470588
0.00124
def non_fluents_scope(self) -> Dict[str, TensorFluent]: '''Returns a partial scope with non-fluents. Returns: A mapping from non-fluent names to :obj:`rddl2tf.fluent.TensorFluent`. ''' if self.__dict__.get('non_fluents') is None: self._initialize_non_fluents() ...
[ "def", "non_fluents_scope", "(", "self", ")", "->", "Dict", "[", "str", ",", "TensorFluent", "]", ":", "if", "self", ".", "__dict__", ".", "get", "(", "'non_fluents'", ")", "is", "None", ":", "self", ".", "_initialize_non_fluents", "(", ")", "return", "d...
38.555556
0.008451
def wait_to_end(self, pids=[]): ''' wait_to_end(self, pids=[]) Wait for processes to finish :Parameters: * *pids* (`list`) -- list of processes to wait to finish ''' actual_pids = self._get_pids(pids) return self.wait_for(pids=actual_pids, status_list=p...
[ "def", "wait_to_end", "(", "self", ",", "pids", "=", "[", "]", ")", ":", "actual_pids", "=", "self", ".", "_get_pids", "(", "pids", ")", "return", "self", ".", "wait_for", "(", "pids", "=", "actual_pids", ",", "status_list", "=", "process_result_statuses",...
27.666667
0.008746
def _build_cache(): """Preprocess collection queries.""" query = current_app.config['COLLECTIONS_DELETED_RECORDS'] for collection in Collection.query.filter( Collection.dbquery.isnot(None)).all(): yield collection.name, dict( query=query.format(dbquery=collection.dbquery), ...
[ "def", "_build_cache", "(", ")", ":", "query", "=", "current_app", ".", "config", "[", "'COLLECTIONS_DELETED_RECORDS'", "]", "for", "collection", "in", "Collection", ".", "query", ".", "filter", "(", "Collection", ".", "dbquery", ".", "isnot", "(", "None", "...
39.3
0.002488
def from_bytes(cls, bitstream, decode_payload=True): r''' Parse the given packet and update properties accordingly >>> data_hex = ('c033d3c10000000745c0005835400000' ... 'ff06094a254d38204d45d1a30016f597' ... 'a1c3c7406718bf1b50180ff0793f0000' ......
[ "def", "from_bytes", "(", "cls", ",", "bitstream", ",", "decode_payload", "=", "True", ")", ":", "packet", "=", "cls", "(", ")", "# Convert to ConstBitStream (if not already provided)", "if", "not", "isinstance", "(", "bitstream", ",", "ConstBitStream", ")", ":", ...
34.078431
0.001118
def process(self, request, response, environ): """ Create a new access token. :param request: The incoming :class:`oauth2.web.Request`. :param response: The :class:`oauth2.web.Response` that will be returned to the client. :param environ: A ``dict`` cont...
[ "def", "process", "(", "self", ",", "request", ",", "response", ",", "environ", ")", ":", "token_data", "=", "self", ".", "token_generator", ".", "create_access_token_data", "(", "self", ".", "refresh_grant_type", ")", "expires_at", "=", "int", "(", "time", ...
42.972222
0.001896
def solve(self,b,overwrite_b=False,check_finite=True, p=None): """ solve A \ b """ if p is None: assert b.shape[:2]==(len(self.solver),self.dof_any) solution = np.empty(b.shape) #This is trivially parallelizable: for p in range(self.P): ...
[ "def", "solve", "(", "self", ",", "b", ",", "overwrite_b", "=", "False", ",", "check_finite", "=", "True", ",", "p", "=", "None", ")", ":", "if", "p", "is", "None", ":", "assert", "b", ".", "shape", "[", ":", "2", "]", "==", "(", "len", "(", ...
34.615385
0.019481
def add_command_option(command, name, doc, is_bool=False): """ Add a custom option to a setup command. Issues a warning if the option already exists on that command. Parameters ---------- command : str The name of the command as given on the command line name : str The nam...
[ "def", "add_command_option", "(", "command", ",", "name", ",", "doc", ",", "is_bool", "=", "False", ")", ":", "dist", "=", "get_dummy_distribution", "(", ")", "cmdcls", "=", "dist", ".", "get_command_class", "(", "command", ")", "if", "(", "hasattr", "(", ...
33.15873
0.000465
def do_cprofile(func): """ Decorator to profile a function It gives good numbers on various function calls but it omits a vital piece of information: what is it about a function that makes it so slow? However, it is a great start to basic profiling. Sometimes it can even point you to the solut...
[ "def", "do_cprofile", "(", "func", ")", ":", "def", "profiled_func", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "profile", "=", "cProfile", ".", "Profile", "(", ")", "try", ":", "profile", ".", "enable", "(", ")", "result", "=", "func", "...
31.911765
0.000894
def get(self, block=True, timeout=None): """Remove and return an item from the queue. If optional args ``block`` is ``True`` and ``timeout`` is ``None`` (the default), block if necessary until an item is available. If ``timeout`` is a positive number, it blocks at most ``timeou...
[ "def", "get", "(", "self", ",", "block", "=", "True", ",", "timeout", "=", "None", ")", ":", "if", "not", "block", ":", "return", "self", ".", "get_nowait", "(", ")", "item", "=", "self", ".", "_bpop", "(", "[", "self", ".", "name", "]", ",", "...
42.105263
0.002445
def find_files(directory=".", ext=None, name=None, match_case=False, disable_glob=False, depth=None, abspath=False, enable_scandir=False): """ Walk through a file directory and return an iterator of files that match requirements. Will autodetect if name has glob as magic ch...
[ "def", "find_files", "(", "directory", "=", "\".\"", ",", "ext", "=", "None", ",", "name", "=", "None", ",", "match_case", "=", "False", ",", "disable_glob", "=", "False", ",", "depth", "=", "None", ",", "abspath", "=", "False", ",", "enable_scandir", ...
37.56962
0.000657
async def get_shade(self, shade_id, from_cache=True) -> BaseShade: """Get a shade instance based on shade id.""" if not from_cache: await self.get_shades() for _shade in self.shades: if _shade.id == shade_id: return _shade raise ResourceNotFoundExc...
[ "async", "def", "get_shade", "(", "self", ",", "shade_id", ",", "from_cache", "=", "True", ")", "->", "BaseShade", ":", "if", "not", "from_cache", ":", "await", "self", ".", "get_shades", "(", ")", "for", "_shade", "in", "self", ".", "shades", ":", "if...
45.375
0.008108
def runcp_producer_loop_savedstate( use_saved_state=None, lightcurve_list=None, input_queue=None, input_bucket=None, result_queue=None, result_bucket=None, pfresult_list=None, runcp_kwargs=None, process_list_slice=None, download_when_done=T...
[ "def", "runcp_producer_loop_savedstate", "(", "use_saved_state", "=", "None", ",", "lightcurve_list", "=", "None", ",", "input_queue", "=", "None", ",", "input_bucket", "=", "None", ",", "result_queue", "=", "None", ",", "result_bucket", "=", "None", ",", "pfres...
41.032258
0.001228
def hstack(tup): """ Horizontally stack a sequence of value bounds pairs. Parameters ---------- tup: sequence a sequence of value, ``Bound`` pairs Returns ------- value: ndarray a horizontally concatenated array1d bounds: a list of Bounds """ vals, b...
[ "def", "hstack", "(", "tup", ")", ":", "vals", ",", "bounds", "=", "zip", "(", "*", "tup", ")", "stackvalue", "=", "np", ".", "hstack", "(", "vals", ")", "stackbounds", "=", "list", "(", "chain", "(", "*", "bounds", ")", ")", "return", "stackvalue"...
20.238095
0.002247
def _handle_api_call(self, url): """ Handle the return call from the api and return a data and meta_data object. It raises a ValueError on problems Keyword Arguments: url: The url of the service data_key: The key for getting the data from the jso object me...
[ "def", "_handle_api_call", "(", "self", ",", "url", ")", ":", "response", "=", "requests", ".", "get", "(", "url", ",", "proxies", "=", "self", ".", "proxy", ")", "if", "'json'", "in", "self", ".", "output_format", ".", "lower", "(", ")", "or", "'pan...
47.444444
0.002295
def gamma_centered(cls, kpts=(1, 1, 1), use_symmetries=True, use_time_reversal=True): """ Convenient static constructor for an automatic Gamma centered Kpoint grid. Args: kpts: Subdivisions N_1, N_2 and N_3 along reciprocal lattice vectors. use_symmetries: False if spati...
[ "def", "gamma_centered", "(", "cls", ",", "kpts", "=", "(", "1", ",", "1", ",", "1", ")", ",", "use_symmetries", "=", "True", ",", "use_time_reversal", "=", "True", ")", ":", "return", "cls", "(", "kpts", "=", "[", "kpts", "]", ",", "kpt_shifts", "...
47.529412
0.008495
def get_genome_refs(loc_file, loc_type): """ get dictionary of genome: location for all genomes of type in a .loc file for example: {'hg19': '/genomedir/Hsapiens/hg19/seq/hg19.fa'} """ if not file_exists(loc_file): return None refs = {} with open(loc_file) as in_handle: for l...
[ "def", "get_genome_refs", "(", "loc_file", ",", "loc_type", ")", ":", "if", "not", "file_exists", "(", "loc_file", ")", ":", "return", "None", "refs", "=", "{", "}", "with", "open", "(", "loc_file", ")", "as", "in_handle", ":", "for", "line", "in", "in...
35.705882
0.001605
def default_hass_config_dir(): """Put together the default configuration directory based on the OS.""" data_dir = os.getenv("APPDATA") if os.name == "nt" else os.path.expanduser("~") return os.path.join(data_dir, ".homeassistant")
[ "def", "default_hass_config_dir", "(", ")", ":", "data_dir", "=", "os", ".", "getenv", "(", "\"APPDATA\"", ")", "if", "os", ".", "name", "==", "\"nt\"", "else", "os", ".", "path", ".", "expanduser", "(", "\"~\"", ")", "return", "os", ".", "path", ".", ...
59.75
0.008264
def run_reach(pmid_list, base_dir, num_cores, start_index, end_index, force_read, force_fulltext, cleanup=False, verbose=True): """Run reach on a list of pmids.""" logger.info('Running REACH with force_read=%s' % force_read) logger.info('Running REACH with force_fulltext=%s' % force_fulltext) ...
[ "def", "run_reach", "(", "pmid_list", ",", "base_dir", ",", "num_cores", ",", "start_index", ",", "end_index", ",", "force_read", ",", "force_fulltext", ",", "cleanup", "=", "False", ",", "verbose", "=", "True", ")", ":", "logger", ".", "info", "(", "'Runn...
38.590476
0.000481
def allLobbySlots(self): """the current configuration of the lobby's players, defined before the match starts""" if self.debug: p = ["Lobby Configuration detail:"] + \ [" %s:%s%s"%(p, " "*(12-len(p.type)), p.name)] #[" agent: %s"%p for...
[ "def", "allLobbySlots", "(", "self", ")", ":", "if", "self", ".", "debug", ":", "p", "=", "[", "\"Lobby Configuration detail:\"", "]", "+", "[", "\" %s:%s%s\"", "%", "(", "p", ",", "\" \"", "*", "(", "12", "-", "len", "(", "p", ".", "type", ")", ...
60.909091
0.020588
def options(cls): """Return a dictionary of the ``Option`` objects for this config.""" return {k: v for k, v in cls.__dict__.items() if isinstance(v, Option)}
[ "def", "options", "(", "cls", ")", ":", "return", "{", "k", ":", "v", "for", "k", ",", "v", "in", "cls", ".", "__dict__", ".", "items", "(", ")", "if", "isinstance", "(", "v", ",", "Option", ")", "}" ]
57.333333
0.011494
def norm(self, estimate=False, **kwargs): """Return the operator norm of this operator. If this operator is non-linear, this should be the Lipschitz constant. Parameters ---------- estimate : bool If true, estimate the operator norm. By default, it is estimated ...
[ "def", "norm", "(", "self", ",", "estimate", "=", "False", ",", "*", "*", "kwargs", ")", ":", "if", "not", "estimate", ":", "raise", "NotImplementedError", "(", "'`Operator.norm()` not implemented, use '", "'`Operator.norm(estimate=True)` to '", "'obtain an estimate.'",...
32.865385
0.001136
def normalise(string): """ Convert each character of the string to the normal form in which it was defined in the IPA spec. This would be normal form D, except for the voiceless palatar fricative (ç) which should be in normal form C. Helper for tokenise_word(string, ..). """ string = unicodedata.normalize('NFD'...
[ "def", "normalise", "(", "string", ")", ":", "string", "=", "unicodedata", ".", "normalize", "(", "'NFD'", ",", "string", ")", "for", "char_c", "in", "ipa", ".", "get_precomposed_chars", "(", ")", ":", "char_d", "=", "unicodedata", ".", "normalize", "(", ...
30.5625
0.025794
def inflect(self, text): """Inflect ``text`` if the ``inflect`` class Meta option is defined, otherwise do nothing. """ return self.opts.inflect(text) if self.opts.inflect else text
[ "def", "inflect", "(", "self", ",", "text", ")", ":", "return", "self", ".", "opts", ".", "inflect", "(", "text", ")", "if", "self", ".", "opts", ".", "inflect", "else", "text" ]
41.8
0.014085
def path(self, path): """ Creates a path based on the location attribute of the backend and the path argument of the function. If the path argument is an absolute path the path is returned. :param path: The path that should be joined with the backends location. """ if os...
[ "def", "path", "(", "self", ",", "path", ")", ":", "if", "os", ".", "path", ".", "isabs", "(", "path", ")", ":", "return", "path", "return", "os", ".", "path", ".", "join", "(", "self", ".", "location", ",", "path", ")" ]
40.2
0.009732
def _parse_tokenize(self, rule): """Tokenizer for the policy language.""" for token in self._TOKENIZE_RE.split(rule): # Skip empty tokens if not token or token.isspace(): continue # Handle leading parens on the token clean = token.lstrip(...
[ "def", "_parse_tokenize", "(", "self", ",", "rule", ")", ":", "for", "token", "in", "self", ".", "_TOKENIZE_RE", ".", "split", "(", "rule", ")", ":", "# Skip empty tokens", "if", "not", "token", "or", "token", ".", "isspace", "(", ")", ":", "continue", ...
33.8
0.001438
def main_target_alternative (self, target): """ Registers the specified target as a main target alternatives. Returns 'target'. """ assert isinstance(target, AbstractTarget) target.project ().add_alternative (target) return target
[ "def", "main_target_alternative", "(", "self", ",", "target", ")", ":", "assert", "isinstance", "(", "target", ",", "AbstractTarget", ")", "target", ".", "project", "(", ")", ".", "add_alternative", "(", "target", ")", "return", "target" ]
39.428571
0.01773
def multi_zset(self, name, **kvs): """ Return a dictionary mapping key/value by ``keys`` from zset ``names`` :param string name: the zset name :param list keys: a list of keys :return: the number of successful creation :rtype: int >>> ssdb.multi_zset('zs...
[ "def", "multi_zset", "(", "self", ",", "name", ",", "*", "*", "kvs", ")", ":", "for", "k", ",", "v", "in", "kvs", ".", "items", "(", ")", ":", "kvs", "[", "k", "]", "=", "get_integer", "(", "k", ",", "int", "(", "v", ")", ")", "return", "se...
37.210526
0.008276
def join(delimiter, iterable, **kwargs): """Returns a string which is a concatenation of strings in ``iterable``, separated by given ``delimiter``. :param delimiter: Delimiter to put between strings :param iterable: Iterable to join Optional keyword arguments control the exact joining strategy: ...
[ "def", "join", "(", "delimiter", ",", "iterable", ",", "*", "*", "kwargs", ")", ":", "ensure_string", "(", "delimiter", ")", "ensure_iterable", "(", "iterable", ")", "ensure_keyword_args", "(", "kwargs", ",", "optional", "=", "(", "'errors'", ",", "'with_'",...
37.137931
0.000905
def switch_state_machine_execution_engine(self, new_state_machine_execution_engine): """ Switch the state machine execution engine the main window controller listens to. :param new_state_machine_execution_engine: the new state machine execution engine for this controller :return: ...
[ "def", "switch_state_machine_execution_engine", "(", "self", ",", "new_state_machine_execution_engine", ")", ":", "# relieve old one", "self", ".", "relieve_model", "(", "self", ".", "state_machine_execution_model", ")", "# register new", "self", ".", "state_machine_execution...
47.416667
0.008621
def del_design(self, design_name): """ Removes the specified design design_name <str> """ try: design = self.get_design(design_name) r = requests.request( "DELETE", "%s/%s/_design/%s" % ( self.host, self.database_name, design_name ...
[ "def", "del_design", "(", "self", ",", "design_name", ")", ":", "try", ":", "design", "=", "self", ".", "get_design", "(", "design_name", ")", "r", "=", "requests", ".", "request", "(", "\"DELETE\"", ",", "\"%s/%s/_design/%s\"", "%", "(", "self", ".", "h...
18.041667
0.015351
def play(self, target=None, index=None, choose=None): """ Queue a Play action on the card. """ if choose: if self.must_choose_one: choose = card = self.choose_cards.filter(id=choose)[0] self.log("%r: choosing %r", self, choose) else: raise InvalidAction("%r cannot be played with choice %r" % (...
[ "def", "play", "(", "self", ",", "target", "=", "None", ",", "index", "=", "None", ",", "choose", "=", "None", ")", ":", "if", "choose", ":", "if", "self", ".", "must_choose_one", ":", "choose", "=", "card", "=", "self", ".", "choose_cards", ".", "...
37.28
0.029289
def get_networks(cls): """ Get the wifi networks currently available. Returns -------- result: future A future that resolves with the list of networks available or None if wifi could not be enabled (permission denied, etc...) ...
[ "def", "get_networks", "(", "cls", ")", ":", "app", "=", "AndroidApplication", ".", "instance", "(", ")", "activity", "=", "app", ".", "widget", "f", "=", "app", ".", "create_future", "(", ")", "def", "on_permission_result", "(", "result", ")", ":", "if"...
34.638889
0.001559
def reformat_node(item=None, full=False): ''' Reformat the returned data from joyent, determine public/private IPs and strip out fields if necessary to provide either full or brief content. :param item: node dictionary :param full: full or brief output :return: dict ''' desired_keys = [...
[ "def", "reformat_node", "(", "item", "=", "None", ",", "full", "=", "False", ")", ":", "desired_keys", "=", "[", "'id'", ",", "'name'", ",", "'state'", ",", "'public_ips'", ",", "'private_ips'", ",", "'size'", ",", "'image'", ",", "'location'", "]", "ite...
28.658537
0.000823
def choicebox(msg="Pick something." , title=" " , choices=() ): """ Present the user with a list of choices. return the choice that he selects. return None if he cancels the selection selection. @arg msg: the msg to be displayed. @arg title: the window title @arg choices: a list...
[ "def", "choicebox", "(", "msg", "=", "\"Pick something.\"", ",", "title", "=", "\" \"", ",", "choices", "=", "(", ")", ")", ":", "if", "len", "(", "choices", ")", "==", "0", ":", "choices", "=", "[", "\"Program logic error - no choices were specified.\"", "]...
30.777778
0.019264
def _remove_persistent_module(mod, comment): ''' Remove module from configuration file. If comment is true only comment line where module is. ''' conf = _get_modules_conf() mod_name = _strip_module_name(mod) if not mod_name or mod_name not in mod_list(True): return set() escape_m...
[ "def", "_remove_persistent_module", "(", "mod", ",", "comment", ")", ":", "conf", "=", "_get_modules_conf", "(", ")", "mod_name", "=", "_strip_module_name", "(", "mod", ")", "if", "not", "mod_name", "or", "mod_name", "not", "in", "mod_list", "(", "True", ")"...
35.6
0.001825
def update_wsnum_in_files(self, vernum): """ With the given version number ```vernum```, update the source's version number, and replace in the file hashmap. the version number is in the CHECKSUMS file. :param vernum: :return: """ self.version_num = vernu...
[ "def", "update_wsnum_in_files", "(", "self", ",", "vernum", ")", ":", "self", ".", "version_num", "=", "vernum", "# replace the WSNUMBER in the url paths with the real WS###", "for", "f", "in", "self", ".", "files", ":", "url", "=", "self", ".", "files", "[", "f...
38.818182
0.002286
def is_valid_type(self, filepath): """ Returns True if the given filepath is a valid watchable filetype. The filepath can be assumed to be a file (not a directory). """ if self.in_repo(filepath): return False validators = self._validators if len(valid...
[ "def", "is_valid_type", "(", "self", ",", "filepath", ")", ":", "if", "self", ".", "in_repo", "(", "filepath", ")", ":", "return", "False", "validators", "=", "self", ".", "_validators", "if", "len", "(", "validators", ")", "==", "0", ":", "validators", ...
35.68
0.002183
def set_subject(self,subject): """ Send a subject change request to the room. :Parameters: - `subject`: the new subject. :Types: - `subject`: `unicode` """ m=Message(to_jid=self.room_jid.bare(),stanza_type="groupchat",subject=subject) self...
[ "def", "set_subject", "(", "self", ",", "subject", ")", ":", "m", "=", "Message", "(", "to_jid", "=", "self", ".", "room_jid", ".", "bare", "(", ")", ",", "stanza_type", "=", "\"groupchat\"", ",", "subject", "=", "subject", ")", "self", ".", "manager",...
30.272727
0.020408
def find_and_remove(self, f: Callable): """ Removes any and all fields for which `f(field)` returns `True`. """ self._table = [fld for fld in self._table if not f(fld)]
[ "def", "find_and_remove", "(", "self", ",", "f", ":", "Callable", ")", ":", "self", ".", "_table", "=", "[", "fld", "for", "fld", "in", "self", ".", "_table", "if", "not", "f", "(", "fld", ")", "]" ]
39.2
0.01
def get_datatype(self, table: str, column: str) -> str: """Returns database SQL datatype for a column: e.g. VARCHAR.""" return self.flavour.get_datatype(self, table, column).upper()
[ "def", "get_datatype", "(", "self", ",", "table", ":", "str", ",", "column", ":", "str", ")", "->", "str", ":", "return", "self", ".", "flavour", ".", "get_datatype", "(", "self", ",", "table", ",", "column", ")", ".", "upper", "(", ")" ]
65
0.010152
def create(self): """ Generate the data and figs for the report and fill the LaTeX templates with them to generate a PDF file with the report. :return: """ logger.info("Generating the report from %s to %s", self.start, self.end) self.create_data_figs() s...
[ "def", "create", "(", "self", ")", ":", "logger", ".", "info", "(", "\"Generating the report from %s to %s\"", ",", "self", ".", "start", ",", "self", ".", "end", ")", "self", ".", "create_data_figs", "(", ")", "self", ".", "create_pdf", "(", ")", "logger"...
28.076923
0.01061
def template(basedir, text, vars, lookup_fatal=True, expand_lists=False): ''' run a text buffer through the templating engine until it no longer changes ''' try: text = text.decode('utf-8') except UnicodeEncodeError: pass # already unicode text = varReplace(basedir, unicode(text), vars,...
[ "def", "template", "(", "basedir", ",", "text", ",", "vars", ",", "lookup_fatal", "=", "True", ",", "expand_lists", "=", "False", ")", ":", "try", ":", "text", "=", "text", ".", "decode", "(", "'utf-8'", ")", "except", "UnicodeEncodeError", ":", "pass", ...
42.444444
0.010256
async def download(self, source, destination="", *, write_into=False, block_size=DEFAULT_BLOCK_SIZE): """ :py:func:`asyncio.coroutine` High level download method for downloading files and directories recursively and save them to the file system. :param so...
[ "async", "def", "download", "(", "self", ",", "source", ",", "destination", "=", "\"\"", ",", "*", ",", "write_into", "=", "False", ",", "block_size", "=", "DEFAULT_BLOCK_SIZE", ")", ":", "source", "=", "pathlib", ".", "PurePosixPath", "(", "source", ")", ...
47.1
0.00156
def get_variation_for_rollout(self, rollout, user_id, attributes=None): """ Determine which experiment/variation the user is in for a given rollout. Returns the variation of the first experiment the user qualifies for. Args: rollout: Rollout for which we are getting the variation. user_id: ID f...
[ "def", "get_variation_for_rollout", "(", "self", ",", "rollout", ",", "user_id", ",", "attributes", "=", "None", ")", ":", "# Go through each experiment in order and try to get the variation for the user", "if", "rollout", "and", "len", "(", "rollout", ".", "experiments",...
48.894737
0.009497
def build_rule(table=None, chain=None, command=None, position='', full=None, family='ipv4', **kwargs): ''' Build a well-formatted nftables rule based on kwargs. A `table` and `chain` are not required, unless `full` is True. If `full` is `True`, then `table`, `chain` and `command` are req...
[ "def", "build_rule", "(", "table", "=", "None", ",", "chain", "=", "None", ",", "command", "=", "None", ",", "position", "=", "''", ",", "full", "=", "None", ",", "family", "=", "'ipv4'", ",", "*", "*", "kwargs", ")", ":", "ret", "=", "{", "'comm...
34.497354
0.000745
def batch_write_input(structures, vasp_input_set=MPRelaxSet, output_dir=".", make_dir_if_not_present=True, subfolder=None, sanitize=False, include_cif=False, **kwargs): """ Batch write vasp input for a sequence of structures to output_dir, following the format out...
[ "def", "batch_write_input", "(", "structures", ",", "vasp_input_set", "=", "MPRelaxSet", ",", "output_dir", "=", "\".\"", ",", "make_dir_if_not_present", "=", "True", ",", "subfolder", "=", "None", ",", "sanitize", "=", "False", ",", "include_cif", "=", "False",...
48.775
0.000503
def format_exception(e): """Returns a string containing the type and text of the exception. """ from .utils.printing import fill return '\n'.join(fill(line) for line in traceback.format_exception_only(type(e), e))
[ "def", "format_exception", "(", "e", ")", ":", "from", ".", "utils", ".", "printing", "import", "fill", "return", "'\\n'", ".", "join", "(", "fill", "(", "line", ")", "for", "line", "in", "traceback", ".", "format_exception_only", "(", "type", "(", "e", ...
37.5
0.008696
def render_trees(trees, path_composer): """ Render list of `trees` to HTML. Args: trees (list): List of :class:`.Tree`. path_composer (fn reference): Function used to compose paths from UUID. Look at :func:`.compose_tree_path` from :mod:`.web_tools`. Returns: str: H...
[ "def", "render_trees", "(", "trees", ",", "path_composer", ")", ":", "trees", "=", "list", "(", "trees", ")", "# by default, this is set", "def", "create_pub_cache", "(", "trees", ")", ":", "\"\"\"\n Create uuid -> DBPublication cache from all uuid's linked from `tre...
27.294872
0.000453
def export_legacy(self, filename): """ TODO: add docs """ logger.warning("exporting to legacy is experimental until official 1.0 release") filename = os.path.expanduser(filename) return io.pass_to_legacy(self, filename)
[ "def", "export_legacy", "(", "self", ",", "filename", ")", ":", "logger", ".", "warning", "(", "\"exporting to legacy is experimental until official 1.0 release\"", ")", "filename", "=", "os", ".", "path", ".", "expanduser", "(", "filename", ")", "return", "io", "...
37.285714
0.011236
def _pack_image(filename, max_size, form_field='image', f=None): """Pack image from file into multipart-formdata post body""" # image must be less than 700kb in size if f is None: try: if os.path.getsize(filename) > (max_size * 1024): raise TweepEr...
[ "def", "_pack_image", "(", "filename", ",", "max_size", ",", "form_field", "=", "'image'", ",", "f", "=", "None", ")", ":", "# image must be less than 700kb in size", "if", "f", "is", "None", ":", "try", ":", "if", "os", ".", "path", ".", "getsize", "(", ...
38.470588
0.001988
def drag_by_coordinates(self,sx, sy, ex, ey, steps=10): """ Drag from (sx, sy) to (ex, ey) with steps See `Swipe By Coordinates` also. """ self.device.drag(sx, sy, ex, ey, steps)
[ "def", "drag_by_coordinates", "(", "self", ",", "sx", ",", "sy", ",", "ex", ",", "ey", ",", "steps", "=", "10", ")", ":", "self", ".", "device", ".", "drag", "(", "sx", ",", "sy", ",", "ex", ",", "ey", ",", "steps", ")" ]
30.428571
0.013699
def replace(self, to_replace, value, inplace=False, filter=None, regex=False, convert=True): """replace the to_replace value with value, possible to create new blocks here this is just a call to putmask. regex is not used here. It is used in ObjectBlocks. It is here for API comp...
[ "def", "replace", "(", "self", ",", "to_replace", ",", "value", ",", "inplace", "=", "False", ",", "filter", "=", "None", ",", "regex", "=", "False", ",", "convert", "=", "True", ")", ":", "inplace", "=", "validate_bool_kwarg", "(", "inplace", ",", "'i...
44.974359
0.001674
def compare(ver1, ver2): '''Version comparing, returns 0 if are the same, returns >0 if first is bigger, <0 if first is smaller, excepts valid version''' if ver1 == ver2: return 0 ver1 = _cut(ver1) ver2 = _cut(ver2) # magic multiplier m = 1 # if the first one is shorter, repl...
[ "def", "compare", "(", "ver1", ",", "ver2", ")", ":", "if", "ver1", "==", "ver2", ":", "return", "0", "ver1", "=", "_cut", "(", "ver1", ")", "ver2", "=", "_cut", "(", "ver2", ")", "# magic multiplier", "m", "=", "1", "# if the first one is shorter, repla...
28.769231
0.001294
def herald_message(self, herald_svc, message): """ Handles a message received by Herald :param herald_svc: Herald service :param message: Received message """ subject = message.subject if subject == SUBJECT_DISCOVERY_STEP_1: # Step 1: Register the rem...
[ "def", "herald_message", "(", "self", ",", "herald_svc", ",", "message", ")", ":", "subject", "=", "message", ".", "subject", "if", "subject", "==", "SUBJECT_DISCOVERY_STEP_1", ":", "# Step 1: Register the remote peer and reply with our dump", "try", ":", "# Delayed reg...
39.163636
0.000906
def setup(basepath=DEFAULT_BASEPATH): """Set the environment modules used by the Environment Module system.""" module_version = os.environ.get('MODULE_VERSION', DEFAULT_VERSION) moduleshome = os.path.join(basepath, module_version) # Abort if MODULESHOME does not exist if not os.path.isdir(modulesh...
[ "def", "setup", "(", "basepath", "=", "DEFAULT_BASEPATH", ")", ":", "module_version", "=", "os", ".", "environ", ".", "get", "(", "'MODULE_VERSION'", ",", "DEFAULT_VERSION", ")", "moduleshome", "=", "os", ".", "path", ".", "join", "(", "basepath", ",", "mo...
42.133333
0.000515
def getOpenIDStore(filestore_path, table_prefix): """ Returns an OpenID association store object based on the database engine chosen for this Django application. * If no database engine is chosen, a filesystem-based store will be used whose path is filestore_path. * If a database engine is c...
[ "def", "getOpenIDStore", "(", "filestore_path", ",", "table_prefix", ")", ":", "db_engine", "=", "settings", ".", "DATABASES", "[", "'default'", "]", "[", "'ENGINE'", "]", "if", "not", "db_engine", ":", "return", "FileOpenIDStore", "(", "filestore_path", ")", ...
35.476923
0.000844
def get_generator(self, field): ''' Return a value generator based on the field instance that is passed to this method. This function may return ``None`` which means that the specified field will be ignored (e.g. if no matching generator was found). ''' if isinsta...
[ "def", "get_generator", "(", "self", ",", "field", ")", ":", "if", "isinstance", "(", "field", ",", "fields", ".", "AutoField", ")", ":", "return", "None", "if", "self", ".", "is_inheritance_parent", "(", "field", ")", ":", "return", "None", "if", "(", ...
47.704545
0.0014
def prune(self, depth=0): """ Removes all nodes with less or equal links than depth. """ for n in list(self.nodes): if len(n.links) <= depth: self.remove_node(n.id)
[ "def", "prune", "(", "self", ",", "depth", "=", "0", ")", ":", "for", "n", "in", "list", "(", "self", ".", "nodes", ")", ":", "if", "len", "(", "n", ".", "links", ")", "<=", "depth", ":", "self", ".", "remove_node", "(", "n", ".", "id", ")" ]
35.166667
0.009259
def getLabel(self, key): """Gets the label assigned to an axes :param key:??? :type key: str """ axisItem = self.getPlotItem().axes[key]['item'] return axisItem.label.toPlainText()
[ "def", "getLabel", "(", "self", ",", "key", ")", ":", "axisItem", "=", "self", ".", "getPlotItem", "(", ")", ".", "axes", "[", "key", "]", "[", "'item'", "]", "return", "axisItem", ".", "label", ".", "toPlainText", "(", ")" ]
27.75
0.008734
def vsan_datastore_configured(name, datastore_name): ''' Configures the cluster's VSAN datastore WARNING: The VSAN datastore is created automatically after the first ESXi host is added to the cluster; the state assumes that the datastore exists and errors if it doesn't. ''' cluster_name, d...
[ "def", "vsan_datastore_configured", "(", "name", ",", "datastore_name", ")", ":", "cluster_name", ",", "datacenter_name", "=", "__salt__", "[", "'esxcluster.get_details'", "]", "(", ")", "[", "'cluster'", "]", ",", "__salt__", "[", "'esxcluster.get_details'", "]", ...
42.349206
0.001465
def doRollover(self): """Do a rollover, as described in __init__().""" self.stream.close() try: if self.backupCount > 0: tmp_location = "%s.0" % self.baseFilename os.rename(self.baseFilename, tmp_location) for i in range(self.backupCoun...
[ "def", "doRollover", "(", "self", ")", ":", "self", ".", "stream", ".", "close", "(", ")", "try", ":", "if", "self", ".", "backupCount", ">", "0", ":", "tmp_location", "=", "\"%s.0\"", "%", "self", ".", "baseFilename", "os", ".", "rename", "(", "self...
41.727273
0.00213
def print_splits(cliques, next_cliques): """Print shifts for new forks.""" splits = 0 for i, clique in enumerate(cliques): parent, _ = clique # If this fork continues if parent in next_cliques: # If there is a new fork, print a split if len(next_cliques[paren...
[ "def", "print_splits", "(", "cliques", ",", "next_cliques", ")", ":", "splits", "=", "0", "for", "i", ",", "clique", "in", "enumerate", "(", "cliques", ")", ":", "parent", ",", "_", "=", "clique", "# If this fork continues", "if", "parent", "in", "next_cli...
34
0.002387
def job_is_running(self, job_id): """ Check if a job is currently running. False is returned if the job does not exist. :param job_id: Job identifier to check the status of. :type job_id: :py:class:`uuid.UUID` :rtype: bool """ job_id = normalize_job_id(job_id) if job_id not in self._jobs: return F...
[ "def", "job_is_running", "(", "self", ",", "job_id", ")", ":", "job_id", "=", "normalize_job_id", "(", "job_id", ")", "if", "job_id", "not", "in", "self", ".", "_jobs", ":", "return", "False", "job_desc", "=", "self", ".", "_jobs", "[", "job_id", "]", ...
25.9375
0.037209
def __standardize_result(status, message, data=None, debug_msg=None): ''' Standardizes all responses :param status: :param message: :param data: :param debug_msg: :return: ''' result = { 'status': status, 'message': message } if data is not None: res...
[ "def", "__standardize_result", "(", "status", ",", "message", ",", "data", "=", "None", ",", "debug_msg", "=", "None", ")", ":", "result", "=", "{", "'status'", ":", "status", ",", "'message'", ":", "message", "}", "if", "data", "is", "not", "None", ":...
18.863636
0.002294
def main(arv=None): """lambda-uploader command line interface.""" # Check for Python 2.7 or later if sys.version_info[0] < 3 and not sys.version_info[1] == 7: raise RuntimeError('lambda-uploader requires Python 2.7 or later') import argparse parser = argparse.ArgumentParser( de...
[ "def", "main", "(", "arv", "=", "None", ")", ":", "# Check for Python 2.7 or later", "if", "sys", ".", "version_info", "[", "0", "]", "<", "3", "and", "not", "sys", ".", "version_info", "[", "1", "]", "==", "7", ":", "raise", "RuntimeError", "(", "'lam...
47.471264
0.000237
def _teardown(self): ''' Replace the original method. ''' if not self._was_object_method: setattr(self._instance, self._attr, self._obj) else: delattr(self._instance, self._attr)
[ "def", "_teardown", "(", "self", ")", ":", "if", "not", "self", ".", "_was_object_method", ":", "setattr", "(", "self", ".", "_instance", ",", "self", ".", "_attr", ",", "self", ".", "_obj", ")", "else", ":", "delattr", "(", "self", ".", "_instance", ...
29.375
0.008264
def calc_exp(skydir, ltc, event_class, event_types, egy, cth_bins, npts=None): """Calculate the exposure on a 2D grid of energy and incidence angle. Parameters ---------- npts : int Number of points by which to sample the response in each incidence angle bin. If None t...
[ "def", "calc_exp", "(", "skydir", ",", "ltc", ",", "event_class", ",", "event_types", ",", "egy", ",", "cth_bins", ",", "npts", "=", "None", ")", ":", "if", "npts", "is", "None", ":", "npts", "=", "int", "(", "np", ".", "ceil", "(", "np", ".", "m...
32.71875
0.001855
def start(self): """ TODO: docstring """ logger.info("Starting interchange") # last = time.time() while True: # active_flag = False socks = dict(self.poller.poll(1)) if socks.get(self.task_incoming) == zmq.POLLIN: message = self.task_...
[ "def", "start", "(", "self", ")", ":", "logger", ".", "info", "(", "\"Starting interchange\"", ")", "# last = time.time()", "while", "True", ":", "# active_flag = False", "socks", "=", "dict", "(", "self", ".", "poller", ".", "poll", "(", "1", ")", ")", "i...
38.958333
0.002088
def update(self, deltat=1.0): '''fly in long curves''' DNFZ.update(self, deltat) if (self.distance_from_home() > gen_settings.region_width or self.getalt() < self.ground_height() or self.getalt() > self.ground_height() + 1000): self.randpos() self....
[ "def", "update", "(", "self", ",", "deltat", "=", "1.0", ")", ":", "DNFZ", ".", "update", "(", "self", ",", "deltat", ")", "if", "(", "self", ".", "distance_from_home", "(", ")", ">", "gen_settings", ".", "region_width", "or", "self", ".", "getalt", ...
40.25
0.009119
def api_subclass_factory(name, docstring, remove_methods, base=SlackApi): """Create an API subclass with fewer methods than its base class. Arguments: name (:py:class:`str`): The name of the new class. docstring (:py:class:`str`): The docstring for the new class. remove_methods (:py:class:`di...
[ "def", "api_subclass_factory", "(", "name", ",", "docstring", ",", "remove_methods", ",", "base", "=", "SlackApi", ")", ":", "methods", "=", "deepcopy", "(", "base", ".", "API_METHODS", ")", "for", "parent", ",", "to_remove", "in", "remove_methods", ".", "it...
40.533333
0.000803
def parse_group_address(addr): """Parse KNX group addresses and return the address as an integer. This allows to convert x/x/x and x/x address syntax to a numeric KNX group address """ if addr is None: raise KNXException("No address given") res = None if re.match('[0-9]+$', addr)...
[ "def", "parse_group_address", "(", "addr", ")", ":", "if", "addr", "is", "None", ":", "raise", "KNXException", "(", "\"No address given\"", ")", "res", "=", "None", "if", "re", ".", "match", "(", "'[0-9]+$'", ",", "addr", ")", ":", "res", "=", "int", "...
26.060606
0.001121
def convert_sum( params, w_name, scope_name, inputs, layers, weights, names ): """ Convert sum. Args: params: dictionary with layer parameters w_name: name prefix in state_dict scope_name: pytorch scope name inputs: pytorch node inputs layers: dictionary with ker...
[ "def", "convert_sum", "(", "params", ",", "w_name", ",", "scope_name", ",", "inputs", ",", "layers", ",", "weights", ",", "names", ")", ":", "print", "(", "'Converting Sum ...'", ")", "def", "target_layer", "(", "x", ")", ":", "import", "keras", ".", "ba...
27.26087
0.001541
def read(self, length, skip=False): """Consumes the first ``length`` bytes from the accumulator.""" if length > self.__size: raise IndexError( 'Cannot pop %d bytes, %d bytes in buffer queue' % (length, self.__size)) self.position += length self.__size -= lengt...
[ "def", "read", "(", "self", ",", "length", ",", "skip", "=", "False", ")", ":", "if", "length", ">", "self", ".", "__size", ":", "raise", "IndexError", "(", "'Cannot pop %d bytes, %d bytes in buffer queue'", "%", "(", "length", ",", "self", ".", "__size", ...
36.021739
0.00235
def result(self): """Get the result(s) for this hook call (DEPRECATED in favor of ``get_result()``).""" msg = "Use get_result() which forces correct exception handling" warnings.warn(DeprecationWarning(msg), stacklevel=2) return self._result
[ "def", "result", "(", "self", ")", ":", "msg", "=", "\"Use get_result() which forces correct exception handling\"", "warnings", ".", "warn", "(", "DeprecationWarning", "(", "msg", ")", ",", "stacklevel", "=", "2", ")", "return", "self", ".", "_result" ]
53.8
0.010989
def _ReadRecordSchemaInformation(self, tables, file_object, record_offset): """Reads a schema information (CSSM_DL_DB_SCHEMA_INFO) record. Args: tables (dict[int, KeychainDatabaseTable]): tables per identifier. file_object (file): file-like object. record_offset (int): offset of the record re...
[ "def", "_ReadRecordSchemaInformation", "(", "self", ",", "tables", ",", "file_object", ",", "record_offset", ")", ":", "_", "=", "self", ".", "_ReadRecordHeader", "(", "file_object", ",", "record_offset", ")", "attribute_value_offsets", "=", "self", ".", "_ReadRec...
34.837209
0.001948
def communityvisibilitystate(self): """Return the Visibility State of the Users Profile""" if self._communityvisibilitystate == None: return None elif self._communityvisibilitystate in self.VisibilityState: return self.VisibilityState[self._communityvisibilitystate] ...
[ "def", "communityvisibilitystate", "(", "self", ")", ":", "if", "self", ".", "_communityvisibilitystate", "==", "None", ":", "return", "None", "elif", "self", ".", "_communityvisibilitystate", "in", "self", ".", "VisibilityState", ":", "return", "self", ".", "Vi...
41.222222
0.010554
def open(filename, connection=None): """Edits or Adds a filename ensuring the file is in perforce and editable :param filename: File to check out :type filename: str :param connection: Connection object to use :type connection: :py:class:`Connection` """ c = connection or connect() res ...
[ "def", "open", "(", "filename", ",", "connection", "=", "None", ")", ":", "c", "=", "connection", "or", "connect", "(", ")", "res", "=", "c", ".", "ls", "(", "filename", ")", "if", "res", "and", "res", "[", "0", "]", ".", "revision", ":", "res", ...
29.357143
0.002358
def _get_proxy_target(service_instance): ''' Returns the target object of a proxy. If the object doesn't exist a VMwareObjectRetrievalError is raised service_instance Service instance (vim.ServiceInstance) of the vCenter/ESXi host. ''' proxy_type = get_proxy_type() if not salt.util...
[ "def", "_get_proxy_target", "(", "service_instance", ")", ":", "proxy_type", "=", "get_proxy_type", "(", ")", "if", "not", "salt", ".", "utils", ".", "vmware", ".", "is_connection_to_a_vcenter", "(", "service_instance", ")", ":", "raise", "CommandExecutionError", ...
45.068182
0.000494
def markdown_cell(markdown): r""" Args: markdown (str): Returns: str: json formatted ipython notebook markdown cell CommandLine: python -m ibeis.templates.generate_notebook --exec-markdown_cell Example: >>> # DISABLE_DOCTEST >>> from ibeis.templates.generat...
[ "def", "markdown_cell", "(", "markdown", ")", ":", "import", "utool", "as", "ut", "markdown_header", "=", "ut", ".", "codeblock", "(", "'''\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {},\n \"source\": [\n '''", ")", "markdown_...
23.277778
0.001145
def do_post(url, payload, to=3, use_json=True): """ 使用 ``request.get`` 从指定 url 获取数据 :param use_json: 是否使用 ``json`` 格式, 如果是, 则可以直接使用字典, 否则需要先转换成字符串 :type use_json: bool :param payload: 实际数据内容 :type payload: dict :param url: ``接口地址`` :type url: :param to: ``响应超时返回时间`` :type to: ...
[ "def", "do_post", "(", "url", ",", "payload", ",", "to", "=", "3", ",", "use_json", "=", "True", ")", ":", "try", ":", "if", "use_json", ":", "rs", "=", "requests", ".", "post", "(", "url", ",", "json", "=", "payload", ",", "timeout", "=", "to", ...
27.518519
0.0013
def retrieve_activity_profile(self, activity, profile_id): """Retrieve activity profile with the specified parameters :param activity: Activity object of the desired activity profile :type activity: :class:`tincan.activity.Activity` :param profile_id: UUID of the desired profile ...
[ "def", "retrieve_activity_profile", "(", "self", ",", "activity", ",", "profile_id", ")", ":", "if", "not", "isinstance", "(", "activity", ",", "Activity", ")", ":", "activity", "=", "Activity", "(", "activity", ")", "request", "=", "HTTPRequest", "(", "meth...
38.146341
0.00187
def upgradeBatch(self, n): """ Upgrade the entire store in batches, yielding after each batch. @param n: Number of upgrades to perform per transaction @type n: C{int} @raise axiom.errors.ItemUpgradeError: if an item upgrade failed @return: A generator that yields after...
[ "def", "upgradeBatch", "(", "self", ",", "n", ")", ":", "store", "=", "self", ".", "store", "def", "_doBatch", "(", "itemType", ")", ":", "upgradedAnything", "=", "False", "for", "theItem", "in", "store", ".", "query", "(", "itemType", ",", "limit", "=...
33.183673
0.002389
def errReceived(self, data): """ Connected process wrote to stderr """ lines = data.splitlines() for line in lines: log_error("*** {name} stderr *** {line}", name=self.name, line=self.errFilter(line))
[ "def", "errReceived", "(", "self", ",", "data", ")", ":", "lines", "=", "data", ".", "splitlines", "(", ")", "for", "line", "in", "lines", ":", "log_error", "(", "\"*** {name} stderr *** {line}\"", ",", "name", "=", "self", ".", "name", ",", "line", "=",...
31.666667
0.017065
def _smooth_acf_savgol(acf, windowsize=21, polyorder=2): ''' This returns a smoothed version of the ACF. This version uses the Savitsky-Golay smoothing filter. Parameters ---------- acf : np.array The auto-correlation function array to smooth. windowsize : int The number ...
[ "def", "_smooth_acf_savgol", "(", "acf", ",", "windowsize", "=", "21", ",", "polyorder", "=", "2", ")", ":", "smoothed", "=", "savgol_filter", "(", "acf", ",", "windowsize", ",", "polyorder", ")", "return", "smoothed" ]
20.896552
0.001577
def patch_api_service(self, name, body, **kwargs): # noqa: E501 """patch_api_service # noqa: E501 partially update the specified APIService # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >...
[ "def", "patch_api_service", "(", "self", ",", "name", ",", "body", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async_req'", ")", ":", "return", "self", ...
55.875
0.001466
def set_fields_from_request(obj, request): """Search request for keys that match field names in obj, and call field mutator with request value. The list of fields for which schema mutators were found is returned. """ schema = obj.Schema() # fields contains all schema-valid field values from...
[ "def", "set_fields_from_request", "(", "obj", ",", "request", ")", ":", "schema", "=", "obj", ".", "Schema", "(", ")", "# fields contains all schema-valid field values from the request.", "fields", "=", "{", "}", "for", "fieldname", ",", "value", "in", "request", ...
36.814815
0.00098
def user_get(user_id=None, name=None, profile=None, **connection_args): ''' Return a specific users (keystone user-get) CLI Examples: .. code-block:: bash salt '*' keystone.user_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.user_get user_id=c965f79c4f864eaaa9c3b41904e67082 ...
[ "def", "user_get", "(", "user_id", "=", "None", ",", "name", "=", "None", ",", "profile", "=", "None", ",", "*", "*", "connection_args", ")", ":", "kstone", "=", "auth", "(", "profile", ",", "*", "*", "connection_args", ")", "ret", "=", "{", "}", "...
33.194444
0.002439
def _update_batches_if_needed(self)->None: "one_batch function is extremely slow with large datasets. This is caching the result as an optimization." if self.learn.data.valid_dl is None: return # Running learning rate finder, so return update_batches = self.data is not self.learn.data i...
[ "def", "_update_batches_if_needed", "(", "self", ")", "->", "None", ":", "if", "self", ".", "learn", ".", "data", ".", "valid_dl", "is", "None", ":", "return", "# Running learning rate finder, so return", "update_batches", "=", "self", ".", "data", "is", "not", ...
65.125
0.015152
def north_arrow_path(feature, parent): """Retrieve the full path of default north arrow logo.""" _ = feature, parent # NOQA north_arrow_file = setting(inasafe_north_arrow_path['setting_key']) if os.path.exists(north_arrow_file): return north_arrow_file else: LOGGER.info( ...
[ "def", "north_arrow_path", "(", "feature", ",", "parent", ")", ":", "_", "=", "feature", ",", "parent", "# NOQA", "north_arrow_file", "=", "setting", "(", "inasafe_north_arrow_path", "[", "'setting_key'", "]", ")", "if", "os", ".", "path", ".", "exists", "("...
41.153846
0.001828
def getLatency(self, instId: int) -> float: """ Return a dict with client identifier as a key and calculated latency as a value """ if len(self.clientAvgReqLatencies) == 0: return 0.0 return self.clientAvgReqLatencies[instId].get_avg_latency()
[ "def", "getLatency", "(", "self", ",", "instId", ":", "int", ")", "->", "float", ":", "if", "len", "(", "self", ".", "clientAvgReqLatencies", ")", "==", "0", ":", "return", "0.0", "return", "self", ".", "clientAvgReqLatencies", "[", "instId", "]", ".", ...
41.285714
0.010169
def save_rnn_checkpoint(cells, prefix, epoch, symbol, arg_params, aux_params): """Save checkpoint for model using RNN cells. Unpacks weight before saving. Parameters ---------- cells : mxnet.rnn.RNNCell or list of RNNCells The RNN cells used by this symbol. prefix : str Prefix o...
[ "def", "save_rnn_checkpoint", "(", "cells", ",", "prefix", ",", "epoch", ",", "symbol", ",", "arg_params", ",", "aux_params", ")", ":", "if", "isinstance", "(", "cells", ",", "BaseRNNCell", ")", ":", "cells", "=", "[", "cells", "]", "for", "cell", "in", ...
33.724138
0.000994
def createPedChr24UsingPlink(options): """Run plink to create a ped format. :param options: the options. :type options: argparse.Namespace Uses Plink to create a ``ped`` file of markers on the chromosome ``24``. It uses the ``recodeA`` options to use additive coding. It also subsets the data ...
[ "def", "createPedChr24UsingPlink", "(", "options", ")", ":", "plinkCommand", "=", "[", "\"plink\"", ",", "\"--noweb\"", ",", "\"--bfile\"", ",", "options", ".", "bfile", ",", "\"--chr\"", ",", "\"24\"", ",", "\"--recodeA\"", ",", "\"--keep\"", ",", "options", ...
36.764706
0.00156
def generate(self, output_dir, work, ngrams, labels, minus_ngrams): """Generates HTML reports for each witness to `work`, showing its text with the n-grams in `ngrams` highlighted. Any n-grams in `minus_ngrams` have any highlighting of them (or subsets of them) removed. :param ...
[ "def", "generate", "(", "self", ",", "output_dir", ",", "work", ",", "ngrams", ",", "labels", ",", "minus_ngrams", ")", ":", "template", "=", "self", ".", "_get_template", "(", ")", "colours", "=", "generate_colours", "(", "len", "(", "ngrams", ")", ")",...
45.176471
0.001275
def get_trace(self, frame, tb): """Get a dict of the traceback for wdb.js use""" import linecache frames = [] stack, _ = self.get_stack(frame, tb) current = 0 for i, (stack_frame, lno) in enumerate(stack): code = stack_frame.f_code filename = code...
[ "def", "get_trace", "(", "self", ",", "frame", ",", "tb", ")", ":", "import", "linecache", "frames", "=", "[", "]", "stack", ",", "_", "=", "self", ".", "get_stack", "(", "frame", ",", "tb", ")", "current", "=", "0", "for", "i", ",", "(", "stack_...
37.075
0.001314
def GetMemSwapTargetMB(self): '''Undocumented.''' counter = c_uint() ret = vmGuestLib.VMGuestLib_GetMemSwapTargetMB(self.handle.value, byref(counter)) if ret != VMGUESTLIB_ERROR_SUCCESS: raise VMGuestLibException(ret) return counter.value
[ "def", "GetMemSwapTargetMB", "(", "self", ")", ":", "counter", "=", "c_uint", "(", ")", "ret", "=", "vmGuestLib", ".", "VMGuestLib_GetMemSwapTargetMB", "(", "self", ".", "handle", ".", "value", ",", "byref", "(", "counter", ")", ")", "if", "ret", "!=", "...
45.5
0.014388
def add_log_handler(log, handler=None, debug=None, fmt=None): """为一个 :class:`logging.Logger` 的实例增加 handler。 :param Logger log: 需要处理的 :class:`logging.Logger` 的实例。 :param Handler handler: 一个 :class:`logging.Handler` 的实例。 :param int debug: Debug 级别。 :param str fmt: Handler 的 Formatter。 """ if...
[ "def", "add_log_handler", "(", "log", ",", "handler", "=", "None", ",", "debug", "=", "None", ",", "fmt", "=", "None", ")", ":", "if", "debug", ":", "log", ".", "setLevel", "(", "debug", ")", "if", "handler", ":", "# if not fmt:", "# fmt = __LOG_FMT"...
29
0.001965
def animation_dialog(images, delay_s=1., loop=True, **kwargs): ''' .. versionadded:: v0.19 Parameters ---------- images : list Filepaths to images or :class:`gtk.Pixbuf` instances. delay_s : float, optional Number of seconds to display each frame. Default: ``1.0``. ...
[ "def", "animation_dialog", "(", "images", ",", "delay_s", "=", "1.", ",", "loop", "=", "True", ",", "*", "*", "kwargs", ")", ":", "def", "_as_pixbuf", "(", "image", ")", ":", "if", "isinstance", "(", "image", ",", "types", ".", "StringTypes", ")", ":...
26.276923
0.000564