text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def rubles(amount, zero_for_kopeck=False): """ Get string for money @param amount: amount of money @type amount: C{integer types}, C{float} or C{Decimal} @param zero_for_kopeck: If false, then zero kopecks ignored @type zero_for_kopeck: C{bool} @return: in-words representation of money's ...
[ "def", "rubles", "(", "amount", ",", "zero_for_kopeck", "=", "False", ")", ":", "check_positive", "(", "amount", ")", "pts", "=", "[", "]", "amount", "=", "round", "(", "amount", ",", "2", ")", "pts", ".", "append", "(", "sum_string", "(", "int", "("...
29.354839
18.258065
def generate_vars(project_name, project_dir): """ Generates the variables to replace in files """ out = vary_name(project_name) out['random_key'] = make_random_key() out['settings_file'] = make_file_path( project_dir, project_name, path.join('src', project_name), ...
[ "def", "generate_vars", "(", "project_name", ",", "project_dir", ")", ":", "out", "=", "vary_name", "(", "project_name", ")", "out", "[", "'random_key'", "]", "=", "make_random_key", "(", ")", "out", "[", "'settings_file'", "]", "=", "make_file_path", "(", "...
22.866667
14.733333
def newPosition(self, globalBestPosition, rng): """See comments in base class.""" # Compute the mean score per choice. numChoices = len(self.choices) meanScorePerChoice = [] overallSum = 0 numResults = 0 for i in range(numChoices): if len(self._resultsPerChoice[i]) > 0: data =...
[ "def", "newPosition", "(", "self", ",", "globalBestPosition", ",", "rng", ")", ":", "# Compute the mean score per choice.", "numChoices", "=", "len", "(", "self", ".", "choices", ")", "meanScorePerChoice", "=", "[", "]", "overallSum", "=", "0", "numResults", "="...
36.166667
20
def get_value(self, variable=None): """ Gets given environment variable value. :param variable: Variable to retrieve value. :type variable: unicode :return: Variable value. :rtype: unicode :note: If the **variable** argument is not given the first **self.__varia...
[ "def", "get_value", "(", "self", ",", "variable", "=", "None", ")", ":", "if", "variable", ":", "self", ".", "get_values", "(", "variable", ")", "return", "self", ".", "__variables", "[", "variable", "]", "else", ":", "self", ".", "get_values", "(", ")...
32.5
20.166667
def calc_fisher_info_matrix(beta, design, alt_IDs, rows_to_obs, rows_to_alts, choice_vector, utility_transform, transform_fi...
[ "def", "calc_fisher_info_matrix", "(", "beta", ",", "design", ",", "alt_IDs", ",", "rows_to_obs", ",", "rows_to_alts", ",", "choice_vector", ",", "utility_transform", ",", "transform_first_deriv_c", ",", "transform_first_deriv_v", ",", "transform_deriv_alpha", ",", "int...
52.706897
23.87931
def run_game_of_life(years, width, height, time_delay, silent="N"): """ run a single game of life for 'years' and log start and end living cells to aikif """ lfe = mod_grid.GameOfLife(width, height, ['.', 'x'], 1) set_random_starting_grid(lfe) lg.record_source(lfe, 'game_of_life_console.py'...
[ "def", "run_game_of_life", "(", "years", ",", "width", ",", "height", ",", "time_delay", ",", "silent", "=", "\"N\"", ")", ":", "lfe", "=", "mod_grid", ".", "GameOfLife", "(", "width", ",", "height", ",", "[", "'.'", ",", "'x'", "]", ",", "1", ")", ...
38.222222
12.333333
def ssim(data, ground_truth, size=11, sigma=1.5, K1=0.01, K2=0.03, dynamic_range=None, normalized=False, force_lower_is_better=False): r"""Structural SIMilarity between ``data`` and ``ground_truth``. The SSIM takes value -1 for maximum dissimilarity and +1 for maximum similarity. See also `th...
[ "def", "ssim", "(", "data", ",", "ground_truth", ",", "size", "=", "11", ",", "sigma", "=", "1.5", ",", "K1", "=", "0.01", ",", "K2", "=", "0.03", ",", "dynamic_range", "=", "None", ",", "normalized", "=", "False", ",", "force_lower_is_better", "=", ...
36.292683
23.707317
def is_device_connected(self, ip): """ Check if a device identified by it IP is connected to the box :param ip: IP of the device you want to test :type ip: str :return: True is the device is connected, False if it's not :rtype: bool """ all_devices = self....
[ "def", "is_device_connected", "(", "self", ",", "ip", ")", ":", "all_devices", "=", "self", ".", "get_all_connected_devices", "(", ")", "for", "device", "in", "all_devices", ":", "if", "ip", "==", "device", "[", "'ipaddress'", "]", ":", "return", "device", ...
36.769231
12.153846
def create_entity_dict(self): ''' Creates a dict-based entity with fixed values, using all of the supported data types. ''' entity = {} # Partition key and row key must be strings and are required entity['PartitionKey'] = 'pk{}'.format(str(uuid.uuid4()).replace('-', ''))...
[ "def", "create_entity_dict", "(", "self", ")", ":", "entity", "=", "{", "}", "# Partition key and row key must be strings and are required", "entity", "[", "'PartitionKey'", "]", "=", "'pk{}'", ".", "format", "(", "str", "(", "uuid", ".", "uuid4", "(", ")", ")",...
45
25
def _delete_vdev_info(self, vdev): """handle vdev related info.""" vdev = vdev.lower() network_config_file_name = self._get_network_file() device = self._get_device_name(vdev) cmd = '\n'.join(("num=$(sed -n '/auto %s/=' %s)" % (device, ...
[ "def", "_delete_vdev_info", "(", "self", ",", "vdev", ")", ":", "vdev", "=", "vdev", ".", "lower", "(", ")", "network_config_file_name", "=", "self", ".", "_get_network_file", "(", ")", "device", "=", "self", ".", "_get_device_name", "(", "vdev", ")", "cmd...
52.555556
19.277778
def _autoinsert_brackets(self, key): """Control automatic insertation of brackets in various situations.""" char = self.BRACKETS_CHAR[key] pair = self.BRACKETS_PAIR[key] line_text = self.editor.get_text('sol', 'eol') line_to_cursor = self.editor.get_text('sol', 'cursor') ...
[ "def", "_autoinsert_brackets", "(", "self", ",", "key", ")", ":", "char", "=", "self", ".", "BRACKETS_CHAR", "[", "key", "]", "pair", "=", "self", ".", "BRACKETS_PAIR", "[", "key", "]", "line_text", "=", "self", ".", "editor", ".", "get_text", "(", "'s...
49.809524
15.571429
def definition_to_json(source): """Convert a bytecode.yaml file into a prepared bytecode.json. Jawa internally uses a YAML file to define all bytecode opcodes, operands, runtime exceptions, default transforms, etc... However since JSON is available in the python stdlib and YAML is not, we process ...
[ "def", "definition_to_json", "(", "source", ")", ":", "try", ":", "import", "yaml", "except", "ImportError", ":", "click", ".", "echo", "(", "'The pyyaml module could not be found and is required'", "' to use this command.'", ",", "err", "=", "True", ")", "return", ...
31
21.806452
def get_existing_path(path, topmost_path=None): """Get the longest parent path in `path` that exists. If `path` exists, it is returned. Args: path (str): Path to test topmost_path (str): Do not test this path or above Returns: str: Existing path, or None if no path was found. ...
[ "def", "get_existing_path", "(", "path", ",", "topmost_path", "=", "None", ")", ":", "prev_path", "=", "None", "if", "topmost_path", ":", "topmost_path", "=", "os", ".", "path", ".", "normpath", "(", "topmost_path", ")", "while", "True", ":", "if", "os", ...
23.482759
21.62069
def get_fanout_client(self, hosts, max_concurrency=64, auto_batch=None): """Returns a thread unsafe fanout client. Returns an instance of :class:`FanoutClient`. """ if auto_batch is None: auto_batch = self.auto_batch return FanoutClient(host...
[ "def", "get_fanout_client", "(", "self", ",", "hosts", ",", "max_concurrency", "=", "64", ",", "auto_batch", "=", "None", ")", ":", "if", "auto_batch", "is", "None", ":", "auto_batch", "=", "self", ".", "auto_batch", "return", "FanoutClient", "(", "hosts", ...
42
12.909091
def execute(self): """Generate local DB, pulling metadata and data from RWSConnection""" logging.info('Requesting view metadata for project %s' % self.project_name) project_csv_meta = self.rws_connection.send_request(ProjectMetaDataRequest(self.project_name)) # Process it into a set of...
[ "def", "execute", "(", "self", ")", ":", "logging", ".", "info", "(", "'Requesting view metadata for project %s'", "%", "self", ".", "project_name", ")", "project_csv_meta", "=", "self", ".", "rws_connection", ".", "send_request", "(", "ProjectMetaDataRequest", "(",...
47.52381
27.285714
def rooms_favorite(self, room_id=None, room_name=None, favorite=True): """Favorite or unfavorite room.""" if room_id is not None: return self.__call_api_post('rooms.favorite', roomId=room_id, favorite=favorite) elif room_name is not None: return self.__call_api_post('room...
[ "def", "rooms_favorite", "(", "self", ",", "room_id", "=", "None", ",", "room_name", "=", "None", ",", "favorite", "=", "True", ")", ":", "if", "room_id", "is", "not", "None", ":", "return", "self", ".", "__call_api_post", "(", "'rooms.favorite'", ",", "...
56.875
26.875
def setReflexAnalysisOf(self, analysis): """Sets the analysis that has been reflexed in order to create this one, but if the analysis is the same as self, do nothing. :param analysis: an analysis object or UID """ if not analysis or analysis.UID() == self.UID(): pass ...
[ "def", "setReflexAnalysisOf", "(", "self", ",", "analysis", ")", ":", "if", "not", "analysis", "or", "analysis", ".", "UID", "(", ")", "==", "self", ".", "UID", "(", ")", ":", "pass", "else", ":", "self", ".", "getField", "(", "'ReflexAnalysisOf'", ")"...
43.444444
14.111111
def loadSVrecs(fname, uselines=None, skiprows=0, linefixer=None, delimiter_regex=None, verbosity=DEFAULT_VERBOSITY, **metadata): """ Load a separated value text file to a list of lists of strings of records. Takes a tabular text file with a specified delimeter and end-of-line character...
[ "def", "loadSVrecs", "(", "fname", ",", "uselines", "=", "None", ",", "skiprows", "=", "0", ",", "linefixer", "=", "None", ",", "delimiter_regex", "=", "None", ",", "verbosity", "=", "DEFAULT_VERBOSITY", ",", "*", "*", "metadata", ")", ":", "if", "delimi...
40.517442
27.087209
def transfer_function( level=[0.1, 0.5, 0.9], opacity=[0.01, 0.05, 0.1], level_width=0.1, controls=True, max_opacity=0.2 ): """Create a transfer function, see volshow.""" tf_kwargs = {} # level, opacity and widths can be scalars try: level[0] except: level = [level] try: ...
[ "def", "transfer_function", "(", "level", "=", "[", "0.1", ",", "0.5", ",", "0.9", "]", ",", "opacity", "=", "[", "0.01", ",", "0.05", ",", "0.1", "]", ",", "level_width", "=", "0.1", ",", "controls", "=", "True", ",", "max_opacity", "=", "0.2", ")...
32.435897
19.615385
def plot_metrics(self, skip_start:int=0, skip_end:int=0, return_fig:bool=None)->Optional[plt.Figure]: "Plot metrics collected during training." assert len(self.metrics) != 0, "There are no metrics to plot." fig, axes = plt.subplots(len(self.metrics[0]),1,figsize=(6, 4*len(self.metrics[0]))) ...
[ "def", "plot_metrics", "(", "self", ",", "skip_start", ":", "int", "=", "0", ",", "skip_end", ":", "int", "=", "0", ",", "return_fig", ":", "bool", "=", "None", ")", "->", "Optional", "[", "plt", ".", "Figure", "]", ":", "assert", "len", "(", "self...
63.285714
24.142857
def rank_items(self, userid, user_items, selected_items, recalculate_user=False): """ Rank given items for a user and returns sorted item list """ # check if selected_items contains itemids that are not in the model(user_items) if max(selected_items) >= user_items.shape[1] or min(selected_items)...
[ "def", "rank_items", "(", "self", ",", "userid", ",", "user_items", ",", "selected_items", ",", "recalculate_user", "=", "False", ")", ":", "# check if selected_items contains itemids that are not in the model(user_items)", "if", "max", "(", "selected_items", ")", ">=", ...
50.894737
24.473684
def unregister_signals(self): """Unregister signals.""" # Unregister Record signals if hasattr(self, 'update_function'): records_signals.before_record_insert.disconnect( self.update_function) records_signals.before_record_update.disconnect( ...
[ "def", "unregister_signals", "(", "self", ")", ":", "# Unregister Record signals", "if", "hasattr", "(", "self", ",", "'update_function'", ")", ":", "records_signals", ".", "before_record_insert", ".", "disconnect", "(", "self", ".", "update_function", ")", "records...
41.666667
7.333333
def make_python_name(self, name): """Transforms an USR into a valid python name.""" # FIXME see cindex.SpellingCache for k, v in [('<', '_'), ('>', '_'), ('::', '__'), (',', ''), (' ', ''), ("$", "DOLLAR"), (".", "DOT"), ("@", "_"), (":", "_"), ('-', '_'...
[ "def", "make_python_name", "(", "self", ",", "name", ")", ":", "# FIXME see cindex.SpellingCache", "for", "k", ",", "v", "in", "[", "(", "'<'", ",", "'_'", ")", ",", "(", "'>'", ",", "'_'", ")", ",", "(", "'::'", ",", "'__'", ")", ",", "(", "','", ...
40.529412
13.411765
def run_checked (cmd, ret_ok=(0,), **kwargs): """Run command and raise PatoolError on error.""" retcode = run(cmd, **kwargs) if retcode not in ret_ok: msg = "Command `%s' returned non-zero exit status %d" % (cmd, retcode) raise PatoolError(msg) return retcode
[ "def", "run_checked", "(", "cmd", ",", "ret_ok", "=", "(", "0", ",", ")", ",", "*", "*", "kwargs", ")", ":", "retcode", "=", "run", "(", "cmd", ",", "*", "*", "kwargs", ")", "if", "retcode", "not", "in", "ret_ok", ":", "msg", "=", "\"Command `%s'...
40.714286
13.428571
def _fit_stacking_model(self,X, y, cost_mat, max_iter=100): """Private function used to fit the stacking model.""" self.f_staking = CostSensitiveLogisticRegression(verbose=self.verbose, max_iter=max_iter) X_stacking = _create_stacking_set(self.estimators_, self.estimators_features_, ...
[ "def", "_fit_stacking_model", "(", "self", ",", "X", ",", "y", ",", "cost_mat", ",", "max_iter", "=", "100", ")", ":", "self", ".", "f_staking", "=", "CostSensitiveLogisticRegression", "(", "verbose", "=", "self", ".", "verbose", ",", "max_iter", "=", "max...
65.857143
28.714286
def get_function_id(sig): '''' Return the function id of the given signature Args: sig (str) Return: (int) ''' s = sha3.keccak_256() s.update(sig.encode('utf-8')) return int("0x" + s.hexdigest()[:8], 16)
[ "def", "get_function_id", "(", "sig", ")", ":", "s", "=", "sha3", ".", "keccak_256", "(", ")", "s", ".", "update", "(", "sig", ".", "encode", "(", "'utf-8'", ")", ")", "return", "int", "(", "\"0x\"", "+", "s", ".", "hexdigest", "(", ")", "[", ":"...
22.272727
20.818182
def check_user_can_vote(cmt_id, client_ip_address, uid=-1): """ Checks if a user hasn't already voted :param cmt_id: comment id :param client_ip_address: IP => use: str(req.remote_ip) :param uid: user id, as given by invenio.legacy.webuser.getUid(req) """ cmt_id = wash_url_argument(cmt_id, 'int'...
[ "def", "check_user_can_vote", "(", "cmt_id", ",", "client_ip_address", ",", "uid", "=", "-", "1", ")", ":", "cmt_id", "=", "wash_url_argument", "(", "cmt_id", ",", "'int'", ")", "client_ip_address", "=", "wash_url_argument", "(", "client_ip_address", ",", "'str'...
38.095238
11.571429
def login(self, username, password=None, email=None, registry=None, reauth=False, dockercfg_path=None): """ :param username: The registry username :param password: The plaintext password :param email: The email for the registry account :param registry: URL to the re...
[ "def", "login", "(", "self", ",", "username", ",", "password", "=", "None", ",", "email", "=", "None", ",", "registry", "=", "None", ",", "reauth", "=", "False", ",", "dockercfg_path", "=", "None", ")", ":", "self", ".", "d", ".", "login", "(", "us...
50.571429
18.142857
def add_path(self, path): """Load translations from an existing path.""" if not os.path.exists(path): raise RuntimeError('Path does not exists: %s.' % path) self.paths.append(path)
[ "def", "add_path", "(", "self", ",", "path", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "raise", "RuntimeError", "(", "'Path does not exists: %s.'", "%", "path", ")", "self", ".", "paths", ".", "append", "(", "path"...
42.4
10.8
def fix_journal_name(journal, knowledge_base): """Convert journal name to Inspire's short form.""" if not journal: return '', '' if not knowledge_base: return journal, '' if len(journal) < 2: return journal, '' volume = '' if (journal[-1] <= 'Z' and journal[-1] >= 'A') \ ...
[ "def", "fix_journal_name", "(", "journal", ",", "knowledge_base", ")", ":", "if", "not", "journal", ":", "return", "''", ",", "''", "if", "not", "knowledge_base", ":", "return", "journal", ",", "''", "if", "len", "(", "journal", ")", "<", "2", ":", "re...
35.259259
14.703704
def load_config(self): """Load the config from a file and return it as a Struct.""" self.clear() try: self._find_file() except IOError as e: raise ConfigFileNotFound(str(e)) self._read_file_as_dict() self._convert_to_config() return self.co...
[ "def", "load_config", "(", "self", ")", ":", "self", ".", "clear", "(", ")", "try", ":", "self", ".", "_find_file", "(", ")", "except", "IOError", "as", "e", ":", "raise", "ConfigFileNotFound", "(", "str", "(", "e", ")", ")", "self", ".", "_read_file...
31.5
12.1
def sum(self, weights=None): """ return the sum of weights of each object """ if weights is None: weights = self.data.weights return utils.bincount(self.labels, weights, self.N)
[ "def", "sum", "(", "self", ",", "weights", "=", "None", ")", ":", "if", "weights", "is", "None", ":", "weights", "=", "self", ".", "data", ".", "weights", "return", "utils", ".", "bincount", "(", "self", ".", "labels", ",", "weights", ",", "self", ...
41.8
9
def move(self, new_container, new_obj_name=None, extra_info=None): """ Works just like copy_object, except that this object is deleted after a successful copy. This means that this storage_object reference will no longer be valid. """ return self.container.move_object(sel...
[ "def", "move", "(", "self", ",", "new_container", ",", "new_obj_name", "=", "None", ",", "extra_info", "=", "None", ")", ":", "return", "self", ".", "container", ".", "move_object", "(", "self", ",", "new_container", ",", "new_obj_name", "=", "new_obj_name",...
46.625
17.875
def button_clicked(self, button): """Action when button was clicked. Parameters ---------- button : instance of QPushButton which button was pressed """ if button is self.idx_ok: fn = Path(self.filename) xp_format = self.xp...
[ "def", "button_clicked", "(", "self", ",", "button", ")", ":", "if", "button", "is", "self", ".", "idx_ok", ":", "fn", "=", "Path", "(", "self", ".", "filename", ")", "xp_format", "=", "self", ".", "xp_format", ".", "get_value", "(", ")", "if", "self...
36.043478
16.673913
def print_fn(results, niter, ncall, add_live_it=None, dlogz=None, stop_val=None, nbatch=None, logl_min=-np.inf, logl_max=np.inf): """ The default function used to print out results in real time. Parameters ---------- results : tuple Collection of variables output ...
[ "def", "print_fn", "(", "results", ",", "niter", ",", "ncall", ",", "add_live_it", "=", "None", ",", "dlogz", "=", "None", ",", "stop_val", "=", "None", ",", "nbatch", "=", "None", ",", "logl_min", "=", "-", "np", ".", "inf", ",", "logl_max", "=", ...
36.441667
20.658333
def get_cluster_port_names(self, cluster_name): """ return a list of the port names under XIV CLuster """ port_names = list() for host_name in self.get_hosts_by_clusters()[cluster_name]: port_names.extend(self.get_hosts_by_name(host_name)) return port_names
[ "def", "get_cluster_port_names", "(", "self", ",", "cluster_name", ")", ":", "port_names", "=", "list", "(", ")", "for", "host_name", "in", "self", ".", "get_hosts_by_clusters", "(", ")", "[", "cluster_name", "]", ":", "port_names", ".", "extend", "(", "self...
50.166667
14.833333
def complexity_entropy_svd(signal, tau=1, emb_dim=2): """ Computes the Singular Value Decomposition (SVD) entropy of a signal. Based on the `pyrem <https://github.com/gilestrolab/pyrem>`_ repo by Quentin Geissmann. Parameters ---------- signal : list or array List or array of values. ta...
[ "def", "complexity_entropy_svd", "(", "signal", ",", "tau", "=", "1", ",", "emb_dim", "=", "2", ")", ":", "mat", "=", "_embed_seq", "(", "signal", ",", "tau", ",", "emb_dim", ")", "W", "=", "np", ".", "linalg", ".", "svd", "(", "mat", ",", "compute...
27.816327
30.142857
def get_clinvar_submission(store, institute_id, case_name, variant_id, submission_id): """Collects all variants from the clinvar submission collection with a specific submission_id Args: store(scout.adapter.MongoAdapter) institute_id(str): Institute ID case_name(str): ca...
[ "def", "get_clinvar_submission", "(", "store", ",", "institute_id", ",", "case_name", ",", "variant_id", ",", "submission_id", ")", ":", "institute_obj", ",", "case_obj", "=", "institute_and_case", "(", "store", ",", "institute_id", ",", "case_name", ")", "pinned"...
39.296296
20.037037
def absent(name, deployment_id, metric_name, api_key=None, profile="telemetry"): ''' Ensure the telemetry alert config is deleted name An optional description of the alarms (not currently supported by telemetry API) deployment_id Specifies the ID of the root deployment resource ...
[ "def", "absent", "(", "name", ",", "deployment_id", ",", "metric_name", ",", "api_key", "=", "None", ",", "profile", "=", "\"telemetry\"", ")", ":", "ret", "=", "{", "'name'", ":", "metric_name", ",", "'result'", ":", "True", ",", "'comment'", ":", "''",...
37.454545
30.272727
def prior_to_xarray(self): """Convert prior samples to xarray.""" data = self.prior if not isinstance(data, dict): raise TypeError("DictConverter.prior is not a dictionary") return dict_to_dataset(data, library=None, coords=self.coords, dims=self.dims)
[ "def", "prior_to_xarray", "(", "self", ")", ":", "data", "=", "self", ".", "prior", "if", "not", "isinstance", "(", "data", ",", "dict", ")", ":", "raise", "TypeError", "(", "\"DictConverter.prior is not a dictionary\"", ")", "return", "dict_to_dataset", "(", ...
41.571429
21
def _set_hello_status(self, v, load=False): """ Setter method for hello_status, mapped from YANG variable /mpls_state/rsvp/interfaces/hello_status (feature-config-status) If this variable is read-only (config: false) in the source YANG file, then _set_hello_status is considered as a private method. ...
[ "def", "_set_hello_status", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", "v", ",", "b...
90.708333
45.5
def convex_comb_agg_log(model,a,b): """convex_comb_agg_log -- add piecewise relation with a logarithmic number of binary variables using the convex combination formulation -- non-disaggregated. Parameters: - model: a model where to include the piecewise linear relation - a[k]: x-coordinate o...
[ "def", "convex_comb_agg_log", "(", "model", ",", "a", ",", "b", ")", ":", "K", "=", "len", "(", "a", ")", "-", "1", "G", "=", "int", "(", "math", ".", "ceil", "(", "(", "math", ".", "log", "(", "K", ")", "/", "math", ".", "log", "(", "2", ...
42.8
20.725
def add_edge(self, x, y, label=None): """Add an edge from distribution *x* to distribution *y* with the given *label*. :type x: :class:`distutils2.database.InstalledDistribution` or :class:`distutils2.database.EggInfoDistribution` :type y: :class:`distutils2.database.In...
[ "def", "add_edge", "(", "self", ",", "x", ",", "y", ",", "label", "=", "None", ")", ":", "self", ".", "adjacency_list", "[", "x", "]", ".", "append", "(", "(", "y", ",", "label", ")", ")", "# multiple edges are allowed, so be careful", "if", "x", "not"...
45.428571
14.285714
def strip_exts(s, exts): """ Given a string and an interable of extensions, strip the extenion off the string if the string ends with one of the extensions. """ f_split = os.path.splitext(s) if f_split[1] in exts: return f_split[0] else: return s
[ "def", "strip_exts", "(", "s", ",", "exts", ")", ":", "f_split", "=", "os", ".", "path", ".", "splitext", "(", "s", ")", "if", "f_split", "[", "1", "]", "in", "exts", ":", "return", "f_split", "[", "0", "]", "else", ":", "return", "s" ]
28.1
16.1
def handler_for_name(fq_name): """Resolves and instantiates handler by fully qualified name. First resolves the name using for_name call. Then if it resolves to a class, instantiates a class, if it resolves to a method - instantiates the class and binds method to the instance. Args: fq_name: fully quali...
[ "def", "handler_for_name", "(", "fq_name", ")", ":", "resolved_name", "=", "for_name", "(", "fq_name", ")", "if", "isinstance", "(", "resolved_name", ",", "(", "type", ",", "types", ".", "ClassType", ")", ")", ":", "# create new instance if this is type", "retur...
33.454545
20.272727
def line(darray, *args, **kwargs): """ Line plot of DataArray index against values Wraps :func:`matplotlib:matplotlib.pyplot.plot` Parameters ---------- darray : DataArray Must be 1 dimensional figsize : tuple, optional A tuple (width, height) of the figure in inches. ...
[ "def", "line", "(", "darray", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# Handle facetgrids first", "row", "=", "kwargs", ".", "pop", "(", "'row'", ",", "None", ")", "col", "=", "kwargs", ".", "pop", "(", "'col'", ",", "None", ")", "if"...
38.985612
17.330935
def Nu_vertical_plate_Churchill(Pr, Gr): r'''Calculates Nusselt number for natural convection around a vertical plate according to the Churchill-Chu [1]_ correlation, also presented in [2]_. Plate must be isothermal; an alternate expression exists for constant heat flux. .. math:: Nu_{L}=\l...
[ "def", "Nu_vertical_plate_Churchill", "(", "Pr", ",", "Gr", ")", ":", "Ra", "=", "Pr", "*", "Gr", "Nu", "=", "(", "0.825", "+", "(", "0.387", "*", "Ra", "**", "(", "1", "/", "6.", ")", "/", "(", "1", "+", "(", "0.492", "/", "Pr", ")", "**", ...
30.792453
27.358491
def authorization_url(self, response, state=""): """ Return the authorization url that's needed to authorize as a user. :param response: Can be either code or pin. If it's code the user will be redirected to your redirect url with the code as a get parameter after author...
[ "def", "authorization_url", "(", "self", ",", "response", ",", "state", "=", "\"\"", ")", ":", "return", "AUTHORIZE_URL", ".", "format", "(", "self", ".", "_base_url", ",", "self", ".", "client_id", ",", "response", ",", "state", ")" ]
59.315789
26.578947
def copy(self): """Returns a copy of the context.""" other = ContextModel(self._context, self.parent()) other._stale = self._stale other._modified = self._modified other.request = self.request[:] other.packages_path = self.packages_path other.implicit_packages = s...
[ "def", "copy", "(", "self", ")", ":", "other", "=", "ContextModel", "(", "self", ".", "_context", ",", "self", ".", "parent", "(", ")", ")", "other", ".", "_stale", "=", "self", ".", "_stale", "other", ".", "_modified", "=", "self", ".", "_modified",...
42.846154
11.153846
def check_call_out(command): """ Run the given command (with shell=False) and return the output as a string. Strip the output of enclosing whitespace. If the return code is non-zero, throw GitInvocationError. """ # start external command process p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr...
[ "def", "check_call_out", "(", "command", ")", ":", "# start external command process", "p", "=", "subprocess", ".", "Popen", "(", "command", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "stderr", "=", "subprocess", ".", "PIPE", ")", "# get outputs", "ou...
30.647059
20.294118
def get_coinc_def_id(xmldoc, search, coinc_type, create_new = True, description = u""): """ Wrapper for the get_coinc_def_id() method of the CoincDefiner table class in pycbc_glue.ligolw.lsctables. This wrapper will optionally create a new coinc_definer table in the document if one does not already exist. """ t...
[ "def", "get_coinc_def_id", "(", "xmldoc", ",", "search", ",", "coinc_type", ",", "create_new", "=", "True", ",", "description", "=", "u\"\"", ")", ":", "try", ":", "coincdeftable", "=", "lsctables", ".", "CoincDefTable", ".", "get_table", "(", "xmldoc", ")",...
38.619048
22.904762
def format_field_by_match(self, value, match): """Formats a field by a Regex match of the format spec pattern.""" groups = match.groups() fill, align, sign, sharp, zero, width, comma, prec, type_ = groups if not comma and not prec and type_ not in list('fF%'): return None ...
[ "def", "format_field_by_match", "(", "self", ",", "value", ",", "match", ")", ":", "groups", "=", "match", ".", "groups", "(", ")", "fill", ",", "align", ",", "sign", ",", "sharp", ",", "zero", ",", "width", ",", "comma", ",", "prec", ",", "type_", ...
43.4375
15.0625
def draw_graph(self, line_kwargs=None, scatter_kwargs=None, **kwargs): """Draws the graph. Uses matplotlib, specifically :class:`~matplotlib.collections.LineCollection` and :meth:`~matplotlib.axes.Axes.scatter`. Gets the default keyword arguments for both methods by calling ...
[ "def", "draw_graph", "(", "self", ",", "line_kwargs", "=", "None", ",", "scatter_kwargs", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "not", "HAS_MATPLOTLIB", ":", "raise", "ImportError", "(", "\"Matplotlib is required to draw the graph.\"", ")", "fig"...
35.257143
20.828571
def create_order_keyword_list(keywords): """ Takes a given keyword list and returns a ready-to-go list of possible ordering values. Example: ['foo'] returns [('foo', ''), ('-foo', '')] """ result = [] for keyword in keywords: result.append((keyword, '')) result.append(('-%s...
[ "def", "create_order_keyword_list", "(", "keywords", ")", ":", "result", "=", "[", "]", "for", "keyword", "in", "keywords", ":", "result", ".", "append", "(", "(", "keyword", ",", "''", ")", ")", "result", ".", "append", "(", "(", "'-%s'", "%", "keywor...
28.666667
11.916667
def _detect_multi_byte(self, fb): # type: (str) -> bool """ _detect_multi_byte returns whether the AbstractUVarIntField is represented on # noqa: E501 multiple bytes or not. A multibyte representation is indicated by all of the first size bits being set # noqa: E501 @para...
[ "def", "_detect_multi_byte", "(", "self", ",", "fb", ")", ":", "# type: (str) -> bool", "assert", "(", "isinstance", "(", "fb", ",", "int", ")", "or", "len", "(", "fb", ")", "==", "1", ")", "return", "(", "orb", "(", "fb", ")", "&", "self", ".", "_...
43.692308
19.076923
def unparse(text, entities, delimiters=None, url_fmt=None): """ Performs the reverse operation to .parse(), effectively returning markdown-like syntax given a normal text and its MessageEntity's. :param text: the text to be reconverted into markdown. :param entities: the MessageEntity's applied to ...
[ "def", "unparse", "(", "text", ",", "entities", ",", "delimiters", "=", "None", ",", "url_fmt", "=", "None", ")", ":", "if", "not", "text", "or", "not", "entities", ":", "return", "text", "if", "not", "delimiters", ":", "if", "delimiters", "is", "not",...
36.724638
18.666667
def delete_record(self, identifier=None, rtype=None, name=None, content=None, **kwargs): """ Delete an existing record. If record does not exist, do nothing. If an identifier is specified, use it, otherwise do a lookup using type, name and content. """ if not rtype and kw...
[ "def", "delete_record", "(", "self", ",", "identifier", "=", "None", ",", "rtype", "=", "None", ",", "name", "=", "None", ",", "content", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "not", "rtype", "and", "kwargs", ".", "get", "(", "'type...
49.416667
22.25
def get_microscope_files(self, plate_name, acquisition_name): '''Gets status and name of files that have been registered for upload. Parameters ---------- plate_name: str name of the parent plate acquisition_name: str name of the parent acquisition ...
[ "def", "get_microscope_files", "(", "self", ",", "plate_name", ",", "acquisition_name", ")", ":", "logger", ".", "info", "(", "'get names of already uploaded files for experiment \"%s\", '", "'plate \"%s\" and acquisition \"%s\"'", ",", "self", ".", "experiment_name", ",", ...
38.4375
23.3125
def getExperiment(uuid: str, exp_id: str): """ Fetch experiment results""" experimentResult = ForwardProjectionResult.query.filter_by( id=exp_id ).first() return jsonify(experimentResult.deserialize())
[ "def", "getExperiment", "(", "uuid", ":", "str", ",", "exp_id", ":", "str", ")", ":", "experimentResult", "=", "ForwardProjectionResult", ".", "query", ".", "filter_by", "(", "id", "=", "exp_id", ")", ".", "first", "(", ")", "return", "jsonify", "(", "ex...
36.666667
14.166667
def plot_power_factor_dop(self, temps='all', output='average', relaxation_time=1e-14): """ Plot the Power Factor in function of doping levels for different temperatures. Args: temps: the default 'all' plots all the temperatures in the analyzer. ...
[ "def", "plot_power_factor_dop", "(", "self", ",", "temps", "=", "'all'", ",", "output", "=", "'average'", ",", "relaxation_time", "=", "1e-14", ")", ":", "import", "matplotlib", ".", "pyplot", "as", "plt", "if", "output", "==", "'average'", ":", "pf", "=",...
44.235294
20.27451
def _request(self, method, url, params=None, headers=None, data=None): """Common handler for all the HTTP requests.""" if not params: params = {} # set default headers if not headers: headers = { 'accept': '*/*' } if method...
[ "def", "_request", "(", "self", ",", "method", ",", "url", ",", "params", "=", "None", ",", "headers", "=", "None", ",", "data", "=", "None", ")", ":", "if", "not", "params", ":", "params", "=", "{", "}", "# set default headers", "if", "not", "header...
42.590909
23.113636
def get_bounds(pts): """Return the minimum point and maximum point bounding a set of points.""" pts_t = np.asarray(pts).T return np.asarray(([np.min(_pts) for _pts in pts_t], [np.max(_pts) for _pts in pts_t]))
[ "def", "get_bounds", "(", "pts", ")", ":", "pts_t", "=", "np", ".", "asarray", "(", "pts", ")", ".", "T", "return", "np", ".", "asarray", "(", "(", "[", "np", ".", "min", "(", "_pts", ")", "for", "_pts", "in", "pts_t", "]", ",", "[", "np", "....
40.5
10.666667
def append_body(self, dom: str): """ Appends the specified HTML-formatted DOM string to the currently stored report body for the step. """ self.flush_stdout() self.body.append(dom) self._last_update_time = time.time()
[ "def", "append_body", "(", "self", ",", "dom", ":", "str", ")", ":", "self", ".", "flush_stdout", "(", ")", "self", ".", "body", ".", "append", "(", "dom", ")", "self", ".", "_last_update_time", "=", "time", ".", "time", "(", ")" ]
33.25
8.5
async def reload_modules(self, pathlist): """ Reload modules with a full path in the pathlist """ loadedModules = [] failures = [] for path in pathlist: p, module = findModule(path, False) if module is not None and hasattr(module, '_instance') and ...
[ "async", "def", "reload_modules", "(", "self", ",", "pathlist", ")", ":", "loadedModules", "=", "[", "]", "failures", "=", "[", "]", "for", "path", "in", "pathlist", ":", "p", ",", "module", "=", "findModule", "(", "path", ",", "False", ")", "if", "m...
49.621951
18.865854
def graph_from_connections(env, directed=False): """Create NetworkX graph from agent connections in a given environment. :param env: Environment where the agents live. The environment must be derived from :class:`~creamas.core.environment.Environment`, :class:`~creamas.mp.MultiEnvironme...
[ "def", "graph_from_connections", "(", "env", ",", "directed", "=", "False", ")", ":", "G", "=", "DiGraph", "(", ")", "if", "directed", "else", "Graph", "(", ")", "conn_list", "=", "env", ".", "get_connections", "(", "data", "=", "True", ")", "for", "ag...
36.939394
20.212121
def file_upload(object_id, input_params={}, always_retry=True, **kwargs): """ Invokes the /file-xxxx/upload API method. For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Files#API-method%3A-%2Ffile-xxxx%2Fupload """ return DXHTTPRequest('/%s/upload' % object_id, input_params, a...
[ "def", "file_upload", "(", "object_id", ",", "input_params", "=", "{", "}", ",", "always_retry", "=", "True", ",", "*", "*", "kwargs", ")", ":", "return", "DXHTTPRequest", "(", "'/%s/upload'", "%", "object_id", ",", "input_params", ",", "always_retry", "=", ...
49.857143
30.714286
def run(self, timeout=None, **kwargs): """ Run a command in a separated thread and wait timeout seconds. kwargs are keyword arguments passed to Popen. Return: self """ from subprocess import Popen, PIPE def target(**kw): try: # print(...
[ "def", "run", "(", "self", ",", "timeout", "=", "None", ",", "*", "*", "kwargs", ")", ":", "from", "subprocess", "import", "Popen", ",", "PIPE", "def", "target", "(", "*", "*", "kw", ")", ":", "try", ":", "# print('Thread started')", "self", ".", "pr...
28.95122
16.463415
def _get_args_and_defaults(args, defaults): """Return a list of 2-tuples - the argument name and its default value or a special value that indicates there is no default value. Args: args: list of argument name defaults: tuple of default values """ defaults = defaults or [] a...
[ "def", "_get_args_and_defaults", "(", "args", ",", "defaults", ")", ":", "defaults", "=", "defaults", "or", "[", "]", "args_and_defaults", "=", "[", "(", "argument", ",", "default", ")", "for", "(", "argument", ",", "default", ")", "in", "zip_longest", "("...
41.230769
15.230769
def creators(self): """ Return a list of creator nodes. Note: Does not add anything to the graph. """ return map(lambda c: Literal(c.to_value()), self.document.creation_info.creators)
[ "def", "creators", "(", "self", ")", ":", "return", "map", "(", "lambda", "c", ":", "Literal", "(", "c", ".", "to_value", "(", ")", ")", ",", "self", ".", "document", ".", "creation_info", ".", "creators", ")" ]
36.333333
13.333333
def set_public_lan(lan_id): ''' Enables public Internet access for the specified public_lan. If no public LAN is available, then a new public LAN is created. ''' conn = get_conn() datacenter_id = get_datacenter_id() try: lan = conn.get_lan(datacenter_id=datacenter_id, lan_id=lan_id)...
[ "def", "set_public_lan", "(", "lan_id", ")", ":", "conn", "=", "get_conn", "(", ")", "datacenter_id", "=", "get_datacenter_id", "(", ")", "try", ":", "lan", "=", "conn", ".", "get_lan", "(", "datacenter_id", "=", "datacenter_id", ",", "lan_id", "=", "lan_i...
35.2
17.4
def getLevelName(level): """ Return the name of a log level. @param level: The level we want to know the name @type level: int @return: The name of the level @rtype: str """ assert isinstance(level, int) and level > 0 and level < 6, \ TypeError("Bad debug level") return ge...
[ "def", "getLevelName", "(", "level", ")", ":", "assert", "isinstance", "(", "level", ",", "int", ")", "and", "level", ">", "0", "and", "level", "<", "6", ",", "TypeError", "(", "\"Bad debug level\"", ")", "return", "getLevelNames", "(", ")", "[", "level"...
30.363636
10.181818
def _set_ldp_fec_prefixes(self, v, load=False): """ Setter method for ldp_fec_prefixes, mapped from YANG variable /mpls_state/ldp/fec/ldp_fec_prefixes (container) If this variable is read-only (config: false) in the source YANG file, then _set_ldp_fec_prefixes is considered as a private method. Back...
[ "def", "_set_ldp_fec_prefixes", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", "v", ",", ...
81.954545
38.318182
def constructor( self, name=None, function=None, return_type=None, arg_types=None, header_dir=None, header_file=None, recursive=None): """returns reference to constructor declaration, that is matched defined ...
[ "def", "constructor", "(", "self", ",", "name", "=", "None", ",", "function", "=", "None", ",", "return_type", "=", "None", ",", "arg_types", "=", "None", ",", "header_dir", "=", "None", ",", "header_file", "=", "None", ",", "recursive", "=", "None", "...
32.416667
11.041667
def get_additional_actions(self, reftrack): """Return a list of additional actions you want to provide for the menu of the reftrack. E.e. you want to have a menu entry, that will select the entity in your programm. This will call :meth:`ReftypeInterface.get_additional_actions`. ...
[ "def", "get_additional_actions", "(", "self", ",", "reftrack", ")", ":", "inter", "=", "self", ".", "get_typ_interface", "(", "reftrack", ".", "get_typ", "(", ")", ")", "return", "inter", ".", "get_additional_actions", "(", "reftrack", ")" ]
37.666667
21
def get_stats(a, full=False): """Compute and print statistics for input array Needs to be cleaned up, return a stats object """ from scipy.stats.mstats import mode a = checkma(a) thresh = 4E6 if full or a.count() < thresh: q = (iqr(a)) p16, p84, spread = robust_spread(a) ...
[ "def", "get_stats", "(", "a", ",", "full", "=", "False", ")", ":", "from", "scipy", ".", "stats", ".", "mstats", "import", "mode", "a", "=", "checkma", "(", "a", ")", "thresh", "=", "4E6", "if", "full", "or", "a", ".", "count", "(", ")", "<", "...
42.931034
18.310345
def write(self, b): '''write some bytes''' from . import mavutil self.debug("sending '%s' (0x%02x) of len %u\n" % (b, ord(b[0]), len(b)), 2) while len(b) > 0: n = len(b) if n > 70: ...
[ "def", "write", "(", "self", ",", "b", ")", ":", "from", ".", "import", "mavutil", "self", ".", "debug", "(", "\"sending '%s' (0x%02x) of len %u\\n\"", "%", "(", "b", ",", "ord", "(", "b", "[", "0", "]", ")", ",", "len", "(", "b", ")", ")", ",", ...
54.055556
20.055556
def _get_data(self): """Process the IGRA2 text file for observations at site_id matching time. Return: ------- :class: `pandas.DataFrame` containing the body data. :class: `pandas.DataFrame` containing the header data. """ # Split the list of times into b...
[ "def", "_get_data", "(", "self", ")", ":", "# Split the list of times into begin and end dates. If only", "# one date is supplied, set both begin and end dates equal to that date.", "body", ",", "header", ",", "dates_long", ",", "dates", "=", "self", ".", "_get_data_raw", "(", ...
35.5
22.416667
async def auth_crypt(wallet_handle: int, sender_vk: str, recipient_vk: str, msg: bytes) -> bytes: """ **** THIS FUNCTION WILL BE DEPRECATED USE pack_message INSTEAD **** Encrypt a message by authenticated-encryption scheme. Sender can encr...
[ "async", "def", "auth_crypt", "(", "wallet_handle", ":", "int", ",", "sender_vk", ":", "str", ",", "recipient_vk", ":", "str", ",", "msg", ":", "bytes", ")", "->", "bytes", ":", "logger", "=", "logging", ".", "getLogger", "(", "__name__", ")", "logger", ...
40.509091
21.672727
def _create_attr(self, property_key, data, ancestors): """ Dynamically Creates attributes on for a Config. Also adds name and alias to each Config object. :param property_key: A :string: configuration property name. :param data: The adds the user supplied for this specific property. :p...
[ "def", "_create_attr", "(", "self", ",", "property_key", ",", "data", ",", "ancestors", ")", ":", "if", "not", "isinstance", "(", "property_key", ",", "six", ".", "string_types", ")", ":", "raise", "TypeError", "(", "\"property_key must be a string. type: {0} was ...
43.913043
25.804348
def get_default_field_names(self, declared_fields, model_info): """ Return the default list of field names that will be used if the `Meta.fields` option is not specified. """ return ( [model_info.pk.name] + list(declared_fields.keys()) + list(m...
[ "def", "get_default_field_names", "(", "self", ",", "declared_fields", ",", "model_info", ")", ":", "return", "(", "[", "model_info", ".", "pk", ".", "name", "]", "+", "list", "(", "declared_fields", ".", "keys", "(", ")", ")", "+", "list", "(", "model_i...
36.363636
12.727273
def create_room(self, payload): ''' create a stream in a non-inclusive manner ''' response, status_code = self.__pod__.Streams.post_v2_room_create( # V2RoomAttributes payload=payload ).result() self.logger.debug('%s: %s' % (status_code, response)) return s...
[ "def", "create_room", "(", "self", ",", "payload", ")", ":", "response", ",", "status_code", "=", "self", ".", "__pod__", ".", "Streams", ".", "post_v2_room_create", "(", "# V2RoomAttributes", "payload", "=", "payload", ")", ".", "result", "(", ")", "self", ...
41.625
16.125
def QA_fetch_get_index_list(ip=None, port=None): """获取指数列表 Keyword Arguments: ip {[type]} -- [description] (default: {None}) port {[type]} -- [description] (default: {None}) Returns: [type] -- [description] """ ip, port = get_mainmarket_ip(ip, port) api = TdxHq_API() ...
[ "def", "QA_fetch_get_index_list", "(", "ip", "=", "None", ",", "port", "=", "None", ")", ":", "ip", ",", "port", "=", "get_mainmarket_ip", "(", "ip", ",", "port", ")", "api", "=", "TdxHq_API", "(", ")", "with", "api", ".", "connect", "(", "ip", ",", ...
37.884615
20.884615
def _cnn_tranch_filtering(in_file, vrn_files, tensor_type, data): """Filter CNN scored VCFs in tranches using standard SNP and Indel truth sets. """ out_file = "%s-filter.vcf.gz" % utils.splitext_plus(in_file)[0] if not utils.file_uptodate(out_file, in_file): runner = broad.runner_from_config(da...
[ "def", "_cnn_tranch_filtering", "(", "in_file", ",", "vrn_files", ",", "tensor_type", ",", "data", ")", ":", "out_file", "=", "\"%s-filter.vcf.gz\"", "%", "utils", ".", "splitext_plus", "(", "in_file", ")", "[", "0", "]", "if", "not", "utils", ".", "file_upt...
55.909091
18.227273
def query_associated_azure_publisher(self, publisher_name): """QueryAssociatedAzurePublisher. [Preview API] :param str publisher_name: :rtype: :class:`<AzurePublisher> <azure.devops.v5_1.gallery.models.AzurePublisher>` """ route_values = {} if publisher_name is no...
[ "def", "query_associated_azure_publisher", "(", "self", ",", "publisher_name", ")", ":", "route_values", "=", "{", "}", "if", "publisher_name", "is", "not", "None", ":", "route_values", "[", "'publisherName'", "]", "=", "self", ".", "_serialize", ".", "url", "...
51.642857
19.642857
def _process_task(self, task, function_execution_info): """Execute a task assigned to this worker. This method deserializes a task from the scheduler, and attempts to execute the task. If the task succeeds, the outputs are stored in the local object store. If the task throws an exceptio...
[ "def", "_process_task", "(", "self", ",", "task", ",", "function_execution_info", ")", ":", "assert", "self", ".", "current_task_id", ".", "is_nil", "(", ")", "assert", "self", ".", "task_context", ".", "task_index", "==", "0", "assert", "self", ".", "task_c...
47.532609
19.347826
def fit(self, struct1, struct2): """ Fit two structures. Args: struct1 (Structure): 1st structure struct2 (Structure): 2nd structure Returns: True or False. """ struct1, struct2 = self._process_species([struct1, struct2]) if ...
[ "def", "fit", "(", "self", ",", "struct1", ",", "struct2", ")", ":", "struct1", ",", "struct2", "=", "self", ".", "_process_species", "(", "[", "struct1", ",", "struct2", "]", ")", "if", "not", "self", ".", "_subset", "and", "self", ".", "_comparator",...
30.28
21.48
def get_rect(self): """ Get rectangle of app or desktop resolution Returns: RECT(left, top, right, bottom) """ if self.handle: left, top, right, bottom = win32gui.GetWindowRect(self.handle) return RECT(left, top, right, bottom) else: ...
[ "def", "get_rect", "(", "self", ")", ":", "if", "self", ".", "handle", ":", "left", ",", "top", ",", "right", ",", "bottom", "=", "win32gui", ".", "GetWindowRect", "(", "self", ".", "handle", ")", "return", "RECT", "(", "left", ",", "top", ",", "ri...
31.733333
18.133333
def get_notebook_object(self, notebook_id): """Get the NotebookNode representation of a notebook by notebook_id.""" path = self.find_path(notebook_id) if not os.path.isfile(path): raise web.HTTPError(404, u'Notebook does not exist: %s' % notebook_id) info = os.stat(path) ...
[ "def", "get_notebook_object", "(", "self", ",", "notebook_id", ")", ":", "path", "=", "self", ".", "find_path", "(", "notebook_id", ")", "if", "not", "os", ".", "path", ".", "isfile", "(", "path", ")", ":", "raise", "web", ".", "HTTPError", "(", "404",...
47.352941
15.882353
def extract_signature(msg_body): ''' Analyzes message for a presence of signature block (by common patterns) and returns tuple with two elements: message text without signature block and the signature itself. >>> extract_signature('Hey man! How r u?\n\n--\nRegards,\nRoman') ('Hey man! How r u?'...
[ "def", "extract_signature", "(", "msg_body", ")", ":", "try", ":", "# identify line delimiter first", "delimiter", "=", "get_delimiter", "(", "msg_body", ")", "# make an assumption", "stripped_body", "=", "msg_body", ".", "strip", "(", ")", "phone_signature", "=", "...
35.230769
17.807692
def stop(self, reason=None): """Shutdown the service with a reason.""" self.logger.info('stopping') self.loop.stop(pyev.EVBREAK_ALL)
[ "def", "stop", "(", "self", ",", "reason", "=", "None", ")", ":", "self", ".", "logger", ".", "info", "(", "'stopping'", ")", "self", ".", "loop", ".", "stop", "(", "pyev", ".", "EVBREAK_ALL", ")" ]
38.25
4
def register(cls, plugin): """Register a new :class:`KurtPlugin`. Once registered, the plugin can be used by :class:`Project`, when: * :attr:`Project.load` sees a file with the right extension * :attr:`Project.convert` is called with the format as a parameter """ cls....
[ "def", "register", "(", "cls", ",", "plugin", ")", ":", "cls", ".", "plugins", "[", "plugin", ".", "name", "]", "=", "plugin", "# make features", "plugin", ".", "features", "=", "map", "(", "Feature", ".", "get", ",", "plugin", ".", "features", ")", ...
31.361111
19.388889
def check_is_declared(self, id_, lineno, classname='identifier', scope=None, show_error=True): """ Checks if the given id is already defined in any scope or raises a Syntax Error. Note: classname is not the class attribute, but the name of the class...
[ "def", "check_is_declared", "(", "self", ",", "id_", ",", "lineno", ",", "classname", "=", "'identifier'", ",", "scope", "=", "None", ",", "show_error", "=", "True", ")", ":", "result", "=", "self", ".", "get_entry", "(", "id_", ",", "scope", ")", "if"...
39.470588
17.411765
def _rnaseq_qualimap_cmd(data, bam_file, out_dir, gtf_file=None, library="non-strand-specific"): """ Create command lines for qualimap """ config = data["config"] qualimap = config_utils.get_program("qualimap", config) resources = config_utils.get_resources("qualimap", config) num_cores = re...
[ "def", "_rnaseq_qualimap_cmd", "(", "data", ",", "bam_file", ",", "out_dir", ",", "gtf_file", "=", "None", ",", "library", "=", "\"non-strand-specific\"", ")", ":", "config", "=", "data", "[", "\"config\"", "]", "qualimap", "=", "config_utils", ".", "get_progr...
54.277778
22.611111
def create(self, callback_url, trigger_value, usage_category, callback_method=values.unset, friendly_name=values.unset, recurring=values.unset, trigger_by=values.unset): """ Create a new TriggerInstance :param unicode callback_url: The URL we call when the trigger ...
[ "def", "create", "(", "self", ",", "callback_url", ",", "trigger_value", ",", "usage_category", ",", "callback_method", "=", "values", ".", "unset", ",", "friendly_name", "=", "values", ".", "unset", ",", "recurring", "=", "values", ".", "unset", ",", "trigg...
45.029412
24.735294
def get_descriptor_by_id(self, id, is_master_id=None): """GetDescriptorById. [Preview API] :param str id: :param bool is_master_id: :rtype: :class:`<str> <azure.devops.v5_0.identity.models.str>` """ route_values = {} if id is not None: route_va...
[ "def", "get_descriptor_by_id", "(", "self", ",", "id", ",", "is_master_id", "=", "None", ")", ":", "route_values", "=", "{", "}", "if", "id", "is", "not", "None", ":", "route_values", "[", "'id'", "]", "=", "self", ".", "_serialize", ".", "url", "(", ...
46.368421
17.736842
def recvmsgs(sk, cb): """https://github.com/thom311/libnl/blob/libnl3_2_25/lib/nl.c#L775. This is where callbacks are called. Positional arguments: sk -- Netlink socket (nl_sock class instance). cb -- callbacks (nl_cb class instance). Returns: Number of bytes received or a negative error ...
[ "def", "recvmsgs", "(", "sk", ",", "cb", ")", ":", "multipart", "=", "0", "interrupted", "=", "0", "nrecv", "=", "0", "buf", "=", "bytearray", "(", ")", "# nla is passed on to not only to nl_recv() but may also be passed to a function pointer provided by the caller", "#...
46.131687
21.358025
def set_pubnote(self, pubnote): """Parse pubnote and populate correct fields.""" if 'publication_info' in self.obj.get('reference', {}): self.add_misc(u'Additional pubnote: {}'.format(pubnote)) return if self.RE_VALID_PUBNOTE.match(pubnote): pubnote = split_p...
[ "def", "set_pubnote", "(", "self", ",", "pubnote", ")", ":", "if", "'publication_info'", "in", "self", ".", "obj", ".", "get", "(", "'reference'", ",", "{", "}", ")", ":", "self", ".", "add_misc", "(", "u'Additional pubnote: {}'", ".", "format", "(", "pu...
42.916667
18.916667
def read(self, how_much=128): # FIXME: 128 might be too much ... what is largest? """ This toggles the RTS pin and reads in data. It also converts the buffer back into a list of bytes and searches through the list to find valid packets of info. If there is more than one packet, this returns an array of valid...
[ "def", "read", "(", "self", ",", "how_much", "=", "128", ")", ":", "# FIXME: 128 might be too much ... what is largest?", "# ret = self.readPkts(how_much)", "# return ret", "ret", "=", "[", "]", "self", ".", "setRTS", "(", "self", ".", "DD_READ", ")", "# this in_wai...
31.407407
19.481481
def add_line(self, line): """ Adds a given line string to the list of lines, validating the line first. """ if not self.is_valid_line(line): logger.warn( "Invalid line for %s section: '%s'", self.section_name, line ) ...
[ "def", "add_line", "(", "self", ",", "line", ")", ":", "if", "not", "self", ".", "is_valid_line", "(", "line", ")", ":", "logger", ".", "warn", "(", "\"Invalid line for %s section: '%s'\"", ",", "self", ".", "section_name", ",", "line", ")", "return", "sel...
27.076923
15.538462
def LoadFirmwareImage(chip, filename): """ Load a firmware image. Can be for ESP8266 or ESP32. ESP8266 images will be examined to determine if they are original ROM firmware images (ESP8266ROMFirmwareImage) or "v2" OTA bootloader images. Returns a BaseFirmwareImage subclass, either ESP8266ROMFirmwa...
[ "def", "LoadFirmwareImage", "(", "chip", ",", "filename", ")", ":", "with", "open", "(", "filename", ",", "'rb'", ")", "as", "f", ":", "if", "chip", ".", "lower", "(", ")", "==", "'esp32'", ":", "return", "ESP32FirmwareImage", "(", "f", ")", "else", ...
50.277778
19