text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def drop_dose(self): """ Drop the maximum dose and related response values. """ doses = np.array(self.individual_doses) responses = np.array(self.responses) mask = doses != doses.max() self.individual_doses = doses[mask].tolist() self.responses = responses...
[ "def", "drop_dose", "(", "self", ")", ":", "doses", "=", "np", ".", "array", "(", "self", ".", "individual_doses", ")", "responses", "=", "np", ".", "array", "(", "self", ".", "responses", ")", "mask", "=", "doses", "!=", "doses", ".", "max", "(", ...
34.727273
0.005102
def select_view_indexes(self, indexes, flags=QItemSelectionModel.Select | QItemSelectionModel.Rows): """ Selects the View given indexes. :param view: View. :type view: QWidget :param indexes: Indexes to select. :type indexes: list :param flags: Selection flags. (...
[ "def", "select_view_indexes", "(", "self", ",", "indexes", ",", "flags", "=", "QItemSelectionModel", ".", "Select", "|", "QItemSelectionModel", ".", "Rows", ")", ":", "if", "self", ".", "selectionModel", "(", ")", ":", "selection", "=", "QItemSelection", "(", ...
35.105263
0.00438
def get_task_logs(self, taskId): """ :param taskId: Task identifier :type caseTaskLog: CaseTaskLog defined in models.py :return: TheHive logs :rtype: json """ req = self.url + "/api/case/task/{}/log".format(taskId) try: return requests.get(re...
[ "def", "get_task_logs", "(", "self", ",", "taskId", ")", ":", "req", "=", "self", ".", "url", "+", "\"/api/case/task/{}/log\"", ".", "format", "(", "taskId", ")", "try", ":", "return", "requests", ".", "get", "(", "req", ",", "proxies", "=", "self", "....
36
0.007737
def without_args(self, *args, **kwargs): """Set the last call to expect that certain arguments will not exist. This is the opposite of :func:`fudge.Fake.with_matching_args`. It will fail if any of the arguments are passed. .. doctest:: >>> import fudge >>> que...
[ "def", "without_args", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "exp", "=", "self", ".", "_get_current_call", "(", ")", "if", "args", ":", "exp", ".", "unexpected_args", "=", "args", "if", "kwargs", ":", "exp", ".", "unexpect...
41.219178
0.00357
def from_config(cls, cp, section, variable_args): """Returns a distribution based on a configuration file. The parameters for the distribution are retrieved from the section titled "[`section`-`variable_args`]" in the config file. Parameters ---------- cp : pycbc.workflo...
[ "def", "from_config", "(", "cls", ",", "cp", ",", "section", ",", "variable_args", ")", ":", "return", "super", "(", "UniformPowerLaw", ",", "cls", ")", ".", "from_config", "(", "cp", ",", "section", ",", "variable_args", ",", "bounds_required", "=", "True...
42.08
0.001859
def _check_and_replace_parser_args(parser, section, option, rename_func, make_dirs=True): """ Searches for parser settings that define filenames. If such settings are found, they are renamed according to the wildcard rules. Moreover, it is also tried to create the corresponding folders. ...
[ "def", "_check_and_replace_parser_args", "(", "parser", ",", "section", ",", "option", ",", "rename_func", ",", "make_dirs", "=", "True", ")", ":", "args", "=", "parser", ".", "get", "(", "section", ",", "option", ",", "raw", "=", "True", ")", "strings", ...
44.482759
0.003035
def to_qubo(self): """Convert a binary quadratic model to QUBO format. If the binary quadratic model's vartype is not :class:`.Vartype.BINARY`, values are converted. Returns: tuple: 2-tuple of form (`biases`, `offset`), where `biases` is a dict in which keys are...
[ "def", "to_qubo", "(", "self", ")", ":", "qubo", "=", "dict", "(", "self", ".", "binary", ".", "quadratic", ")", "qubo", ".", "update", "(", "(", "(", "v", ",", "v", ")", ",", "bias", ")", "for", "v", ",", "bias", "in", "iteritems", "(", "self"...
44.5
0.00707
def deregister_listener(self, member_uuid, listener): """ Deregister listener for audio group changes of cast uuid.""" self._casts[str(member_uuid)]['listeners'].remove(listener)
[ "def", "deregister_listener", "(", "self", ",", "member_uuid", ",", "listener", ")", ":", "self", ".", "_casts", "[", "str", "(", "member_uuid", ")", "]", "[", "'listeners'", "]", ".", "remove", "(", "listener", ")" ]
64
0.010309
def cancel(): """HTTP endpoint for canceling tasks If an active task is cancelled, an inactive task with the same code and the smallest interval will be activated if it exists. """ task_id = request.form['id'] task = Task.query.get(task_id) if not task: return json.dumps({ 'status': 'success',...
[ "def", "cancel", "(", ")", ":", "task_id", "=", "request", ".", "form", "[", "'id'", "]", "task", "=", "Task", ".", "query", ".", "get", "(", "task_id", ")", "if", "not", "task", ":", "return", "json", ".", "dumps", "(", "{", "'status'", ":", "'s...
22.428571
0.013431
def SLOAD(self, offset): """Load word from storage""" storage_address = self.address self._publish('will_evm_read_storage', storage_address, offset) value = self.world.get_storage_data(storage_address, offset) self._publish('did_evm_read_storage', storage_address, offset, value) ...
[ "def", "SLOAD", "(", "self", ",", "offset", ")", ":", "storage_address", "=", "self", ".", "address", "self", ".", "_publish", "(", "'will_evm_read_storage'", ",", "storage_address", ",", "offset", ")", "value", "=", "self", ".", "world", ".", "get_storage_d...
47.714286
0.005882
def get_entity_propnames(entity): """ Get entity property names :param entity: Entity :type entity: sqlalchemy.ext.declarative.api.DeclarativeMeta :returns: Set of entity property names :rtype: set """ ins = entity if isinstance(entity, InstanceState) else inspect(entity) ...
[ "def", "get_entity_propnames", "(", "entity", ")", ":", "ins", "=", "entity", "if", "isinstance", "(", "entity", ",", "InstanceState", ")", "else", "inspect", "(", "entity", ")", "return", "set", "(", "ins", ".", "mapper", ".", "column_attrs", ".", "keys",...
33.538462
0.002232
def convert_to_ip(self): """Convert the Data Collection to IP units.""" self._values, self._header._unit = self._header.data_type.to_ip( self._values, self._header.unit)
[ "def", "convert_to_ip", "(", "self", ")", ":", "self", ".", "_values", ",", "self", ".", "_header", ".", "_unit", "=", "self", ".", "_header", ".", "data_type", ".", "to_ip", "(", "self", ".", "_values", ",", "self", ".", "_header", ".", "unit", ")" ...
49.5
0.00995
def application_information(self, application_id): """ The MapReduce application master information resource provides overall information about that mapreduce application master. This includes application id, time it was started, user, name, etc. :returns: API response object wi...
[ "def", "application_information", "(", "self", ",", "application_id", ")", ":", "path", "=", "'/proxy/{appid}/ws/v1/mapreduce/info'", ".", "format", "(", "appid", "=", "application_id", ")", "return", "self", ".", "request", "(", "path", ")" ]
40
0.003759
def map(self, *sequences): """call a function on each element of a sequence remotely. This should behave very much like the builtin map, but return an AsyncMapResult if self.block is False. """ # set _map as a flag for use inside self.__call__ self._map = True try...
[ "def", "map", "(", "self", ",", "*", "sequences", ")", ":", "# set _map as a flag for use inside self.__call__", "self", ".", "_map", "=", "True", "try", ":", "ret", "=", "self", ".", "__call__", "(", "*", "sequences", ")", "finally", ":", "del", "self", "...
34.666667
0.007026
def get_current_version_by_config_file() -> str: """ Get current version from the version variable defined in the configuration :return: A string with the current version number :raises ImproperConfigurationError: if version variable cannot be parsed """ debug('get_current_version_by_config_fil...
[ "def", "get_current_version_by_config_file", "(", ")", "->", "str", ":", "debug", "(", "'get_current_version_by_config_file'", ")", "filename", ",", "variable", "=", "config", ".", "get", "(", "'semantic_release'", ",", "'version_variable'", ")", ".", "split", "(", ...
35.909091
0.001233
def create_analysis(name, kernel, src_dir, scaffold_name): """Create analysis files.""" # analysis folder folder = os.path.join(os.getcwd(), 'analyses', name) if not os.path.exists(folder): os.makedirs(folder) else: log.warning('Analysis folder {} already exists.'.format(folder)) ...
[ "def", "create_analysis", "(", "name", ",", "kernel", ",", "src_dir", ",", "scaffold_name", ")", ":", "# analysis folder", "folder", "=", "os", ".", "path", ".", "join", "(", "os", ".", "getcwd", "(", ")", ",", "'analyses'", ",", "name", ")", "if", "no...
35.222222
0.001536
def download(self, overwrite=False): """ Download data files needed by this Genome instance. Parameters ---------- overwrite : bool, optional Download files regardless whether local copy already exists. """ self._set_local_paths(download_if_missing=Tr...
[ "def", "download", "(", "self", ",", "overwrite", "=", "False", ")", ":", "self", ".", "_set_local_paths", "(", "download_if_missing", "=", "True", ",", "overwrite", "=", "overwrite", ")" ]
33.5
0.005814
def get_config(self): """Return configurations of MaxBoltzmannQPolicy # Returns Dict of config """ config = super(MaxBoltzmannQPolicy, self).get_config() config['eps'] = self.eps config['tau'] = self.tau config['clip'] = self.clip return confi...
[ "def", "get_config", "(", "self", ")", ":", "config", "=", "super", "(", "MaxBoltzmannQPolicy", ",", "self", ")", ".", "get_config", "(", ")", "config", "[", "'eps'", "]", "=", "self", ".", "eps", "config", "[", "'tau'", "]", "=", "self", ".", "tau",...
28.272727
0.006231
def remove_formatting_codes(line, irc=False): """Remove girc control codes from the given line.""" if irc: line = escape(line) new_line = '' while len(line) > 0: try: if line[0] == '$': line = line[1:] if line[0] == '$': ne...
[ "def", "remove_formatting_codes", "(", "line", ",", "irc", "=", "False", ")", ":", "if", "irc", ":", "line", "=", "escape", "(", "line", ")", "new_line", "=", "''", "while", "len", "(", "line", ")", ">", "0", ":", "try", ":", "if", "line", "[", "...
33.872727
0.000522
def do_map(*args, **kwargs): """Applies a filter on a sequence of objects or looks up an attribute. This is useful when dealing with lists of objects but you are really only interested in a certain value of it. The basic usage is mapping on an attribute. Imagine you have a list of users but you ar...
[ "def", "do_map", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "seq", ",", "func", "=", "prepare_map", "(", "args", ",", "kwargs", ")", "if", "seq", ":", "for", "item", "in", "seq", ":", "yield", "func", "(", "item", ")" ]
33.576923
0.001114
def noise_from_step_num(): """Quantization noise equal to (phi * (step_num + 1)) mod 1.0. Not using random_uniform here due to a problem on TPU in that random seeds are not respected, which may cause the parameters on different replicas to go out-of-sync. Returns: a float32 scalar """ step = tf.to_i...
[ "def", "noise_from_step_num", "(", ")", ":", "step", "=", "tf", ".", "to_int32", "(", "tf", ".", "train", ".", "get_or_create_global_step", "(", ")", ")", "+", "1", "phi", "=", "(", "(", "5", "**", "0.5", ")", "-", "1", ")", "/", "2", "# Naive comp...
41.095238
0.012458
def generate_hazard_rates(n, d, timelines, constant=False, independent=0, n_binary=0, model="aalen"): """ n: the number of instances d: the number of covariates lifelines: the observational times constant: make the coeffients constant (not time dependent) n_binary: the number of binary...
[ "def", "generate_hazard_rates", "(", "n", ",", "d", ",", "timelines", ",", "constant", "=", "False", ",", "independent", "=", "0", ",", "n_binary", "=", "0", ",", "model", "=", "\"aalen\"", ")", ":", "covariates", "=", "generate_covariates", "(", "n", ",...
48
0.004376
def tf_loss_per_instance(self, states, internals, actions, terminal, reward, next_states, next_internals, update, reference=None): """ Creates the TensorFlow operations for calculating the loss per batch instance. Args: states: Dict of state tensors. ...
[ "def", "tf_loss_per_instance", "(", "self", ",", "states", ",", "internals", ",", "actions", ",", "terminal", ",", "reward", ",", "next_states", ",", "next_internals", ",", "update", ",", "reference", "=", "None", ")", ":", "raise", "NotImplementedError" ]
44.45
0.007709
def build_requirements(docs_path, package_name="yacms"): """ Updates the requirements file with yacms's version number. """ mezz_string = "yacms==" project_path = os.path.join(docs_path, "..") requirements_file = os.path.join(project_path, package_name, "proj...
[ "def", "build_requirements", "(", "docs_path", ",", "package_name", "=", "\"yacms\"", ")", ":", "mezz_string", "=", "\"yacms==\"", "project_path", "=", "os", ".", "path", ".", "join", "(", "docs_path", ",", "\"..\"", ")", "requirements_file", "=", "os", ".", ...
44.533333
0.001466
def max_width(self): """ The maximum width of all the Decors in the Legend. This is needed to scale a Legend or Striplog when plotting with widths turned on. """ try: maximum = max([row.width for row in self.__list if row.width is not None]) return maximum...
[ "def", "max_width", "(", "self", ")", ":", "try", ":", "maximum", "=", "max", "(", "[", "row", ".", "width", "for", "row", "in", "self", ".", "__list", "if", "row", ".", "width", "is", "not", "None", "]", ")", "return", "maximum", "except", ":", ...
34.8
0.011204
def text(files): '''Returns the whole transcribed text''' sentences = convert_timestamps(files) out = [] for s in sentences: out.append(' '.join([w[0] for w in s['words']])) return '\n'.join(out)
[ "def", "text", "(", "files", ")", ":", "sentences", "=", "convert_timestamps", "(", "files", ")", "out", "=", "[", "]", "for", "s", "in", "sentences", ":", "out", ".", "append", "(", "' '", ".", "join", "(", "[", "w", "[", "0", "]", "for", "w", ...
31
0.004484
def QA_SU_save_stock_min(client=DATABASE, ui_log=None, ui_progress=None): """save stock_min Keyword Arguments: client {[type]} -- [description] (default: {DATABASE}) """ stock_list = QA_fetch_get_stock_list().code.unique().tolist() coll = client.stock_min coll.create_index( [ ...
[ "def", "QA_SU_save_stock_min", "(", "client", "=", "DATABASE", ",", "ui_log", "=", "None", ",", "ui_progress", "=", "None", ")", ":", "stock_list", "=", "QA_fetch_get_stock_list", "(", ")", ".", "code", ".", "unique", "(", ")", ".", "tolist", "(", ")", "...
34.704918
0.00023
def get_default_config(self): """ Returns the default collector settings """ config = super(TCPCollector, self).get_default_config() config.update({ 'path': 'tcp', 'allowed_names': 'ListenOverflows, ListenDrops, TCPLoss, ' + ...
[ "def", "get_default_config", "(", "self", ")", ":", "config", "=", "super", "(", "TCPCollector", ",", "self", ")", ".", "get_default_config", "(", ")", "config", ".", "update", "(", "{", "'path'", ":", "'tcp'", ",", "'allowed_names'", ":", "'ListenOverflows,...
40.125
0.003044
def get_length(self, length, trim=0, offset=0): """Return string at current position + length. If trim == true then get as much as possible before eos. """ if trim and not self.has_space(offset + length): return self.string[self.pos + offset:] elif self.has_space(offs...
[ "def", "get_length", "(", "self", ",", "length", ",", "trim", "=", "0", ",", "offset", "=", "0", ")", ":", "if", "trim", "and", "not", "self", ".", "has_space", "(", "offset", "+", "length", ")", ":", "return", "self", ".", "string", "[", "self", ...
43.7
0.004484
def work_model_factory(*, validator=validators.is_work_model, **kwargs): """Generate a Work model. Expects ``data``, ``validator``, ``model_cls``, and ``ld_context`` as keyword arguments. Raises: :exc:`ModelError`: If a non-'AbstractWork' ``ld_type`` keyword argument is given. ...
[ "def", "work_model_factory", "(", "*", ",", "validator", "=", "validators", ".", "is_work_model", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'ld_type'", "]", "=", "'AbstractWork'", "return", "_model_factory", "(", "validator", "=", "validator", ",", ...
34
0.002387
def format_character(char): """Returns the C-formatting of the character""" if \ char in string.ascii_letters \ or char in string.digits \ or char in [ '_', '.', ':', ';', ' ', '!', '?', '+', '-', '/', '=', '<', '>', '$', '(', ')', '@', '~', '`', '|', '#',...
[ "def", "format_character", "(", "char", ")", ":", "if", "char", "in", "string", ".", "ascii_letters", "or", "char", "in", "string", ".", "digits", "or", "char", "in", "[", "'_'", ",", "'.'", ",", "':'", ",", "';'", ",", "' '", ",", "'!'", ",", "'?'...
31.85
0.001524
def cmd_compassmot(self, args): '''do a compass/motor interference calibration''' mav = self.master print("compassmot starting") mav.mav.command_long_send(mav.target_system, mav.target_component, mavutil.mavlink.MAV_CMD_PREFLIGHT_CALIBRATION, 0, ...
[ "def", "cmd_compassmot", "(", "self", ",", "args", ")", ":", "mav", "=", "self", ".", "master", "print", "(", "\"compassmot starting\"", ")", "mav", ".", "mav", ".", "command_long_send", "(", "mav", ".", "target_system", ",", "mav", ".", "target_component", ...
51.222222
0.006397
def init_logger(self): """Create configuration for the root logger.""" # All logs are comming to this logger self.logger.setLevel(logging.DEBUG) self.logger.propagate = False # Logging to console if self.min_log_level_to_print: level = self.min_log_level_to_p...
[ "def", "init_logger", "(", "self", ")", ":", "# All logs are comming to this logger", "self", ".", "logger", ".", "setLevel", "(", "logging", ".", "DEBUG", ")", "self", ".", "logger", ".", "propagate", "=", "False", "# Logging to console", "if", "self", ".", "...
35.548387
0.001767
def add_doc(self, doc, index_update=True, label_guesser_update=True): """ Add a document to the index """ if not self.index_writer and index_update: self.index_writer = self.index.writer() if not self.label_guesser_updater and label_guesser_update: self.la...
[ "def", "add_doc", "(", "self", ",", "doc", ",", "index_update", "=", "True", ",", "label_guesser_update", "=", "True", ")", ":", "if", "not", "self", ".", "index_writer", "and", "index_update", ":", "self", ".", "index_writer", "=", "self", ".", "index", ...
44.933333
0.002907
def timestamp(self): "Return POSIX timestamp as float" if self._tzinfo is None: return _time.mktime((self.year, self.month, self.day, self.hour, self.minute, self.second, -1, -1, -1)) + self.microsecond / 1e6 else: ...
[ "def", "timestamp", "(", "self", ")", ":", "if", "self", ".", "_tzinfo", "is", "None", ":", "return", "_time", ".", "mktime", "(", "(", "self", ".", "year", ",", "self", ".", "month", ",", "self", ".", "day", ",", "self", ".", "hour", ",", "self"...
45
0.00545
def _generateModel0(numCategories): """ Generate the initial, first order, and second order transition probabilities for 'model0'. For this model, we generate the following set of sequences: 1-2-3 (4X) 1-2-4 (1X) 5-2-3 (1X) 5-2-4 (4X) Parameters: --------------------------------------...
[ "def", "_generateModel0", "(", "numCategories", ")", ":", "# ===============================================================", "# Let's model the following:", "# a-b-c (4X)", "# a-b-d (1X)", "# e-b-c (1X)", "# e-b-d (4X)", "# --------------------------------------------------------------...
37.333333
0.01495
def check_type(self): """Make sure each stochastic has a correct type, and identify discrete stochastics.""" self.isdiscrete = {} for stochastic in self.stochastics: if stochastic.dtype in integer_dtypes: self.isdiscrete[stochastic] = True elif stochastic....
[ "def", "check_type", "(", "self", ")", ":", "self", ".", "isdiscrete", "=", "{", "}", "for", "stochastic", "in", "self", ".", "stochastics", ":", "if", "stochastic", ".", "dtype", "in", "integer_dtypes", ":", "self", ".", "isdiscrete", "[", "stochastic", ...
46.909091
0.007605
def update_dropdown_list_slot(self): """Keep updating the dropdown list. Say, don't let the user choose USB devices if none is available """ self.dropdown_widget.clear() # this will trigger dropdown_changed_slot self.row_instance_by_index = [] for i, key in enumerate(self.row_in...
[ "def", "update_dropdown_list_slot", "(", "self", ")", ":", "self", ".", "dropdown_widget", ".", "clear", "(", ")", "# this will trigger dropdown_changed_slot", "self", ".", "row_instance_by_index", "=", "[", "]", "for", "i", ",", "key", "in", "enumerate", "(", "...
54.583333
0.006006
def _calc_inst_pmf(self): """Calculate the epsilon-greedy instrumental distribution""" # Easy vars t = self.t_ epsilon = self.epsilon alpha = self.alpha preds = self._preds_avg_in_strata weights = self.strata.weights_[:,np.newaxis] p1 = self._BB_model.thet...
[ "def", "_calc_inst_pmf", "(", "self", ")", ":", "# Easy vars", "t", "=", "self", ".", "t_", "epsilon", "=", "self", ".", "epsilon", "alpha", "=", "self", ".", "alpha", "preds", "=", "self", ".", "_preds_avg_in_strata", "weights", "=", "self", ".", "strat...
38.727273
0.00687
def _dash_escape_text(text: str) -> str: """ Add dash '-' (0x2D) and space ' ' (0x20) as prefix on each line :param text: Text to dash-escape :return: """ dash_escaped_text = str() for line in text.splitlines(True): # add dash '-' (0x2D) and space ' ...
[ "def", "_dash_escape_text", "(", "text", ":", "str", ")", "->", "str", ":", "dash_escaped_text", "=", "str", "(", ")", "for", "line", "in", "text", ".", "splitlines", "(", "True", ")", ":", "# add dash '-' (0x2D) and space ' ' (0x20) as prefix", "dash_escaped_text...
29.857143
0.00464
def _get_valid_with_defaults_modes(capabilities): """Reference: https://tools.ietf.org/html/rfc6243#section-4.3""" capability = capabilities[":with-defaults"] try: valid_modes = [capability.parameters["basic-mode"]] except KeyError: raise WithDefaultsError( "Invalid 'with-de...
[ "def", "_get_valid_with_defaults_modes", "(", "capabilities", ")", ":", "capability", "=", "capabilities", "[", "\":with-defaults\"", "]", "try", ":", "valid_modes", "=", "[", "capability", ".", "parameters", "[", "\"basic-mode\"", "]", "]", "except", "KeyError", ...
30.2
0.001605
def get_connection(self): """ Return a pair of socket object and string address. May block! """ conn = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) try: conn.bind(self._agent._get_filename()) conn.listen(1) (r, addr) = conn.accept...
[ "def", "get_connection", "(", "self", ")", ":", "conn", "=", "socket", ".", "socket", "(", "socket", ".", "AF_UNIX", ",", "socket", ".", "SOCK_STREAM", ")", "try", ":", "conn", ".", "bind", "(", "self", ".", "_agent", ".", "_get_filename", "(", ")", ...
26.428571
0.007833
def _search_parents(initial_dir): """Search the initial and parent directories for a ``conf.py`` Sphinx configuration file that represents the root of a Sphinx project. Returns ------- root_dir : `pathlib.Path` Directory path containing a ``conf.py`` file. Raises ------ FileNot...
[ "def", "_search_parents", "(", "initial_dir", ")", ":", "root_paths", "=", "(", "'.'", ",", "'/'", ")", "parent", "=", "pathlib", ".", "Path", "(", "initial_dir", ")", "while", "True", ":", "if", "_has_conf_py", "(", "parent", ")", ":", "return", "parent...
30.035714
0.001152
def pattern(self): """ Return the pattern used to check if a field name can be accepted by this dynamic field. Use a default one ('^fieldname_(.+)$') if not set when the field was initialized """ if self.dynamic_version_of is not None: return self.dynamic_vers...
[ "def", "pattern", "(", "self", ")", ":", "if", "self", ".", "dynamic_version_of", "is", "not", "None", ":", "return", "self", ".", "dynamic_version_of", ".", "pattern", "if", "not", "self", ".", "_pattern", ":", "self", ".", "_pattern", "=", "re", ".", ...
37.25
0.00655
def daily(target_coll, source_coll, interp_days=32, interp_method='linear'): """Generate daily ETa collection from ETo and ETf collections Parameters ---------- target_coll : ee.ImageCollection Source images will be interpolated to each target image time_start. Target images should have...
[ "def", "daily", "(", "target_coll", ",", "source_coll", ",", "interp_days", "=", "32", ",", "interp_method", "=", "'linear'", ")", ":", "# # DEADBEEF - This module is assuming that the time band is already in", "# # the source collection.", "# # Uncomment the following to add a...
46.480263
0.001524
def subscribe(self, connection, destination): """ Subscribes a connection to the specified topic destination. @param connection: The client connection to subscribe. @type connection: L{coilmq.server.StompConnection} @param destination: The topic destination (e.g. '/topic/foo')...
[ "def", "subscribe", "(", "self", ",", "connection", ",", "destination", ")", ":", "self", ".", "log", ".", "debug", "(", "\"Subscribing %s to %s\"", "%", "(", "connection", ",", "destination", ")", ")", "self", ".", "_topics", "[", "destination", "]", ".",...
40.083333
0.00813
def _headers(self, headers_dict): """ Convert dictionary of headers into twisted.web.client.Headers object. """ return Headers(dict((k,[v]) for (k,v) in headers_dict.items()))
[ "def", "_headers", "(", "self", ",", "headers_dict", ")", ":", "return", "Headers", "(", "dict", "(", "(", "k", ",", "[", "v", "]", ")", "for", "(", "k", ",", "v", ")", "in", "headers_dict", ".", "items", "(", ")", ")", ")" ]
40.6
0.019324
def get_login(self, use_session=True): """ Get an active login session @param use_session: Use a saved session file if available @type use_session: bool """ # Should we try and return an existing login session? if use_session and self._login.check(): ...
[ "def", "get_login", "(", "self", ",", "use_session", "=", "True", ")", ":", "# Should we try and return an existing login session?", "if", "use_session", "and", "self", ".", "_login", ".", "check", "(", ")", ":", "self", ".", "cookiejar", "=", "self", ".", "_l...
36.090909
0.002454
def astral(msg): """Does `msg` have characters outside the Basic Multilingual Plane?""" # Python2 narrow builds present astral characters as surrogate pairs. # By encoding as utf32, and decoding DWORDS, we can get at the real code # points. utf32 = msg.encode("utf32")[4:] # [4:] to drop the ...
[ "def", "astral", "(", "msg", ")", ":", "# Python2 narrow builds present astral characters as surrogate pairs.", "# By encoding as utf32, and decoding DWORDS, we can get at the real code", "# points.", "utf32", "=", "msg", ".", "encode", "(", "\"utf32\"", ")", "[", "4", ":", "...
53.875
0.002283
def checkPortIsOpen(remoteServerHost=ServerHost, port = Port): ''' Checks if the specified port is open :param remoteServerHost: the host address :param port: port which needs to be checked :return: ``True`` if port is open, ``False`` otherwise ''' remoteServerIP = socket.gethostbyname(remo...
[ "def", "checkPortIsOpen", "(", "remoteServerHost", "=", "ServerHost", ",", "port", "=", "Port", ")", ":", "remoteServerIP", "=", "socket", ".", "gethostbyname", "(", "remoteServerHost", ")", "try", ":", "sock", "=", "socket", ".", "socket", "(", "socket", "....
30.206897
0.006637
def isStochastic(matrix): """Check that ``matrix`` is row stochastic. Returns ======= is_stochastic : bool ``True`` if ``matrix`` is row stochastic, ``False`` otherwise. """ try: absdiff = (_np.abs(matrix.sum(axis=1) - _np.ones(matrix.shape[0]))) except AttributeError: ...
[ "def", "isStochastic", "(", "matrix", ")", ":", "try", ":", "absdiff", "=", "(", "_np", ".", "abs", "(", "matrix", ".", "sum", "(", "axis", "=", "1", ")", "-", "_np", ".", "ones", "(", "matrix", ".", "shape", "[", "0", "]", ")", ")", ")", "ex...
31.533333
0.002053
def is_code(self): """Is this cell a code cell?""" if self.cell_type == 'code': return True if self.cell_type == 'raw' and 'active' in self.metadata: return True return False
[ "def", "is_code", "(", "self", ")", ":", "if", "self", ".", "cell_type", "==", "'code'", ":", "return", "True", "if", "self", ".", "cell_type", "==", "'raw'", "and", "'active'", "in", "self", ".", "metadata", ":", "return", "True", "return", "False" ]
32
0.008696
def smooth_ot_dual(a, b, M, reg, reg_type='l2', method="L-BFGS-B", stopThr=1e-9, numItermax=500, verbose=False, log=False): r""" Solve the regularized OT problem in the dual and return the OT matrix The function solves the smooth relaxed dual formulation (7) in [17]_ : .. math:: ...
[ "def", "smooth_ot_dual", "(", "a", ",", "b", ",", "M", ",", "reg", ",", "reg_type", "=", "'l2'", ",", "method", "=", "\"L-BFGS-B\"", ",", "stopThr", "=", "1e-9", ",", "numItermax", "=", "500", ",", "verbose", "=", "False", ",", "log", "=", "False", ...
33.644444
0.002246
def verify(self): """ ## FOR DEBUGGING ONLY ## Checks the table to ensure that the invariants are held. """ if self.all_intervals: ## top_node.all_children() == self.all_intervals try: assert self.top_node.all_children() == self.all_interva...
[ "def", "verify", "(", "self", ")", ":", "if", "self", ".", "all_intervals", ":", "## top_node.all_children() == self.all_intervals", "try", ":", "assert", "self", ".", "top_node", ".", "all_children", "(", ")", "==", "self", ".", "all_intervals", "except", "Asse...
38.873239
0.00318
def add_locations(self, locations): """Add extra locations to AstralGeocoder. Extra locations can be * A single string containing one or more locations separated by a newline. * A list of strings * A list of lists/tuples that are passed to a :class:`Location` constructor ...
[ "def", "add_locations", "(", "self", ",", "locations", ")", ":", "if", "isinstance", "(", "locations", ",", "(", "str", ",", "ustr", ")", ")", ":", "self", ".", "_add_from_str", "(", "locations", ")", "elif", "isinstance", "(", "locations", ",", "(", "...
35.428571
0.007859
def main( upload='usbasp', core='arduino', replace_existing=True, ): """install custom boards.""" def install(mcu, f_cpu, kbyte): board = AutoBunch() board.name = TEMPL_NAME.format(mcu=mcu, f_cpu=format_freq(f_cpu), ...
[ "def", "main", "(", "upload", "=", "'usbasp'", ",", "core", "=", "'arduino'", ",", "replace_existing", "=", "True", ",", ")", ":", "def", "install", "(", "mcu", ",", "f_cpu", ",", "kbyte", ")", ":", "board", "=", "AutoBunch", "(", ")", "board", ".", ...
30.538462
0.000814
def schedule_checksum_verification(frequency=None, batch_interval=None, max_count=None, max_size=None, files_query=None, checksum_kwargs=None): """Schedule a batch of files for checksum verification. The pu...
[ "def", "schedule_checksum_verification", "(", "frequency", "=", "None", ",", "batch_interval", "=", "None", ",", "max_count", "=", "None", ",", "max_size", "=", "None", ",", "files_query", "=", "None", ",", "checksum_kwargs", "=", "None", ")", ":", "assert", ...
48.123596
0.000229
async def main(loop): """Demonstrate functionality of PyVLX.""" pyvlx = PyVLX('pyvlx.yaml', loop=loop) # Alternative: # pyvlx = PyVLX(host="192.168.2.127", password="velux123", loop=loop) # Runing scenes: await pyvlx.load_scenes() await pyvlx.scenes["All Windows Closed"].run() # Changi...
[ "async", "def", "main", "(", "loop", ")", ":", "pyvlx", "=", "PyVLX", "(", "'pyvlx.yaml'", ",", "loop", "=", "loop", ")", "# Alternative:", "# pyvlx = PyVLX(host=\"192.168.2.127\", password=\"velux123\", loop=loop)", "# Runing scenes:", "await", "pyvlx", ".", "load_scen...
31.416667
0.001287
def optimize_rfc(data, targets): """Apply Bayesian Optimization to Random Forest parameters.""" def rfc_crossval(n_estimators, min_samples_split, max_features): """Wrapper of RandomForest cross validation. Notice how we ensure n_estimators and min_samples_split are casted to integer bef...
[ "def", "optimize_rfc", "(", "data", ",", "targets", ")", ":", "def", "rfc_crossval", "(", "n_estimators", ",", "min_samples_split", ",", "max_features", ")", ":", "\"\"\"Wrapper of RandomForest cross validation.\n\n Notice how we ensure n_estimators and min_samples_split a...
33.612903
0.000933
def _rebuffer(self): """ (internal) refill the repeat buffer """ # collect a stride worth of results(result lists) or exceptions results = [] exceptions = [] for i in xrange(self.stride): try: results.append(self.iterable.next(...
[ "def", "_rebuffer", "(", "self", ")", ":", "# collect a stride worth of results(result lists) or exceptions", "results", "=", "[", "]", "exceptions", "=", "[", "]", "for", "i", "in", "xrange", "(", "self", ".", "stride", ")", ":", "try", ":", "results", ".", ...
35.214286
0.002962
def collect_metrics(): """ Register the decorated function to run for the collect_metrics hook. """ def _register(action): handler = Handler.get(action) handler.add_predicate(partial(_restricted_hook, 'collect-metrics')) return action return _register
[ "def", "collect_metrics", "(", ")", ":", "def", "_register", "(", "action", ")", ":", "handler", "=", "Handler", ".", "get", "(", "action", ")", "handler", ".", "add_predicate", "(", "partial", "(", "_restricted_hook", ",", "'collect-metrics'", ")", ")", "...
31.888889
0.00339
def _update_process_stats(self): """Updates the process stats with the information from the processes This method is called at the end of each static parsing of the nextflow trace file. It re-populates the :attr:`process_stats` dictionary with the new stat metrics. """ ...
[ "def", "_update_process_stats", "(", "self", ")", ":", "good_status", "=", "[", "\"COMPLETED\"", ",", "\"CACHED\"", "]", "for", "process", ",", "vals", "in", "self", ".", "trace_info", ".", "items", "(", ")", ":", "# Update submission status of tags for each proce...
37.678161
0.000595
def get_all(cls): """ Returns an array with all databases :returns Database list """ api = Client.instance().api data = api.database.get() database_names = data['result'] databases = [] for name in database_names: db = Data...
[ "def", "get_all", "(", "cls", ")", ":", "api", "=", "Client", ".", "instance", "(", ")", ".", "api", "data", "=", "api", ".", "database", ".", "get", "(", ")", "database_names", "=", "data", "[", "'result'", "]", "databases", "=", "[", "]", "for", ...
20.263158
0.004963
def get_ports_by_name(device_name): '''Returns all serial devices with a given name''' filtered_devices = filter( lambda device: device_name in device[1], list_ports.comports() ) device_ports = [device[0] for device in filtered_devices] return device_ports
[ "def", "get_ports_by_name", "(", "device_name", ")", ":", "filtered_devices", "=", "filter", "(", "lambda", "device", ":", "device_name", "in", "device", "[", "1", "]", ",", "list_ports", ".", "comports", "(", ")", ")", "device_ports", "=", "[", "device", ...
35.625
0.003425
def _create_http_session(self): """Create a http session and initialize the retry object.""" self.session = requests.Session() if self.headers: self.session.headers.update(self.headers) retries = urllib3.util.Retry(total=self.max_retries, ...
[ "def", "_create_http_session", "(", "self", ")", ":", "self", ".", "session", "=", "requests", ".", "Session", "(", ")", "if", "self", ".", "headers", ":", "self", ".", "session", ".", "headers", ".", "update", "(", "self", ".", "headers", ")", "retrie...
55
0.004062
def json_2_routing_area(json_obj): """ transform JSON obj coming from Ariane to ariane_clip3 object :param json_obj: the JSON obj coming from Ariane :return: ariane_clip3 RoutingArea object """ LOGGER.debug("RoutingArea.json_2_routing_area") return RoutingArea(rai...
[ "def", "json_2_routing_area", "(", "json_obj", ")", ":", "LOGGER", ".", "debug", "(", "\"RoutingArea.json_2_routing_area\"", ")", "return", "RoutingArea", "(", "raid", "=", "json_obj", "[", "'routingAreaID'", "]", ",", "name", "=", "json_obj", "[", "'routingAreaNa...
55.357143
0.005076
def create_file_service(self): ''' Creates a FileService object with the settings specified in the CloudStorageAccount. :return: A service object. :rtype: :class:`~azure.storage.file.fileservice.FileService` ''' try: from azure.storage.file.fileservi...
[ "def", "create_file_service", "(", "self", ")", ":", "try", ":", "from", "azure", ".", "storage", ".", "file", ".", "fileservice", "import", "FileService", "return", "FileService", "(", "self", ".", "account_name", ",", "self", ".", "account_key", ",", "sas_...
44.5625
0.005495
def validate_request_timestamp(req_body, max_diff=150): """Ensure the request's timestamp doesn't fall outside of the app's specified tolerance. Returns True if this request is valid, False otherwise. :param req_body: JSON object parsed out of the raw POST data of a request. :param max_diff: Maxim...
[ "def", "validate_request_timestamp", "(", "req_body", ",", "max_diff", "=", "150", ")", ":", "time_str", "=", "req_body", ".", "get", "(", "'request'", ",", "{", "}", ")", ".", "get", "(", "'timestamp'", ")", "if", "not", "time_str", ":", "log", ".", "...
33.192308
0.001126
def loadFromURL(self, url): """Return a WSDL instance loaded from the given url.""" document = DOM.loadFromURL(url) wsdl = WSDL() wsdl.location = url wsdl.load(document) return wsdl
[ "def", "loadFromURL", "(", "self", ",", "url", ")", ":", "document", "=", "DOM", ".", "loadFromURL", "(", "url", ")", "wsdl", "=", "WSDL", "(", ")", "wsdl", ".", "location", "=", "url", "wsdl", ".", "load", "(", "document", ")", "return", "wsdl" ]
31.857143
0.008734
def get_hex_chain(self, index): """Assemble and return the chain leading from a given node to the merkle root of this tree with hash values in hex form """ return [(codecs.encode(i[0], 'hex_codec'), i[1]) for i in self.get_chain(index)]
[ "def", "get_hex_chain", "(", "self", ",", "index", ")", ":", "return", "[", "(", "codecs", ".", "encode", "(", "i", "[", "0", "]", ",", "'hex_codec'", ")", ",", "i", "[", "1", "]", ")", "for", "i", "in", "self", ".", "get_chain", "(", "index", ...
52.8
0.014925
def pow(self, *args, **kwargs): """ pow(other, rho=0, inplace=True) Raises by the power of an *other* number instance. The correlation coefficient *rho* can be configured per uncertainty when passed as a dict. When *inplace* is *False*, a new instance is returned. """ ret...
[ "def", "pow", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_apply", "(", "operator", ".", "pow", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
51.428571
0.010929
def remote(href): """ Normalize remote href :param href: remote path :return: normalize href >>> remote("/test/hello.txt") u'/test/hello.txt' >>> remote("test/hello.txt") u'/test/hello.txt' >>> remote("test\hello.txt") u'/test/hello.txt' >>> remote(None) u'/' """ ...
[ "def", "remote", "(", "href", ")", ":", "href", "=", "_", "(", "href", ")", "href", "=", "os", ".", "path", ".", "join", "(", "u", "(", "\"/\"", ")", ",", "href", ")", "if", "os", ".", "sep", "==", "\"\\\\\"", ":", "href", "=", "href", ".", ...
21.6
0.004435
def _largest_integer_by_dtype(dt): """Helper returning the largest integer exactly representable by dtype.""" if not _is_known_dtype(dt): raise TypeError("Unrecognized dtype: {}".format(dt.name)) if dt.is_floating: return int(2**(np.finfo(dt.as_numpy_dtype).nmant + 1)) if dt.is_integer: return np.ii...
[ "def", "_largest_integer_by_dtype", "(", "dt", ")", ":", "if", "not", "_is_known_dtype", "(", "dt", ")", ":", "raise", "TypeError", "(", "\"Unrecognized dtype: {}\"", ".", "format", "(", "dt", ".", "name", ")", ")", "if", "dt", ".", "is_floating", ":", "re...
42.666667
0.015296
def _check_scalar_vertical_extents(self, ds, z_variable): ''' Check the scalar value of Z compared to the vertical extents which should also be equivalent :param netCDF4.Dataset ds: An open netCDF dataset :param str z_variable: Name of the variable representing the Z-Axis ...
[ "def", "_check_scalar_vertical_extents", "(", "self", ",", "ds", ",", "z_variable", ")", ":", "vert_min", "=", "ds", ".", "geospatial_vertical_min", "vert_max", "=", "ds", ".", "geospatial_vertical_max", "msgs", "=", "[", "]", "total", "=", "2", "zvalue", "=",...
35.387097
0.002662
async def _send_rtcp_nack(self, media_ssrc, lost): """ Send an RTCP packet to report missing RTP packets. """ if self.__rtcp_ssrc is not None: packet = RtcpRtpfbPacket( fmt=RTCP_RTPFB_NACK, ssrc=self.__rtcp_ssrc, media_ssrc=media_ssrc) packet.lost ...
[ "async", "def", "_send_rtcp_nack", "(", "self", ",", "media_ssrc", ",", "lost", ")", ":", "if", "self", ".", "__rtcp_ssrc", "is", "not", "None", ":", "packet", "=", "RtcpRtpfbPacket", "(", "fmt", "=", "RTCP_RTPFB_NACK", ",", "ssrc", "=", "self", ".", "__...
40
0.008152
def get_statements_for_paper(ids, ev_limit=10, best_first=True, tries=2, max_stmts=None): """Get the set of raw Statements extracted from a paper given by the id. Parameters ---------- ids : list[(<id type>, <id value>)] A list of tuples with ids and their type. The...
[ "def", "get_statements_for_paper", "(", "ids", ",", "ev_limit", "=", "10", ",", "best_first", "=", "True", ",", "tries", "=", "2", ",", "max_stmts", "=", "None", ")", ":", "id_l", "=", "[", "{", "'id'", ":", "id_val", ",", "'type'", ":", "id_type", "...
50.567568
0.001049
def get_first_child_of_type(self, klass): """! @brief Breadth-first search for a child of the given class. @param self @param klass The class type to search for. The first child at any depth that is an instance of this class or a subclass thereof will be returned. Matching children a...
[ "def", "get_first_child_of_type", "(", "self", ",", "klass", ")", ":", "matches", "=", "self", ".", "find_children", "(", "lambda", "c", ":", "isinstance", "(", "c", ",", "klass", ")", ")", "if", "len", "(", "matches", ")", ":", "return", "matches", "[...
46.230769
0.006525
def idle_task(self): '''called rapidly by mavproxy''' now = time.time() if now-self.last_bored > self.boredom_interval: self.last_bored = now message = self.boredom_message() self.say("%s: %s" % (self.name,message)) # See if whatever we're connecte...
[ "def", "idle_task", "(", "self", ")", ":", "now", "=", "time", ".", "time", "(", ")", "if", "now", "-", "self", ".", "last_bored", ">", "self", ".", "boredom_interval", ":", "self", ".", "last_bored", "=", "now", "message", "=", "self", ".", "boredom...
46.9
0.008368
def _process_request(self, request): """Adds data necessary for Horizon to function to the request.""" request.horizon = {'dashboard': None, 'panel': None, 'async_messages': []} if not hasattr(request, "user") or not request.user.is_authenti...
[ "def", "_process_request", "(", "self", ",", "request", ")", ":", "request", ".", "horizon", "=", "{", "'dashboard'", ":", "None", ",", "'panel'", ":", "None", ",", "'async_messages'", ":", "[", "]", "}", "if", "not", "hasattr", "(", "request", ",", "\...
47.828125
0.00064
def select(self, table, items=None, limit=None, offset=None, remote_filter=None, func_filters=None): '''This method simulate a select on a table >>> yql.select('geo.countries', limit=5) >>> yql.select('social.profile', ['guid', 'givenName', 'gender']) ''' self._table = table ...
[ "def", "select", "(", "self", ",", "table", ",", "items", "=", "None", ",", "limit", "=", "None", ",", "offset", "=", "None", ",", "remote_filter", "=", "None", ",", "func_filters", "=", "None", ")", ":", "self", ".", "_table", "=", "table", "if", ...
34.958333
0.009281
def inv(z: int) -> int: """$= z^{-1} mod q$, for z != 0""" # Adapted from curve25519_athlon.c in djb's Curve25519. z2 = z * z % q # 2 z9 = pow2(z2, 2) * z % q # 9 z11 = z9 * z2 % q # 11 z2_5_0 = (z11 * z11) % q * z9 % q # 31 == 2^5 - 2^0 z2_10_0 = pow2(z2_5_0, 5) * z2_5_0 % q # 2^10 - 2...
[ "def", "inv", "(", "z", ":", "int", ")", "->", "int", ":", "# Adapted from curve25519_athlon.c in djb's Curve25519.", "z2", "=", "z", "*", "z", "%", "q", "# 2", "z9", "=", "pow2", "(", "z2", ",", "2", ")", "*", "z", "%", "q", "# 9", "z11", "=", "z9...
43.466667
0.001502
def parse_nhx(NHX_string): """ NHX format: [&&NHX:prop1=value1:prop2=value2] MB format: ((a[&Z=1,Y=2], b[&Z=1,Y=2]):1.0[&L=1,W=0], ... """ # store features ndict = {} # parse NHX or MB features if "[&&NHX:" in NHX_string: NHX_string = NHX_string.replace("[&&NHX:", "") ...
[ "def", "parse_nhx", "(", "NHX_string", ")", ":", "# store features", "ndict", "=", "{", "}", "# parse NHX or MB features", "if", "\"[&&NHX:\"", "in", "NHX_string", ":", "NHX_string", "=", "NHX_string", ".", "replace", "(", "\"[&&NHX:\"", ",", "\"\"", ")", "NHX_s...
30.95
0.00627
def stack_keys(ddict, keys, extra=None): """ Combine elements of ddict into an array of shape (len(ddict[key]), len(keys)). Useful for preparing data for sklearn. Parameters ---------- ddict : dict A dict containing arrays or lists to be stacked. Must be of equal length. ke...
[ "def", "stack_keys", "(", "ddict", ",", "keys", ",", "extra", "=", "None", ")", ":", "if", "isinstance", "(", "keys", ",", "str", ")", ":", "d", "=", "[", "ddict", "[", "keys", "]", "]", "else", ":", "d", "=", "[", "ddict", "[", "k", "]", "fo...
30.48
0.002545
def monitors(self): # type: () -> Monitors """ Get positions of monitors (see parent class). """ if not self._monitors: int_ = int core = self.core # All monitors # We need to update the value with every single monitor found # using C...
[ "def", "monitors", "(", "self", ")", ":", "# type: () -> Monitors", "if", "not", "self", ".", "_monitors", ":", "int_", "=", "int", "core", "=", "self", ".", "core", "# All monitors", "# We need to update the value with every single monitor found", "# using CGRectUnion....
38.66
0.001514
def CreateStorageWriterForFile(cls, session, path): """Creates a storage writer based on the file. Args: session (Session): session the storage changes are part of. path (str): path to the storage file. Returns: StorageWriter: a storage writer or None if the storage file cannot be ...
[ "def", "CreateStorageWriterForFile", "(", "cls", ",", "session", ",", "path", ")", ":", "if", "sqlite_file", ".", "SQLiteStorageFile", ".", "CheckSupportedFormat", "(", "path", ")", ":", "return", "sqlite_writer", ".", "SQLiteStorageFileWriter", "(", "session", ",...
34.133333
0.003802
def _resolve_shape(self, name, layers): '''Given a list of layers, find the layer output with the given name. Parameters ---------- name : str Name of a layer to resolve. layers : list of :class:`theanets.layers.base.Layer` A list of layers to search in. ...
[ "def", "_resolve_shape", "(", "self", ",", "name", ",", "layers", ")", ":", "matches", "=", "[", "l", "for", "l", "in", "layers", "if", "name", ".", "split", "(", "':'", ")", "[", "0", "]", "==", "l", ".", "name", "]", "if", "len", "(", "matche...
35.517241
0.003781
def register_middleware(self, middleware, attach_to="request"): """ Register an application level middleware that will be attached to all the API URLs registered under this application. This method is internally invoked by the :func:`middleware` decorator provided at the app lev...
[ "def", "register_middleware", "(", "self", ",", "middleware", ",", "attach_to", "=", "\"request\"", ")", ":", "if", "attach_to", "==", "\"request\"", ":", "if", "middleware", "not", "in", "self", ".", "request_middleware", ":", "self", ".", "request_middleware",...
45.217391
0.001883
def _auth_stage1(self): """Do the first stage (<iq type='get'/>) of legacy ("plain" or "digest") authentication. [client only]""" iq=Iq(stanza_type="get") q=iq.new_query("jabber:iq:auth") q.newTextChild(None,"username",to_utf8(self.my_jid.node)) q.newTextChild(No...
[ "def", "_auth_stage1", "(", "self", ")", ":", "iq", "=", "Iq", "(", "stanza_type", "=", "\"get\"", ")", "q", "=", "iq", ".", "new_query", "(", "\"jabber:iq:auth\"", ")", "q", ".", "newTextChild", "(", "None", ",", "\"username\"", ",", "to_utf8", "(", "...
40.153846
0.022472
def CacheStorage_requestCachedResponse(self, cacheId, requestURL): """ Function path: CacheStorage.requestCachedResponse Domain: CacheStorage Method name: requestCachedResponse Parameters: Required arguments: 'cacheId' (type: CacheId) -> Id of cache that contains the enty. 'requestURL' (ty...
[ "def", "CacheStorage_requestCachedResponse", "(", "self", ",", "cacheId", ",", "requestURL", ")", ":", "assert", "isinstance", "(", "requestURL", ",", "(", "str", ",", ")", ")", ",", "\"Argument 'requestURL' must be of type '['str']'. Received type: '%s'\"", "%", "type"...
36.238095
0.038412
def get_environ_proxies(): """Return a dict of environment proxies. From requests_.""" proxy_keys = [ 'all', 'http', 'https', 'ftp', 'socks', 'ws', 'wss', 'no' ] def get_proxy(k): return os.environ.get(k) or os.environ.get(k.upper...
[ "def", "get_environ_proxies", "(", ")", ":", "proxy_keys", "=", "[", "'all'", ",", "'http'", ",", "'https'", ",", "'ftp'", ",", "'socks'", ",", "'ws'", ",", "'wss'", ",", "'no'", "]", "def", "get_proxy", "(", "k", ")", ":", "return", "os", ".", "envi...
23.157895
0.002183
def createPushParser(SAX, chunk, size, URI): """Create a progressive XML parser context to build either an event flow if the SAX object is not None, or a DOM tree otherwise. """ ret = libxml2mod.xmlCreatePushParser(SAX, chunk, size, URI) if ret is None:raise parserError('xmlCreatePushParser() f...
[ "def", "createPushParser", "(", "SAX", ",", "chunk", ",", "size", ",", "URI", ")", ":", "ret", "=", "libxml2mod", ".", "xmlCreatePushParser", "(", "SAX", ",", "chunk", ",", "size", ",", "URI", ")", "if", "ret", "is", "None", ":", "raise", "parserError"...
50.428571
0.008357
def _find_players(self, boxscore): """ Find all players for each team. Iterate through every player for both teams as found in the boxscore tables and create a list of instances of the BoxscorePlayer class for each player. Return lists of player instances comprising the away and...
[ "def", "_find_players", "(", "self", ",", "boxscore", ")", ":", "player_dict", "=", "{", "}", "table_count", "=", "0", "tables", "=", "self", ".", "_find_boxscore_tables", "(", "boxscore", ")", "for", "table", "in", "tables", ":", "home_or_away", "=", "HOM...
38.162162
0.001381
def files(self): """List of files (only supported file formats)""" if self._files is None: fifo = SeriesFolder._search_files(self.path) self._files = [ff[0] for ff in fifo] self._formats = [ff[1] for ff in fifo] return self._files
[ "def", "files", "(", "self", ")", ":", "if", "self", ".", "_files", "is", "None", ":", "fifo", "=", "SeriesFolder", ".", "_search_files", "(", "self", ".", "path", ")", "self", ".", "_files", "=", "[", "ff", "[", "0", "]", "for", "ff", "in", "fif...
40.571429
0.006897
def fs_obj_remove(self, path): """Removes a file system object (file, symlink, etc) in the guest. Will not work on directories, use :py:func:`IGuestSession.directory_remove` to remove directories. This method will remove symbolic links in the final path component, not ...
[ "def", "fs_obj_remove", "(", "self", ",", "path", ")", ":", "if", "not", "isinstance", "(", "path", ",", "basestring", ")", ":", "raise", "TypeError", "(", "\"path can only be an instance of type basestring\"", ")", "self", ".", "_call", "(", "\"fsObjRemove\"", ...
38.32
0.010183
def log(package): """ List all of the changes to a package on the server. """ team, owner, pkg = parse_package(package) session = _get_session(team) response = session.get( "{url}/api/log/{owner}/{pkg}/".format( url=get_registry_url(team), owner=owner, ...
[ "def", "log", "(", "package", ")", ":", "team", ",", "owner", ",", "pkg", "=", "parse_package", "(", "package", ")", "session", "=", "_get_session", "(", "team", ")", "response", "=", "session", ".", "get", "(", "\"{url}/api/log/{owner}/{pkg}/\"", ".", "fo...
31.954545
0.002762
def vars_class(cls): """Return a dict of vars for the given class, including all ancestors. This differs from the usual behaviour of `vars` which returns attributes belonging to the given class and not its ancestors. """ return dict(chain.from_iterable( vars(cls).items() for cls in reversed...
[ "def", "vars_class", "(", "cls", ")", ":", "return", "dict", "(", "chain", ".", "from_iterable", "(", "vars", "(", "cls", ")", ".", "items", "(", ")", "for", "cls", "in", "reversed", "(", "cls", ".", "__mro__", ")", ")", ")" ]
41
0.002985
def c_if(self, classical, val): """Add classical control register to all instructions.""" for gate in self.instructions: gate.c_if(classical, val) return self
[ "def", "c_if", "(", "self", ",", "classical", ",", "val", ")", ":", "for", "gate", "in", "self", ".", "instructions", ":", "gate", ".", "c_if", "(", "classical", ",", "val", ")", "return", "self" ]
38
0.010309
def psd(data, dt, ndivide=1, window=hanning, overlap_half=False): """Calculate power spectrum density of data. Args: data (np.ndarray): Input data. dt (float): Time between each data. ndivide (int): Do averaging (split data into ndivide, get psd of each, and average them). ax (m...
[ "def", "psd", "(", "data", ",", "dt", ",", "ndivide", "=", "1", ",", "window", "=", "hanning", ",", "overlap_half", "=", "False", ")", ":", "logger", "=", "getLogger", "(", "'decode.utils.ndarray.psd'", ")", "if", "overlap_half", ":", "step", "=", "int",...
33.795918
0.005869
def len(iterable): """Redefining len here so it will be able to work with non-ASCII characters """ if not isinstance(iterable, str): return iterable.__len__() try: return len(unicode(iterable, 'utf')) except: return iterable.__len__()
[ "def", "len", "(", "iterable", ")", ":", "if", "not", "isinstance", "(", "iterable", ",", "str", ")", ":", "return", "iterable", ".", "__len__", "(", ")", "try", ":", "return", "len", "(", "unicode", "(", "iterable", ",", "'utf'", ")", ")", "except",...
27
0.007168
def _get_names(self, path: str) -> Iterator[str]: """Load required packages from path to requirements file """ for i in RequirementsFinder._get_names_cached(path): yield i
[ "def", "_get_names", "(", "self", ",", "path", ":", "str", ")", "->", "Iterator", "[", "str", "]", ":", "for", "i", "in", "RequirementsFinder", ".", "_get_names_cached", "(", "path", ")", ":", "yield", "i" ]
40.6
0.009662