text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def update_import_errors(session, dagbag): """ For the DAGs in the given DagBag, record any associated import errors and clears errors for files that no longer have them. These are usually displayed through the Airflow UI so that users know that there are issues parsing DAGs. :p...
[ "def", "update_import_errors", "(", "session", ",", "dagbag", ")", ":", "# Clear the errors of the processed files", "for", "dagbag_file", "in", "dagbag", ".", "file_last_changed", ":", "session", ".", "query", "(", "errors", ".", "ImportError", ")", ".", "filter", ...
44.26087
17.304348
def lsb_release(self, loglevel=logging.DEBUG): """Get distro information from lsb_release. """ # v the space is intentional, to avoid polluting bash history. shutit = self.shutit d = {} self.send(ShutItSendSpec(self, send=' command lsb_release -a', ...
[ "def", "lsb_release", "(", "self", ",", "loglevel", "=", "logging", ".", "DEBUG", ")", ":", "# v the space is intentional, to avoid polluting bash history.", "shutit", "=", "self", ".", "shutit", "d", "=", "{", "}", "self", ".", "send", "(", "ShutItSendSp...
36.964286
18.821429
def run(self, func, *func_args, **func__kwargs): """ Specify the function to run at the scheduled times :param func: a callable :param func_args: the args to the callable :param func__kwargs: the kwargs to the callable :return: """ self._func = func ...
[ "def", "run", "(", "self", ",", "func", ",", "*", "func_args", ",", "*", "*", "func__kwargs", ")", ":", "self", ".", "_func", "=", "func", "self", ".", "_func_args", "=", "func_args", "self", ".", "_func_kwargs", "=", "func__kwargs", "return", "self" ]
30.846154
12.692308
def get(self, request, bot_id, id, format=None): """ Get list of Messenger recipients of a hook --- serializer: MessengerRecipientSerializer responseMessages: - code: 401 message: Not authenticated """ return super(MessengerRecipientList,...
[ "def", "get", "(", "self", ",", "request", ",", "bot_id", ",", "id", ",", "format", "=", "None", ")", ":", "return", "super", "(", "MessengerRecipientList", ",", "self", ")", ".", "get", "(", "request", ",", "bot_id", ",", "id", ",", "format", ")" ]
35
13
def ConvCnstrMODOptions(opt=None, method='fista'): """A wrapper function that dynamically defines a class derived from the Options class associated with one of the implementations of the Convolutional Constrained MOD problem, and returns an object instantiated with the provided parameters. The wrapper i...
[ "def", "ConvCnstrMODOptions", "(", "opt", "=", "None", ",", "method", "=", "'fista'", ")", ":", "# Assign base class depending on method selection argument", "base", "=", "ccmod_class_label_lookup", "(", "method", ")", ".", "Options", "# Nested class with dynamically determ...
45.56
19.8
def search(self, resource, resource_class, search_filter=None, dmql_query=None, limit=9999999, offset=0, optional_parameters=None, auto_offset=True, query_type='DMQL2', standard_names=0, response_format='COMPACT-DECODED'): """ Preform a search on the RETS board :par...
[ "def", "search", "(", "self", ",", "resource", ",", "resource_class", ",", "search_filter", "=", "None", ",", "dmql_query", "=", "None", ",", "limit", "=", "9999999", ",", "offset", "=", "0", ",", "optional_parameters", "=", "None", ",", "auto_offset", "="...
44.052632
25.657895
def check_in_out_dates(self): """ When date_order is less then check-in date or Checkout date should be greater than the check-in date. """ if self.checkout and self.checkin: if self.checkin < self.date_order: raise ValidationError(_('Check-in date sho...
[ "def", "check_in_out_dates", "(", "self", ")", ":", "if", "self", ".", "checkout", "and", "self", ".", "checkin", ":", "if", "self", ".", "checkin", "<", "self", ".", "date_order", ":", "raise", "ValidationError", "(", "_", "(", "'Check-in date should be gre...
48.083333
14.75
def capture_usb_device(self, id_p, capture_filename): """Requests a capture of the given host USB device. When the request is completed, the VM process will get a :py:func:`IInternalSessionControl.on_usb_device_attach` notification. in id_p of type str in capture_filen...
[ "def", "capture_usb_device", "(", "self", ",", "id_p", ",", "capture_filename", ")", ":", "if", "not", "isinstance", "(", "id_p", ",", "basestring", ")", ":", "raise", "TypeError", "(", "\"id_p can only be an instance of type basestring\"", ")", "if", "not", "isin...
40.882353
19.705882
def invert_dict(dict_, unique_vals=True): r""" Swaps the keys and values in a dictionary. Args: dict_ (dict): dictionary to invert unique_vals (bool): if False, inverted keys are returned in a set. The default is True. Returns: dict: inverted Notes: The...
[ "def", "invert_dict", "(", "dict_", ",", "unique_vals", "=", "True", ")", ":", "if", "unique_vals", ":", "if", "isinstance", "(", "dict_", ",", "OrderedDict", ")", ":", "inverted", "=", "OrderedDict", "(", "(", "val", ",", "key", ")", "for", "key", ","...
32.490566
20.018868
def clear(self) -> None: """ Clears out the tracked metrics, but keeps the patience and should_decrease settings. """ self._best_so_far = None self._epochs_with_no_improvement = 0 self._is_best_so_far = True self._epoch_number = 0 self.best_epoch = None
[ "def", "clear", "(", "self", ")", "->", "None", ":", "self", ".", "_best_so_far", "=", "None", "self", ".", "_epochs_with_no_improvement", "=", "0", "self", ".", "_is_best_so_far", "=", "True", "self", ".", "_epoch_number", "=", "0", "self", ".", "best_epo...
34.333333
11.666667
def parse(chord): """ Parse a string to get chord component :param str chord: str expression of a chord :rtype: (str, pychord.Quality, str, str) :return: (root, quality, appended, on) """ if len(chord) > 1 and chord[1] in ("b", "#"): root = chord[:2] rest = chord[2:] else: ...
[ "def", "parse", "(", "chord", ")", ":", "if", "len", "(", "chord", ")", ">", "1", "and", "chord", "[", "1", "]", "in", "(", "\"b\"", ",", "\"#\"", ")", ":", "root", "=", "chord", "[", ":", "2", "]", "rest", "=", "chord", "[", "2", ":", "]",...
29.285714
14.928571
def set_fixed_capabils(self, capabils): """set keys of capabils into fields of object :capabils: dict """ self.ess = capabils['ess'] self.ibss = capabils['ibss'] self.priv = capabils['priv'] self.short_preamble = capabils['short_preamble'] self.pbcc = capa...
[ "def", "set_fixed_capabils", "(", "self", ",", "capabils", ")", ":", "self", ".", "ess", "=", "capabils", "[", "'ess'", "]", "self", ".", "ibss", "=", "capabils", "[", "'ibss'", "]", "self", ".", "priv", "=", "capabils", "[", "'priv'", "]", "self", "...
40.235294
5.882353
def checkOutputPath(self, output_path): """ Create or clean up output path """ if not output_path: # output_path = self.output_path_DEFAULT output_path = os.path.join(self.output_path_DEFAULT, slugify(unicode(self.title))) ...
[ "def", "checkOutputPath", "(", "self", ",", "output_path", ")", ":", "if", "not", "output_path", ":", "# output_path = self.output_path_DEFAULT", "output_path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "output_path_DEFAULT", ",", "slugify", "(", "u...
37.083333
8.75
def get_response(self): """ Get a response from the chatbot and display it. """ user_input = self.usr_input.get() self.usr_input.delete(0, tk.END) response = self.chatbot.get_response(user_input) self.conversation['state'] = 'normal' self.conversation.in...
[ "def", "get_response", "(", "self", ")", ":", "user_input", "=", "self", ".", "usr_input", ".", "get", "(", ")", "self", ".", "usr_input", ".", "delete", "(", "0", ",", "tk", ".", "END", ")", "response", "=", "self", ".", "chatbot", ".", "get_respons...
30.3125
17.9375
def voigt_symmetrized(self): """ Returns a "voigt"-symmetrized tensor, i. e. a voigt-notation tensor such that it is invariant wrt permutation of indices """ if not (self.rank % 2 == 0 and self.rank >= 2): raise ValueError("V-symmetrization requires rank even and >= 2...
[ "def", "voigt_symmetrized", "(", "self", ")", ":", "if", "not", "(", "self", ".", "rank", "%", "2", "==", "0", "and", "self", ".", "rank", ">=", "2", ")", ":", "raise", "ValueError", "(", "\"V-symmetrization requires rank even and >= 2\"", ")", "v", "=", ...
43.583333
20.083333
def import_from_path(path): """ Import and return the object at `path` if it exists. Raises an :exc:`ImportError` if the object is not found. """ if path is None: return obj = locate(path) if obj is None: raise ImportError( "`{}` could not be imported".format(path) ...
[ "def", "import_from_path", "(", "path", ")", ":", "if", "path", "is", "None", ":", "return", "obj", "=", "locate", "(", "path", ")", "if", "obj", "is", "None", ":", "raise", "ImportError", "(", "\"`{}` could not be imported\"", ".", "format", "(", "path", ...
22.066667
21.466667
def action_update_library_location(_location): """ Sets the folder that contains models for the local library @todo: add options to move things over etc.. note: this is called from 'manager' """ # if not(os.path.exists(_location)): # os.mkdir(_location) # printDebug("Creating...
[ "def", "action_update_library_location", "(", "_location", ")", ":", "# if not(os.path.exists(_location)):\r", "# \tos.mkdir(_location)\r", "# \tprintDebug(\"Creating new folder..\", \"comment\")\r", "printDebug", "(", "\"Old location: '%s'\"", "%", "get_home_location", "(", ")", ","...
31.344828
17.068966
def execute_catch(c, sql, vars=None): """Run a query, but ignore any errors. For error recovery paths where the error handler should not raise another.""" try: c.execute(sql, vars) except Exception as err: cmd = sql.split(' ', 1)[0] log.error("Error executing %s: %s", cmd, err)
[ "def", "execute_catch", "(", "c", ",", "sql", ",", "vars", "=", "None", ")", ":", "try", ":", "c", ".", "execute", "(", "sql", ",", "vars", ")", "except", "Exception", "as", "err", ":", "cmd", "=", "sql", ".", "split", "(", "' '", ",", "1", ")"...
44
11.142857
def _substitute_file_uuids_throughout_template(self, template, file_dependencies): """Anywhere in "template" that refers to a data object but does not give a specific UUID, if a matching file can be found in "file_dependencies", we will change the data object reference to use that UUID. That wa...
[ "def", "_substitute_file_uuids_throughout_template", "(", "self", ",", "template", ",", "file_dependencies", ")", ":", "if", "not", "isinstance", "(", "template", ",", "dict", ")", ":", "# Nothing to do if this is a reference to a previously imported template.", "return", "...
62.785714
25.428571
def build_config(self, config): """Set config defaults""" for sec in 'LiSE', 'ELiDE': config.adddefaultsection(sec) config.setdefaults( 'LiSE', { 'world': 'sqlite:///LiSEworld.db', 'language': 'eng', 'logfile': '...
[ "def", "build_config", "(", "self", ",", "config", ")", ":", "for", "sec", "in", "'LiSE'", ",", "'ELiDE'", ":", "config", ".", "adddefaultsection", "(", "sec", ")", "config", ".", "setdefaults", "(", "'LiSE'", ",", "{", "'world'", ":", "'sqlite:///LiSEworl...
38.357143
15.666667
def quantize( self, input=None, qout=False, cutoff=0, retrain=False, epoch=None, lr=None, thread=None, verbose=None, dsub=2, qnorm=False ): """ Quantize the model reducing the size of the model and it's m...
[ "def", "quantize", "(", "self", ",", "input", "=", "None", ",", "qout", "=", "False", ",", "cutoff", "=", "0", ",", "retrain", "=", "False", ",", "epoch", "=", "None", ",", "lr", "=", "None", ",", "thread", "=", "None", ",", "verbose", "=", "None...
24.205882
18.911765
def read_profile(name): """Get a named profile from the CONFIG_FILE. Args: name The name of the profile to load. Returns: A dictionary with the profile's ``repo`` and ``token`` values. """ config = configparser.ConfigParser() config.read(CONFIG_FILE) profile =...
[ "def", "read_profile", "(", "name", ")", ":", "config", "=", "configparser", ".", "ConfigParser", "(", ")", "config", ".", "read", "(", "CONFIG_FILE", ")", "profile", "=", "config", "[", "name", "]", "repo", "=", "profile", "[", "\"repo\"", "]", "token",...
23
19.5
def truncate_to_string(num, precision=0): """Deprecated, todo: remove references from subclasses""" if precision > 0: parts = ('{0:.%df}' % precision).format(Decimal(num)).split('.') decimal_digits = parts[1][:precision].rstrip('0') decimal_digits = decimal_digits if ...
[ "def", "truncate_to_string", "(", "num", ",", "precision", "=", "0", ")", ":", "if", "precision", ">", "0", ":", "parts", "=", "(", "'{0:.%df}'", "%", "precision", ")", ".", "format", "(", "Decimal", "(", "num", ")", ")", ".", "split", "(", "'.'", ...
52.5
16.375
def generate(self, x, **kwargs): """ Return a tensor that constructs adversarial examples for the given input. Generate uses tf.py_func in order to operate over tensors. :param x: A tensor with the inputs. :param kwargs: See `parse_params` """ assert self.sess is not None, \ 'Cannot...
[ "def", "generate", "(", "self", ",", "x", ",", "*", "*", "kwargs", ")", ":", "assert", "self", ".", "sess", "is", "not", "None", ",", "'Cannot use `generate` when no `sess` was provided'", "self", ".", "parse_params", "(", "*", "*", "kwargs", ")", "labels", ...
36.071429
20.428571
def _get_snapshot(name, suffix, blade): ''' Return name of Snapshot or None ''' try: filt = 'source=\'{}\' and suffix=\'{}\''.format(name, suffix) res = blade.file_system_snapshots.list_file_system_snapshots(filter=filt) return res.items[0] except rest.ApiException: ...
[ "def", "_get_snapshot", "(", "name", ",", "suffix", ",", "blade", ")", ":", "try", ":", "filt", "=", "'source=\\'{}\\' and suffix=\\'{}\\''", ".", "format", "(", "name", ",", "suffix", ")", "res", "=", "blade", ".", "file_system_snapshots", ".", "list_file_sys...
29.454545
23.272727
def find(self, asset_id, query=None, **kwargs): """ Gets a single asset by ID. """ if query is None: query = {} normalize_select(query) return super(AssetsProxy, self).find(asset_id, query=query, **kwargs)
[ "def", "find", "(", "self", ",", "asset_id", ",", "query", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "query", "is", "None", ":", "query", "=", "{", "}", "normalize_select", "(", "query", ")", "return", "super", "(", "AssetsProxy", ",", ...
23.454545
19.272727
def f_set_single(self, name, item): """Adds a single data item to the pickle result. Note that it is NOT checked if the item can be pickled! """ if self.v_stored: self._logger.debug('You are changing an already stored result. If ' 'you not...
[ "def", "f_set_single", "(", "self", ",", "name", ",", "item", ")", ":", "if", "self", ".", "v_stored", ":", "self", ".", "_logger", ".", "debug", "(", "'You are changing an already stored result. If '", "'you not explicitly overwrite the data on disk, this change '", "'...
37.625
27.0625
def wrap_tuple_streams(unwrapped, kdims, streams): """ Fills in tuple keys with dimensioned stream values as appropriate. """ param_groups = [(s.contents.keys(), s) for s in streams] pairs = [(name,s) for (group, s) in param_groups for name in group] substituted = [] for pos,el in enumerate...
[ "def", "wrap_tuple_streams", "(", "unwrapped", ",", "kdims", ",", "streams", ")", ":", "param_groups", "=", "[", "(", "s", ".", "contents", ".", "keys", "(", ")", ",", "s", ")", "for", "s", "in", "streams", "]", "pairs", "=", "[", "(", "name", ",",...
42.4
13.2
def _replace_deferred(self, arg, context): """This replaces all deferred nodes (UnboundVariables and _DeferredLayers). If arg is a sequence or a dict, then it's deferred values are also replaced. Args: arg: The argument to replace. If a list or a dict, then all items are also replaced. ...
[ "def", "_replace_deferred", "(", "self", ",", "arg", ",", "context", ")", ":", "if", "isinstance", "(", "arg", ",", "UnboundVariable", ")", ":", "return", "context", "[", "arg", "]", "elif", "isinstance", "(", "arg", ",", "_DeferredLayer", ")", ":", "# p...
38.814815
16.666667
def get_predictions(genes): """Get sift predictions from genes.""" data = { 'sift_predictions': [], 'polyphen_predictions': [], 'region_annotations': [], 'functional_annotations': [] } for gene_obj in genes: for pred_key in data: gene_key = pred_key[:-...
[ "def", "get_predictions", "(", "genes", ")", ":", "data", "=", "{", "'sift_predictions'", ":", "[", "]", ",", "'polyphen_predictions'", ":", "[", "]", ",", "'region_annotations'", ":", "[", "]", ",", "'functional_annotations'", ":", "[", "]", "}", "for", "...
32.578947
16.368421
def new_crew_member(self, program, role, fullname, givenname, surname): """Callback run for each new crew member entry. 'fullname' is a derived full-name, based on the presence of 'givenname' and/or 'surname'. """ if self.__v_crew_member: # [Crew: EP000036710112, Ac...
[ "def", "new_crew_member", "(", "self", ",", "program", ",", "role", ",", "fullname", ",", "givenname", ",", "surname", ")", ":", "if", "self", ".", "__v_crew_member", ":", "# [Crew: EP000036710112, Actor, Estelle Parsons]", "print", "(", "\"[Crew: %s, %s, %s]\"", "%...
44.555556
19.888889
def setupSources(self, config): """Sets up source objects from the given config""" sources = config.get('sources', []) for source in sources: src = self.createSource(source) self.setupTriggers(source, src) self.sources.append(src)
[ "def", "setupSources", "(", "self", ",", "config", ")", ":", "sources", "=", "config", ".", "get", "(", "'sources'", ",", "[", "]", ")", "for", "source", "in", "sources", ":", "src", "=", "self", ".", "createSource", "(", "source", ")", "self", ".", ...
31.555556
12.444444
def findNestedUnions(self, lst): ''' Recursive helper function for finding nested unions. If this node is a class or struct it may have had a union added to its child list. When this occurred, the union was removed from ``self.unions`` in the :class:`~exhale.graph.ExhaleRoot` c...
[ "def", "findNestedUnions", "(", "self", ",", "lst", ")", ":", "if", "self", ".", "kind", "==", "\"union\"", ":", "lst", ".", "append", "(", "self", ")", "for", "c", "in", "self", ".", "children", ":", "c", ".", "findNestedUnions", "(", "lst", ")" ]
45.761905
26.333333
def resolve_dst(self, dst_dir, src): """ finds the destination based on source if source is an absolute path, and there's no pattern, it copies the file to base dst_dir """ if os.path.isabs(src): return os.path.join(dst_dir, os.path.basename(src)) return os.pa...
[ "def", "resolve_dst", "(", "self", ",", "dst_dir", ",", "src", ")", ":", "if", "os", ".", "path", ".", "isabs", "(", "src", ")", ":", "return", "os", ".", "path", ".", "join", "(", "dst_dir", ",", "os", ".", "path", ".", "basename", "(", "src", ...
41.75
12.5
def profile_function(self): """Runs cProfile on a function.""" prof = cProfile.Profile() prof.enable() result = self._run_object(*self._run_args, **self._run_kwargs) prof.disable() prof_stats = pstats.Stats(prof) prof_stats.calc_callees() return { ...
[ "def", "profile_function", "(", "self", ")", ":", "prof", "=", "cProfile", ".", "Profile", "(", ")", "prof", ".", "enable", "(", ")", "result", "=", "self", ".", "_run_object", "(", "*", "self", ".", "_run_args", ",", "*", "*", "self", ".", "_run_kwa...
37.117647
12.411765
def run_command(self, commands, timeout_sec=None, exception=None): """ Executes the given commands and sends OVSDB messages. ``commands`` must be a list of :py:mod:`ryu.lib.ovs.vsctl.VSCtlCommand`. If ``timeout_sec`` is specified, raises exception after the given timeou...
[ "def", "run_command", "(", "self", ",", "commands", ",", "timeout_sec", "=", "None", ",", "exception", "=", "None", ")", ":", "if", "timeout_sec", "is", "None", ":", "self", ".", "_run_command", "(", "commands", ")", "else", ":", "with", "hub", ".", "T...
37.842105
20.052632
def list_fence(self, filename): '''list fence points, optionally saving to a file''' self.fenceloader.clear() count = self.get_mav_param('FENCE_TOTAL', 0) if count == 0: print("No geo-fence points") return for i in range(int(count)): p = self.f...
[ "def", "list_fence", "(", "self", ",", "filename", ")", ":", "self", ".", "fenceloader", ".", "clear", "(", ")", "count", "=", "self", ".", "get_mav_param", "(", "'FENCE_TOTAL'", ",", "0", ")", "if", "count", "==", "0", ":", "print", "(", "\"No geo-fen...
39.9375
15.125
def add_defs(self, variable, locations, size_threshold=32): """ Add a collection of new definitions of a variable. :param SimVariable variable: The variable being defined. :param iterable locations: A collection of locations where the variable was defined. :param int size_thresh...
[ "def", "add_defs", "(", "self", ",", "variable", ",", "locations", ",", "size_threshold", "=", "32", ")", ":", "new_defs_added", "=", "False", "for", "loc", "in", "locations", ":", "new_defs_added", "|=", "self", ".", "add_def", "(", "variable", ",", "loc"...
37.882353
26.235294
def init(args=None, lib='standard'): """Intialize the rabit module, call this once before using anything. Parameters ---------- args: list of str, optional The list of arguments used to initialized the rabit usually you need to pass in sys.argv. Defaults to sys.argv when it is N...
[ "def", "init", "(", "args", "=", "None", ",", "lib", "=", "'standard'", ")", ":", "if", "args", "is", "None", ":", "args", "=", "sys", ".", "argv", "_loadlib", "(", "lib", ")", "arr", "=", "(", "ctypes", ".", "c_char_p", "*", "len", "(", "args", ...
30.555556
12.722222
def pow(cls, x: 'TensorFluent', y: 'TensorFluent') -> 'TensorFluent': '''Returns a TensorFluent for the pow function.TensorFluent Args: x: The first operand. y: The second operand. Returns: A TensorFluent wrapping the pow function. ''' return...
[ "def", "pow", "(", "cls", ",", "x", ":", "'TensorFluent'", ",", "y", ":", "'TensorFluent'", ")", "->", "'TensorFluent'", ":", "return", "cls", ".", "_binary_op", "(", "x", ",", "y", ",", "tf", ".", "pow", ",", "tf", ".", "float32", ")" ]
31.909091
23.363636
def inspect_image(self, image_id): """ return detailed metadata about provided image (see 'man docker-inspect') :param image_id: str or ImageName, id or name of the image :return: dict """ logger.info("inspecting image '%s'", image_id) logger.debug("image_id = '%...
[ "def", "inspect_image", "(", "self", ",", "image_id", ")", ":", "logger", ".", "info", "(", "\"inspecting image '%s'\"", ",", "image_id", ")", "logger", ".", "debug", "(", "\"image_id = '%s'\"", ",", "image_id", ")", "if", "isinstance", "(", "image_id", ",", ...
37.923077
14.076923
def in_scope(self, exclude_scopes=None, include_scopes=None): """Whether this scope should be included by the given inclusion and exclusion rules. :param Scope exclude_scopes: An optional Scope containing scope names to exclude. None (the default value) indicates that no filtering should be done based on...
[ "def", "in_scope", "(", "self", ",", "exclude_scopes", "=", "None", ",", "include_scopes", "=", "None", ")", ":", "if", "include_scopes", "is", "not", "None", "and", "not", "isinstance", "(", "include_scopes", ",", "Scope", ")", ":", "raise", "ValueError", ...
54.625
32.416667
def release_apply(ui, repo, clname, **opts): """apply a CL to the release branch Creates a new CL copying a previously committed change from the main branch to the release branch. The current client must either be clean or already be in the release branch. The release branch must be created by starting with a ...
[ "def", "release_apply", "(", "ui", ",", "repo", ",", "clname", ",", "*", "*", "opts", ")", ":", "c", "=", "repo", "[", "None", "]", "if", "not", "releaseBranch", ":", "raise", "hg_util", ".", "Abort", "(", "\"no active release branches\"", ")", "if", "...
27.709091
20.327273
def load_global_settings(): """Loads settings file containing paths to dependencies and other optional configuration elements.""" with open(settings_path, 'r') as settings_f: global global_settings settings_json = json.loads(settings_f.read()) if global_settings is None: glob...
[ "def", "load_global_settings", "(", ")", ":", "with", "open", "(", "settings_path", ",", "'r'", ")", "as", "settings_f", ":", "global", "global_settings", "settings_json", "=", "json", ".", "loads", "(", "settings_f", ".", "read", "(", ")", ")", "if", "glo...
43.142857
9.785714
def compile(self, cost, name_scope="train"): """Compile the optimizer with the given training parameters. Parameters ---------- cost : Tensor A Tensor containing the value to minimize. name_scope : str , optional (default="train") Optional name scope for ...
[ "def", "compile", "(", "self", ",", "cost", ",", "name_scope", "=", "\"train\"", ")", ":", "with", "tf", ".", "name_scope", "(", "name_scope", ")", ":", "return", "self", ".", "opt_", ".", "minimize", "(", "cost", ")" ]
35.75
13.166667
def create_index(manager, prop, node_type='Node'): """ :param manager: Neo4jDBSessionManager :param prop: Property to index :param node_type: Label to create index on :type manager: Neo4jDBSessionManager :type prop: str :type node_type: str """ with manager.session as s: s.r...
[ "def", "create_index", "(", "manager", ",", "prop", ",", "node_type", "=", "'Node'", ")", ":", "with", "manager", ".", "session", "as", "s", ":", "s", ".", "run", "(", "'CREATE INDEX ON :{node_type}({prop})'", ".", "format", "(", "node_type", "=", "node_type...
32.5
13.5
def generate_api_resources(): """Generate the Blockade API endpoints.""" client = boto3.client('apigateway', region_name=PRIMARY_REGION) matches = [x for x in client.get_rest_apis().get('items', list()) if x['name'] == API_GATEWAY] match = matches.pop() iam = boto3.resource('iam') ...
[ "def", "generate_api_resources", "(", ")", ":", "client", "=", "boto3", ".", "client", "(", "'apigateway'", ",", "region_name", "=", "PRIMARY_REGION", ")", "matches", "=", "[", "x", "for", "x", "in", "client", ".", "get_rest_apis", "(", ")", ".", "get", ...
42.019231
21.096154
def get_homology_models(self): """DictList: Return a DictList of all homology models in self.structures""" # TODO: change to a property? if self.representative_structure: return DictList(x for x in self.structures if not x.is_experimental and x.id != self.representative_structure.id)...
[ "def", "get_homology_models", "(", "self", ")", ":", "# TODO: change to a property?", "if", "self", ".", "representative_structure", ":", "return", "DictList", "(", "x", "for", "x", "in", "self", ".", "structures", "if", "not", "x", ".", "is_experimental", "and"...
58.428571
23.714286
def reshape_like(a, b): """Reshapes a to match the shape of b in all but the last dimension.""" ret = tf.reshape(a, tf.concat([tf.shape(b)[:-1], tf.shape(a)[-1:]], 0)) if not tf.executing_eagerly(): ret.set_shape(b.get_shape().as_list()[:-1] + a.get_shape().as_list()[-1:]) return ret
[ "def", "reshape_like", "(", "a", ",", "b", ")", ":", "ret", "=", "tf", ".", "reshape", "(", "a", ",", "tf", ".", "concat", "(", "[", "tf", ".", "shape", "(", "b", ")", "[", ":", "-", "1", "]", ",", "tf", ".", "shape", "(", "a", ")", "[", ...
48.5
20.666667
def make_value_from_datastore(self, value): """Convert value from datastore representation. Args: value: datastore value. Returns: value to store in the model. """ if value is None: return None _json = json.loads(value, cls=JsonDecoder) if self.data_type == dict: r...
[ "def", "make_value_from_datastore", "(", "self", ",", "value", ")", ":", "if", "value", "is", "None", ":", "return", "None", "_json", "=", "json", ".", "loads", "(", "value", ",", "cls", "=", "JsonDecoder", ")", "if", "self", ".", "data_type", "==", "d...
22.4375
17.5625
def list_to_string(input, delimiter): """converts list to string recursively so that nested lists are supported :param input: a list of strings and lists of strings (and so on recursive) :type input: list :param delimiter: the deimiter to use when joining the items :type delimiter: str :returns...
[ "def", "list_to_string", "(", "input", ",", "delimiter", ")", ":", "if", "isinstance", "(", "input", ",", "list", ")", ":", "return", "delimiter", ".", "join", "(", "list_to_string", "(", "item", ",", "delimiter", ")", "for", "item", "in", "input", ")", ...
35.928571
16.5
def _prep_message(self): """Performs initial message setup. :raises MasterKeyProviderError: if primary master key is not a member of supplied MasterKeyProvider :raises MasterKeyProviderError: if no Master Keys are returned from key_provider """ message_id = aws_encryption_sdk.in...
[ "def", "_prep_message", "(", "self", ")", ":", "message_id", "=", "aws_encryption_sdk", ".", "internal", ".", "utils", ".", "message_id", "(", ")", "try", ":", "plaintext_length", "=", "self", ".", "stream_length", "except", "NotSupportedError", ":", "plaintext_...
44.630769
24.676923
def get_base_image_info(self): """ query docker about base image :return dict """ if self.base_from_scratch: return logger.info("getting information about base image '%s'", self.base_image) image_info = self.tasker.get_image_info_by_image_name(self.ba...
[ "def", "get_base_image_info", "(", "self", ")", ":", "if", "self", ".", "base_from_scratch", ":", "return", "logger", ".", "info", "(", "\"getting information about base image '%s'\"", ",", "self", ".", "base_image", ")", "image_info", "=", "self", ".", "tasker", ...
43.095238
21.190476
def list(self, to=values.unset, from_=values.unset, parent_call_sid=values.unset, status=values.unset, start_time_before=values.unset, start_time=values.unset, start_time_after=values.unset, end_time_before=values.unset, end_time=values.unset, end_time_after=values.un...
[ "def", "list", "(", "self", ",", "to", "=", "values", ".", "unset", ",", "from_", "=", "values", ".", "unset", ",", "parent_call_sid", "=", "values", ".", "unset", ",", "status", "=", "values", ".", "unset", ",", "start_time_before", "=", "values", "."...
56.444444
27.911111
def get_musiclibrary(): lib_files = music_library.get_file_list(config.library_path) global lib lib = music_library.parse_library(lib_files) """:type :musiclibrary.MusicLibrary""" return lib
[ "def", "get_musiclibrary", "(", ")", ":", "lib_files", "=", "music_library", ".", "get_file_list", "(", "config", ".", "library_path", ")", "global", "lib", "lib", "=", "music_library", ".", "parse_library", "(", "lib_files", ")", "return", "lib" ]
34.166667
16.833333
def convert_bytes(bytes): """ Convert bytes into human readable """ bytes = float(bytes) if bytes >= 1099511627776: terabytes = bytes / 1099511627776 size = '%.2fT' % terabytes elif bytes >= 1073741824: gigabytes = bytes / 1073741824 size = '%.2fG' % gigabytes ...
[ "def", "convert_bytes", "(", "bytes", ")", ":", "bytes", "=", "float", "(", "bytes", ")", "if", "bytes", ">=", "1099511627776", ":", "terabytes", "=", "bytes", "/", "1099511627776", "size", "=", "'%.2fT'", "%", "terabytes", "elif", "bytes", ">=", "10737418...
27.2
9.6
def postponed_from(self): """ Date that the event was postponed from (in the local time zone). """ fromDate = getLocalDate(self.except_date, self.time_from, self.tz) return dateFormat(fromDate)
[ "def", "postponed_from", "(", "self", ")", ":", "fromDate", "=", "getLocalDate", "(", "self", ".", "except_date", ",", "self", ".", "time_from", ",", "self", ".", "tz", ")", "return", "dateFormat", "(", "fromDate", ")" ]
38
14.333333
def mfcc(wav_path): """ Grabs MFCC features with energy and derivates. """ (rate, sig) = wav.read(wav_path) feat = python_speech_features.mfcc(sig, rate, appendEnergy=True) delta_feat = python_speech_features.delta(feat, 2) all_feats = [feat, delta_feat] all_feats = np.array(all_feats) # Ma...
[ "def", "mfcc", "(", "wav_path", ")", ":", "(", "rate", ",", "sig", ")", "=", "wav", ".", "read", "(", "wav_path", ")", "feat", "=", "python_speech_features", ".", "mfcc", "(", "sig", ",", "rate", ",", "appendEnergy", "=", "True", ")", "delta_feat", "...
39.071429
15.642857
def protected_view(view, info): """allows adding `protected=True` to a view_config`""" if info.options.get('protected'): def wrapper_view(context, request): response = _advice(request) if response is not None: return response else: ret...
[ "def", "protected_view", "(", "view", ",", "info", ")", ":", "if", "info", ".", "options", ".", "get", "(", "'protected'", ")", ":", "def", "wrapper_view", "(", "context", ",", "request", ")", ":", "response", "=", "_advice", "(", "request", ")", "if",...
31.583333
11.25
def _adjust_rate_aggressive(self, real_wave_mfcc, algo_parameters): """ RATEAGGRESSIVE """ self.log(u"Called _adjust_rate_aggressive") self._apply_rate(max_rate=algo_parameters[0], aggressive=True)
[ "def", "_adjust_rate_aggressive", "(", "self", ",", "real_wave_mfcc", ",", "algo_parameters", ")", ":", "self", ".", "log", "(", "u\"Called _adjust_rate_aggressive\"", ")", "self", ".", "_apply_rate", "(", "max_rate", "=", "algo_parameters", "[", "0", "]", ",", ...
38.666667
14.333333
def rank_member_in( self, leaderboard_name, member, score, member_data=None): ''' Rank a member in the named leaderboard. @param leaderboard_name [String] Name of the leaderboard. @param member [String] Member name. @param score [float] Member score. @param m...
[ "def", "rank_member_in", "(", "self", ",", "leaderboard_name", ",", "member", ",", "score", ",", "member_data", "=", "None", ")", ":", "pipeline", "=", "self", ".", "redis_connection", ".", "pipeline", "(", ")", "if", "isinstance", "(", "self", ".", "redis...
37.047619
18
def image_search(auth=None, **kwargs): ''' Search for images CLI Example: .. code-block:: bash salt '*' glanceng.image_search name=image1 salt '*' glanceng.image_search ''' cloud = get_operator_cloud(auth) kwargs = _clean_kwargs(**kwargs) return cloud.search_images(**k...
[ "def", "image_search", "(", "auth", "=", "None", ",", "*", "*", "kwargs", ")", ":", "cloud", "=", "get_operator_cloud", "(", "auth", ")", "kwargs", "=", "_clean_kwargs", "(", "*", "*", "kwargs", ")", "return", "cloud", ".", "search_images", "(", "*", "...
22.357143
19.071429
def save_model(self, request, entry, form, change): """ Fill the content field with the interpretation of the placeholder """ context = RequestContext(request) try: content = render_placeholder(entry.content_placeholder, context) entry.content = co...
[ "def", "save_model", "(", "self", ",", "request", ",", "entry", ",", "form", ",", "change", ")", ":", "context", "=", "RequestContext", "(", "request", ")", "try", ":", "content", "=", "render_placeholder", "(", "entry", ".", "content_placeholder", ",", "c...
39.142857
13
def defer(callable): '''Defers execution of the callable to a thread. For example: >>> def foo(): ... print('bar') >>> join = defer(foo) >>> join() ''' t = threading.Thread(target=callable) t.start() return t.join
[ "def", "defer", "(", "callable", ")", ":", "t", "=", "threading", ".", "Thread", "(", "target", "=", "callable", ")", "t", ".", "start", "(", ")", "return", "t", ".", "join" ]
20.230769
21.769231
def get_graphics_control_ext(self, duration=0.1, dispose=2, transparent_flag=0, transparency_index=0): """ get_graphics_control_ext(duration=0.1, dispose=2) Graphics Control Extension. A sort of header at the start of each image. Specifies duration and transparancy. Dispose ---...
[ "def", "get_graphics_control_ext", "(", "self", ",", "duration", "=", "0.1", ",", "dispose", "=", "2", ",", "transparent_flag", "=", "0", ",", "transparency_index", "=", "0", ")", ":", "bb", "=", "'\\x21\\xF9\\x04'", "bb", "+=", "chr", "(", "(", "(", "di...
43.111111
25.185185
def _filter_meta_data(self, source, soup, data, url=None): """This method filters the web page content for meta tags that match patterns given in the ``FILTER_MAPS`` :param source: The key of the meta dictionary in ``FILTER_MAPS['meta']`` :type source: string :param soup: BeautifulSoup ...
[ "def", "_filter_meta_data", "(", "self", ",", "source", ",", "soup", ",", "data", ",", "url", "=", "None", ")", ":", "meta", "=", "FILTER_MAPS", "[", "'meta'", "]", "[", "source", "]", "meta_map", "=", "meta", "[", "'map'", "]", "html", "=", "soup", ...
38.887097
19.129032
def list_schemas(repo): """ Return a list of parsed avro schemas as dictionaries. :param Repo repo: The git repository. :returns: dict """ schema_files = glob.glob( os.path.join(repo.working_dir, '_schemas', '*.avsc')) schemas = {} for schema_file in schema_files: ...
[ "def", "list_schemas", "(", "repo", ")", ":", "schema_files", "=", "glob", ".", "glob", "(", "os", ".", "path", ".", "join", "(", "repo", ".", "working_dir", ",", "'_schemas'", ",", "'*.avsc'", ")", ")", "schemas", "=", "{", "}", "for", "schema_file", ...
28.6875
15.0625
def _addsub_offset_array(self, other, op): """ Add or subtract array-like of DateOffset objects Parameters ---------- other : Index, np.ndarray object-dtype containing pd.DateOffset objects op : {operator.add, operator.sub} Returns ------- ...
[ "def", "_addsub_offset_array", "(", "self", ",", "other", ",", "op", ")", ":", "assert", "op", "in", "[", "operator", ".", "add", ",", "operator", ".", "sub", "]", "if", "len", "(", "other", ")", "==", "1", ":", "return", "op", "(", "self", ",", ...
32.3
17.566667
def ekccnt(table): """ Return the number of distinct columns in a specified, currently loaded table. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekccnt_c.html :param table: Name of table. :type table: str :return: Count of distinct, currently loaded columns. :rtype: int ...
[ "def", "ekccnt", "(", "table", ")", ":", "table", "=", "stypes", ".", "stringToCharP", "(", "table", ")", "ccount", "=", "ctypes", ".", "c_int", "(", ")", "libspice", ".", "ekccnt_c", "(", "table", ",", "ctypes", ".", "byref", "(", "ccount", ")", ")"...
28.25
17.25
def get_vnetwork_dvs_output_vnetwork_dvs_host(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_vnetwork_dvs = ET.Element("get_vnetwork_dvs") config = get_vnetwork_dvs output = ET.SubElement(get_vnetwork_dvs, "output") vnetwork_dvs = ET...
[ "def", "get_vnetwork_dvs_output_vnetwork_dvs_host", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "get_vnetwork_dvs", "=", "ET", ".", "Element", "(", "\"get_vnetwork_dvs\"", ")", "config", "=", "ge...
40.307692
12.692308
def _fallback(self, section_name, pref_name): """ Create a fallback preference object, This is used when you have model instances that do not match any registered preferences, see #41 """ message = ( 'Creating a fallback preference with ' + 'sectio...
[ "def", "_fallback", "(", "self", ",", "section_name", ",", "pref_name", ")", ":", "message", "=", "(", "'Creating a fallback preference with '", "+", "'section \"{}\" and name \"{}\".'", "+", "'This means you have preferences in your database that '", "+", "'don\\'t match any r...
43.5
19.227273
def _set_src_host_ip(self, v, load=False): """ Setter method for src_host_ip, mapped from YANG variable /ipv6_acl/ipv6/access_list/extended/seq/src_host_ip (sip) If this variable is read-only (config: false) in the source YANG file, then _set_src_host_ip is considered as a private method. Backends l...
[ "def", "_set_src_host_ip", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", "v", ",", "ba...
100.409091
48.136364
def get(self): """ *get the ebook object* **Return:** - ``ebook`` **Usage:** See class docstring for usage """ self.log.debug('starting the ``get`` method') if self.format == "epub": if self.urlOrPath[:4] == "http" or self.u...
[ "def", "get", "(", "self", ")", ":", "self", ".", "log", ".", "debug", "(", "'starting the ``get`` method'", ")", "if", "self", ".", "format", "==", "\"epub\"", ":", "if", "self", ".", "urlOrPath", "[", ":", "4", "]", "==", "\"http\"", "or", "self", ...
25.255814
18.883721
def get_min_max_mag(self): "Return the minimum and maximum magnitudes" mag, num_bins = self._get_min_mag_and_num_bins() return mag, mag + self. bin_width * (num_bins - 1)
[ "def", "get_min_max_mag", "(", "self", ")", ":", "mag", ",", "num_bins", "=", "self", ".", "_get_min_mag_and_num_bins", "(", ")", "return", "mag", ",", "mag", "+", "self", ".", "bin_width", "*", "(", "num_bins", "-", "1", ")" ]
47.75
14.75
def fix_e713(self, result): """Fix (trivial case of) non-membership check.""" (line_index, offset, target) = get_index_offset_contents(result, self.source) # to convert once 'not in' -> 'in' before_target = target[:offset]...
[ "def", "fix_e713", "(", "self", ",", "result", ")", ":", "(", "line_index", ",", "offset", ",", "target", ")", "=", "get_index_offset_contents", "(", "result", ",", "self", ".", "source", ")", "# to convert once 'not in' -> 'in'", "before_target", "=", "target",...
46.677419
17.290323
def opacity( self ): """ Returns the 0-1 percentage opacity value for this node. :return <float> """ if self.isIsolateHidden(): return 0.1 opacity = super(XNode, self).opacity() layer = self.layer() if layer: r...
[ "def", "opacity", "(", "self", ")", ":", "if", "self", ".", "isIsolateHidden", "(", ")", ":", "return", "0.1", "opacity", "=", "super", "(", "XNode", ",", "self", ")", ".", "opacity", "(", ")", "layer", "=", "self", ".", "layer", "(", ")", "if", ...
24.6
15.933333
def setup_geoserver(options): from geonode.settings import INSTALLED_APPS, OGC_SERVER """Prepare a testing instance of GeoServer.""" # only start if using Geoserver backend _backend = os.environ.get('BACKEND', OGC_SERVER['default']['BACKEND']) if (_backend == 'geonode.qgis_server' or 'ge...
[ "def", "setup_geoserver", "(", "options", ")", ":", "from", "geonode", ".", "settings", "import", "INSTALLED_APPS", ",", "OGC_SERVER", "# only start if using Geoserver backend", "_backend", "=", "os", ".", "environ", ".", "get", "(", "'BACKEND'", ",", "OGC_SERVER", ...
31.205128
18.846154
def _backward_impl(self): """Actual implementation of the backward computation. The computation should take ``self._scores`` and ``self._labels`` and then compute the gradients with respect to the scores, store it as an `NDArray` in ``self._scores_grad``. Instead of defining a s...
[ "def", "_backward_impl", "(", "self", ")", ":", "if", "self", ".", "_grad_func", "is", "not", "None", ":", "grad", "=", "self", ".", "_grad_func", "(", "self", ".", "_scores", ",", "self", ".", "_labels", ")", "if", "not", "isinstance", "(", "grad", ...
46.235294
17.647059
def generate_look_up_table(): """ Generate look up table. :return: List """ poly = 0xA001 table = [] for index in range(256): data = index << 1 crc = 0 for _ in range(8, 0, -1): data >>= 1 if (data ^ crc) & 0x0001: crc = (crc >> ...
[ "def", "generate_look_up_table", "(", ")", ":", "poly", "=", "0xA001", "table", "=", "[", "]", "for", "index", "in", "range", "(", "256", ")", ":", "data", "=", "index", "<<", "1", "crc", "=", "0", "for", "_", "in", "range", "(", "8", ",", "0", ...
18.904762
19.095238
def translation_generator( variant_sequences, reference_contexts, min_transcript_prefix_length, max_transcript_mismatches, include_mismatches_after_variant, protein_sequence_length=None): """ Given all detected VariantSequence objects for a particular variant ...
[ "def", "translation_generator", "(", "variant_sequences", ",", "reference_contexts", ",", "min_transcript_prefix_length", ",", "max_transcript_mismatches", ",", "include_mismatches_after_variant", ",", "protein_sequence_length", "=", "None", ")", ":", "for", "reference_context"...
41.705882
20.568627
def get_file(path, s3_bucket=None): """Gets a file""" bucket_name = s3_bucket or oz.settings["s3_bucket"] if bucket_name: bucket = get_bucket(bucket_name) key = bucket.get_key(path) if not key: key = bucket.new_key(path) return S3File(key) else: retu...
[ "def", "get_file", "(", "path", ",", "s3_bucket", "=", "None", ")", ":", "bucket_name", "=", "s3_bucket", "or", "oz", ".", "settings", "[", "\"s3_bucket\"", "]", "if", "bucket_name", ":", "bucket", "=", "get_bucket", "(", "bucket_name", ")", "key", "=", ...
27.230769
16.384615
def gen(mimetype): """``gen`` is a decorator factory function, you just need to set a mimetype before using:: @app.route('/') @gen('') def index(): pass A full demo for creating a image stream is available on `GitHub <https://github.com/kxxoling/flask-video-streamin...
[ "def", "gen", "(", "mimetype", ")", ":", "def", "streaming", "(", "func", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "@", "wraps", "(", "func", ")", "def", "_", "(", ")", ":", "return", "Response", "(", "func", "(", "*", "args", ",", ...
28.052632
18.421053
def _zfs_image_create(vm_name, pool, disk_name, hostname_property_name, sparse_volume, disk_size, disk_image_name): ''' Clones an existing image, or creates a new one. When cl...
[ "def", "_zfs_image_create", "(", "vm_name", ",", "pool", ",", "disk_name", ",", "hostname_property_name", ",", "sparse_volume", ",", "disk_size", ",", "disk_image_name", ")", ":", "if", "not", "disk_image_name", "and", "not", "disk_size", ":", "raise", "CommandExe...
35.820896
17.701493
def sys_writev(self, fd, iov, count): """ Works just like C{sys_write} except that multiple buffers are written out. :rtype: int :param fd: the file descriptor of the file to write. :param iov: the buffer where the the bytes to write are taken. :param count: amount of C{...
[ "def", "sys_writev", "(", "self", ",", "fd", ",", "iov", ",", "count", ")", ":", "cpu", "=", "self", ".", "current", "ptrsize", "=", "cpu", ".", "address_bit_size", "sizeof_iovec", "=", "2", "*", "(", "ptrsize", "//", "8", ")", "total", "=", "0", "...
38.7
19.9
def validate(model:nn.Module, dl:DataLoader, loss_func:OptLossFunc=None, cb_handler:Optional[CallbackHandler]=None, pbar:Optional[PBar]=None, average=True, n_batch:Optional[int]=None)->Iterator[Tuple[Union[Tensor,int],...]]: "Calculate `loss_func` of `model` on `dl` in evaluation mode." model.eval(...
[ "def", "validate", "(", "model", ":", "nn", ".", "Module", ",", "dl", ":", "DataLoader", ",", "loss_func", ":", "OptLossFunc", "=", "None", ",", "cb_handler", ":", "Optional", "[", "CallbackHandler", "]", "=", "None", ",", "pbar", ":", "Optional", "[", ...
59.888889
25.777778
def export_profile(self): """ Export minimum needs to a json file. This method will save the current state of the minimum needs setup. Then open a dialog allowing the user to browse to the desired destination location and allow the user to save the needs as a json file. ...
[ "def", "export_profile", "(", "self", ")", ":", "file_name_dialog", "=", "QFileDialog", "(", "self", ")", "file_name_dialog", ".", "setAcceptMode", "(", "QFileDialog", ".", "AcceptSave", ")", "file_name_dialog", ".", "setNameFilter", "(", "self", ".", "tr", "(",...
45.588235
18.823529
def from_classes(cls, im_model_cls, im_model_config, expl_dims, sm_model_cls, sm_model_config, inf_dims, m_mins, m_maxs, s_mins, s_maxs, n_bootstrap=0, context_mode=None): """Initialize agent class :param class im_model_cls: a subclass of InterestedMod...
[ "def", "from_classes", "(", "cls", ",", "im_model_cls", ",", "im_model_config", ",", "expl_dims", ",", "sm_model_cls", ",", "sm_model_config", ",", "inf_dims", ",", "m_mins", ",", "m_maxs", ",", "s_mins", ",", "s_maxs", ",", "n_bootstrap", "=", "0", ",", "co...
47.206897
40.103448
def generate_docs(self, clspath, more_content): """Generate documentation for this configman class""" obj = import_class(clspath) sourcename = 'docstring of %s' % clspath all_options = [] indent = ' ' config = obj.get_required_config() if config.options: ...
[ "def", "generate_docs", "(", "self", ",", "clspath", ",", "more_content", ")", ":", "obj", "=", "import_class", "(", "clspath", ")", "sourcename", "=", "'docstring of %s'", "%", "clspath", "all_options", "=", "[", "]", "indent", "=", "' '", "config", "=",...
41.22619
18.309524
def plot_margins(*, fig=None, inches=1., centers=True, edges=True): """Add lines onto a figure indicating the margins, centers, and edges. Useful for ensuring your figure design scripts work as intended, and for laying out figures. Parameters ---------- fig : matplotlib.figure.Figure object (o...
[ "def", "plot_margins", "(", "*", ",", "fig", "=", "None", ",", "inches", "=", "1.", ",", "centers", "=", "True", ",", "edges", "=", "True", ")", ":", "if", "fig", "is", "None", ":", "fig", "=", "plt", ".", "gcf", "(", ")", "size", "=", "fig", ...
40.035714
22.803571
def surface(func, umin=0, umax=2 * np.pi, ucount=64, urepeat=1.0, vmin=0, vmax=2 * np.pi, vcount=64, vrepeat=1.0): """ Computes the parameterization of a parametric surface func: function(u,v) Parametric function used to build the surface """ vtype = [('position', np.float32, 3...
[ "def", "surface", "(", "func", ",", "umin", "=", "0", ",", "umax", "=", "2", "*", "np", ".", "pi", ",", "ucount", "=", "64", ",", "urepeat", "=", "1.0", ",", "vmin", "=", "0", ",", "vmax", "=", "2", "*", "np", ".", "pi", ",", "vcount", "=",...
32.914894
16.787234
def make_tsmap_plots(self, maps, roi=None, **kwargs): """Make plots from the output of `~fermipy.gtanalysis.GTAnalysis.tsmap` or `~fermipy.gtanalysis.GTAnalysis.tscube`. This method generates a 2D sky map for the best-fit test source in sqrt(TS) and Npred. Parameters ...
[ "def", "make_tsmap_plots", "(", "self", ",", "maps", ",", "roi", "=", "None", ",", "*", "*", "kwargs", ")", ":", "kwargs", ".", "setdefault", "(", "'graticule_radii'", ",", "self", ".", "config", "[", "'graticule_radii'", "]", ")", "kwargs", ".", "setdef...
40.738095
17.892857
def infer_timedelta_units(deltas): """Given an array of timedeltas, returns a CF compatible time-unit from {'days', 'hours', 'minutes' 'seconds'} (the first one that can evenly divide all unique time deltas in `deltas`) """ deltas = pd.to_timedelta(np.asarray(deltas).ravel(), box=False) unique_t...
[ "def", "infer_timedelta_units", "(", "deltas", ")", ":", "deltas", "=", "pd", ".", "to_timedelta", "(", "np", ".", "asarray", "(", "deltas", ")", ".", "ravel", "(", ")", ",", "box", "=", "False", ")", "unique_timedeltas", "=", "np", ".", "unique", "(",...
48.555556
15
def from_local_repository(repository_path, refspec=None): """ Retrieves the git context from a local git repository. :param repository_path: Path to the git repository to retrieve the context from :param refspec: The commit(s) to retrieve """ context = GitContext() # If...
[ "def", "from_local_repository", "(", "repository_path", ",", "refspec", "=", "None", ")", ":", "context", "=", "GitContext", "(", ")", "# If no refspec is defined, fallback to the last commit on the current branch", "if", "refspec", "is", "None", ":", "# We tried many thing...
52.222222
35.4
def as_list(self): """ Return an *ordered* list of the source attributes """ self._sanitise() l = [] for name in self.names: l.append(getattr(self, name)) return l
[ "def", "as_list", "(", "self", ")", ":", "self", ".", "_sanitise", "(", ")", "l", "=", "[", "]", "for", "name", "in", "self", ".", "names", ":", "l", ".", "append", "(", "getattr", "(", "self", ",", "name", ")", ")", "return", "l" ]
24.777778
12.777778
def handle_keypress(self): """When hitting tab, it handles if single or double tab""" if self.numpress == 2: self.sig_double_tab_pressed.emit(True) self.numpress = 0
[ "def", "handle_keypress", "(", "self", ")", ":", "if", "self", ".", "numpress", "==", "2", ":", "self", ".", "sig_double_tab_pressed", ".", "emit", "(", "True", ")", "self", ".", "numpress", "=", "0" ]
40.2
9.6
def ib64_patched(self, attrsD, contentparams): """ Patch isBase64 to prevent Base64 encoding of JSON content """ if attrsD.get("mode", "") == "base64": return 0 if self.contentparams["type"].startswith("text/"): return 0 if self.contentparams["type"].endswith("+xml"): return ...
[ "def", "ib64_patched", "(", "self", ",", "attrsD", ",", "contentparams", ")", ":", "if", "attrsD", ".", "get", "(", "\"mode\"", ",", "\"\"", ")", "==", "\"base64\"", ":", "return", "0", "if", "self", ".", "contentparams", "[", "\"type\"", "]", ".", "st...
32.857143
14.571429
def match(self, subj=None, pred=None, obj=None, attrs=None): ''' Retrieve an iterator of relationship IDs that match a pattern of components subj - optional subject or origin of the relationship, an IRI coded as a unicode object. If omitted any subject will be matched. pred - optional p...
[ "def", "match", "(", "self", ",", "subj", "=", "None", ",", "pred", "=", "None", ",", "obj", "=", "None", ",", "attrs", "=", "None", ")", ":", "cur", "=", "self", ".", "_conn", ".", "cursor", "(", ")", "conditions", "=", "u\"\"", "and_placeholder",...
71.283019
47.584906
def _get_identical_contigs(self, hits_dict): '''Input is a dict: key=contig name. Value = set of contigs that contain the key. Returns a list of sets of contigs that are equivalent''' equivalent_contigs = [] for qry_name, containing in hits_dict.items(): equi...
[ "def", "_get_identical_contigs", "(", "self", ",", "hits_dict", ")", ":", "equivalent_contigs", "=", "[", "]", "for", "qry_name", ",", "containing", "in", "hits_dict", ".", "items", "(", ")", ":", "equivalent", "=", "set", "(", ")", "for", "containing_name",...
42.222222
20.888889
def setUserPushTag(self, userTag): """ 添加 Push 标签方法 方法 @param userTag:用户标签。 @return code:返回码,200 为正常。 @return errorMessage:错误信息。 """ desc = { "name": "CodeSuccessReslut", "desc": " http 成功返回结果", "fields": [{ "n...
[ "def", "setUserPushTag", "(", "self", ",", "userTag", ")", ":", "desc", "=", "{", "\"name\"", ":", "\"CodeSuccessReslut\"", ",", "\"desc\"", ":", "\" http 成功返回结果\",", "", "\"fields\"", ":", "[", "{", "\"name\"", ":", "\"code\"", ",", "\"type\"", ":", "\"Inte...
26.444444
12.407407
def create_node(self, bank, tags=None): """ Set up a CondorDagmanNode class to run splitbank code Parameters ---------- bank : pycbc.workflow.core.File The File containing the template bank to be split Returns -------- node : pycbc.workflow.c...
[ "def", "create_node", "(", "self", ",", "bank", ",", "tags", "=", "None", ")", ":", "if", "tags", "is", "None", ":", "tags", "=", "[", "]", "node", "=", "Node", "(", "self", ")", "node", ".", "add_input_opt", "(", "'--bank-file'", ",", "bank", ")",...
36.69697
17.060606