text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def reset_scorer(self): """Reset the scorer used for couration.""" self.scorer = get_eidos_bayesian_scorer() for corpus_id, corpus in self.corpora.items(): corpus.curations = {}
[ "def", "reset_scorer", "(", "self", ")", ":", "self", ".", "scorer", "=", "get_eidos_bayesian_scorer", "(", ")", "for", "corpus_id", ",", "corpus", "in", "self", ".", "corpora", ".", "items", "(", ")", ":", "corpus", ".", "curations", "=", "{", "}" ]
41.8
9.4
def plot_nodes(self, nodelist, theta, group): """ Plots nodes to screen. """ for i, node in enumerate(nodelist): r = self.internal_radius + i * self.scale x, y = get_cartesian(r, theta) circle = plt.Circle(xy=(x, y), radius=self.dot_radius, ...
[ "def", "plot_nodes", "(", "self", ",", "nodelist", ",", "theta", ",", "group", ")", ":", "for", "i", ",", "node", "in", "enumerate", "(", "nodelist", ")", ":", "r", "=", "self", ".", "internal_radius", "+", "i", "*", "self", ".", "scale", "x", ",",...
41.5
9.9
def get_time_remaining_estimate(self): """ Looks through all power sources and returns total time remaining estimate or TIME_REMAINING_UNLIMITED if ac power supply is online. """ all_energy_now = [] all_power_now = [] try: type = self.power_source_type...
[ "def", "get_time_remaining_estimate", "(", "self", ")", ":", "all_energy_now", "=", "[", "]", "all_power_now", "=", "[", "]", "try", ":", "type", "=", "self", ".", "power_source_type", "(", ")", "if", "type", "==", "common", ".", "POWER_TYPE_AC", ":", "if"...
47.833333
21.5
def recordHostname(self, basedir): "Record my hostname in twistd.hostname, for user convenience" log.msg("recording hostname in twistd.hostname") filename = os.path.join(basedir, "twistd.hostname") try: hostname = os.uname()[1] # only on unix except AttributeError: ...
[ "def", "recordHostname", "(", "self", ",", "basedir", ")", ":", "log", ".", "msg", "(", "\"recording hostname in twistd.hostname\"", ")", "filename", "=", "os", ".", "path", ".", "join", "(", "basedir", ",", "\"twistd.hostname\"", ")", "try", ":", "hostname", ...
36
17.764706
def predict(self, X, batch_size=1, show_progressbar=False): """ Predict the BMU for each input data. Parameters ---------- X : numpy array. The input data. batch_size : int, optional, default 100 The batch size to use in prediction. This may affec...
[ "def", "predict", "(", "self", ",", "X", ",", "batch_size", "=", "1", ",", "show_progressbar", "=", "False", ")", ":", "dist", "=", "self", ".", "transform", "(", "X", ",", "batch_size", ",", "show_progressbar", ")", "res", "=", "dist", ".", "__getattr...
30.5
19.666667
def parse_value_objectwithpath(self, tup_tree): """ :: <!ELEMENT VALUE.OBJECTWITHPATH ((CLASSPATH, CLASS) | (INSTANCEPATH, INSTANCE))> Returns: tupletree with child item that is: - for class-level use: a tuple(CI...
[ "def", "parse_value_objectwithpath", "(", "self", ",", "tup_tree", ")", ":", "self", ".", "check_node", "(", "tup_tree", ",", "'VALUE.OBJECTWITHPATH'", ")", "k", "=", "kids", "(", "tup_tree", ")", "if", "len", "(", "k", ")", "!=", "2", ":", "raise", "CIM...
40.357143
20.5
def _write_branch_and_tag_to_meta_yaml(self): """ Write branch and tag to meta.yaml by editing in place """ ## set the branch to pull source from with open(self.meta_yaml.replace("meta", "template"), 'r') as infile: dat = infile.read() newdat = dat.format(...
[ "def", "_write_branch_and_tag_to_meta_yaml", "(", "self", ")", ":", "## set the branch to pull source from", "with", "open", "(", "self", ".", "meta_yaml", ".", "replace", "(", "\"meta\"", ",", "\"template\"", ")", ",", "'r'", ")", "as", "infile", ":", "dat", "=...
39.909091
15.363636
def get_publisher(self, publisher_id): """GetPublisher. Get a specific service hooks publisher. :param str publisher_id: ID for a publisher. :rtype: :class:`<Publisher> <azure.devops.v5_0.service_hooks.models.Publisher>` """ route_values = {} if publisher_id is no...
[ "def", "get_publisher", "(", "self", ",", "publisher_id", ")", ":", "route_values", "=", "{", "}", "if", "publisher_id", "is", "not", "None", ":", "route_values", "[", "'publisherId'", "]", "=", "self", ".", "_serialize", ".", "url", "(", "'publisher_id'", ...
50.142857
16.357143
def bet_cancel(self, bet_to_cancel, account=None, **kwargs): """ Cancel a bet :param str bet_to_cancel: The identifier that identifies the bet to cancel :param str account: (optional) the account that owns the bet (defaults to ``default_account``) ...
[ "def", "bet_cancel", "(", "self", ",", "bet_to_cancel", ",", "account", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "not", "account", ":", "if", "\"default_account\"", "in", "self", ".", "config", ":", "account", "=", "self", ".", "config", "...
38.333333
16.541667
def list_menu(self, options, title="Choose a value", message="Choose a value", default=None, **kwargs): """ Show a single-selection list menu Usage: C{dialog.list_menu(options, title="Choose a value", message="Choose a value", default=None, **kwargs)} @param options: li...
[ "def", "list_menu", "(", "self", ",", "options", ",", "title", "=", "\"Choose a value\"", ",", "message", "=", "\"Choose a value\"", ",", "default", "=", "None", ",", "*", "*", "kwargs", ")", ":", "choices", "=", "[", "]", "optionNum", "=", "0", "for", ...
38.931034
19.275862
def set_presence(self, state, status): """ Set the presence `state` and `status` on the client. This has the same effects as writing `state` to :attr:`presence`, but the status of the presence is also set at the same time. `status` must be either a string or something which can ...
[ "def", "set_presence", "(", "self", ",", "state", ",", "status", ")", ":", "self", ".", "_presence_server", ".", "set_presence", "(", "state", ",", "status", "=", "status", ")" ]
52.375
26.25
def print_log(text, *colors): """Print a log message to standard error.""" sys.stderr.write(sprint("{}: {}".format(script_name, text), *colors) + "\n")
[ "def", "print_log", "(", "text", ",", "*", "colors", ")", ":", "sys", ".", "stderr", ".", "write", "(", "sprint", "(", "\"{}: {}\"", ".", "format", "(", "script_name", ",", "text", ")", ",", "*", "colors", ")", "+", "\"\\n\"", ")" ]
52.333333
17
def clip_bounds(bounds=None, clip=None): """ Clips bounds by clip. Parameters ---------- bounds : bounds to be clipped clip : clip bounds Returns ------- Bounds(left, bottom, right, top) """ bounds = Bounds(*bounds) clip = Bounds(*clip) return Bounds( max(bo...
[ "def", "clip_bounds", "(", "bounds", "=", "None", ",", "clip", "=", "None", ")", ":", "bounds", "=", "Bounds", "(", "*", "bounds", ")", "clip", "=", "Bounds", "(", "*", "clip", ")", "return", "Bounds", "(", "max", "(", "bounds", ".", "left", ",", ...
21.047619
15.809524
def _extract_rev(self, line1, line2): """ Extract the filename and revision hint from a line. """ try: if line1.startswith('--- ') and line2.startswith('+++ '): l1 = line1[4:].split(None, 1) old_filename = l1[0].lstrip('a/') if len(l1) >= 1 el...
[ "def", "_extract_rev", "(", "self", ",", "line1", ",", "line2", ")", ":", "try", ":", "if", "line1", ".", "startswith", "(", "'--- '", ")", "and", "line2", ".", "startswith", "(", "'+++ '", ")", ":", "l1", "=", "line1", "[", "4", ":", "]", ".", "...
35.782609
21.26087
def filter_gradient_threshold_percentile(self, analyte, percentiles, level='population', win=15, filt=False, samples=None, subset=None): """ Calculate a gradient threshold filter to the data. Generates two filters above and below the threshold value ...
[ "def", "filter_gradient_threshold_percentile", "(", "self", ",", "analyte", ",", "percentiles", ",", "level", "=", "'population'", ",", "win", "=", "15", ",", "filt", "=", "False", ",", "samples", "=", "None", ",", "subset", "=", "None", ")", ":", "params"...
40.077778
22.877778
def volume(self): """ The analytic volume of the cylinder primitive. Returns --------- volume : float Volume of the cylinder """ volume = ((np.pi * self.primitive.radius ** 2) * self.primitive.height) return volume
[ "def", "volume", "(", "self", ")", ":", "volume", "=", "(", "(", "np", ".", "pi", "*", "self", ".", "primitive", ".", "radius", "**", "2", ")", "*", "self", ".", "primitive", ".", "height", ")", "return", "volume" ]
24.666667
15.5
def is_valid_pred_string(predstr): """ Return `True` if *predstr* is a valid predicate string. Examples: >>> is_valid_pred_string('"_dog_n_1_rel"') True >>> is_valid_pred_string('_dog_n_1') True >>> is_valid_pred_string('_dog_noun_1') False >>> is_val...
[ "def", "is_valid_pred_string", "(", "predstr", ")", ":", "predstr", "=", "predstr", ".", "strip", "(", "'\"'", ")", ".", "lstrip", "(", "\"'\"", ")", "# this is a stricter regex than in Pred, but doesn't check POS", "return", "re", ".", "match", "(", "r'_([^ _\\\\]|...
29.238095
16.571429
def validator(self, meth): """ Decorator that adds *meth* to the list of validators. Returns *meth* unchanged. .. versionadded:: 17.1.0 """ if self._validator is None: self._validator = meth else: self._validator = and_(self._validator, m...
[ "def", "validator", "(", "self", ",", "meth", ")", ":", "if", "self", ".", "_validator", "is", "None", ":", "self", ".", "_validator", "=", "meth", "else", ":", "self", ".", "_validator", "=", "and_", "(", "self", ".", "_validator", ",", "meth", ")",...
25.538462
15.846154
def check_version(version: str): """ Checks given version against code version and determines compatibility. Throws if versions are incompatible. :param version: Given version. """ code_version = parse_version(__version__) given_version = parse_version(version) check_condition(code_vers...
[ "def", "check_version", "(", "version", ":", "str", ")", ":", "code_version", "=", "parse_version", "(", "__version__", ")", "given_version", "=", "parse_version", "(", "version", ")", "check_condition", "(", "code_version", "[", "0", "]", "==", "given_version",...
47.692308
21.076923
def backup(target_file, config=None): """ Backups the main ssh configuration into target file. """ storm_ = get_storm_instance(config) try: storm_.backup(target_file) except Exception as error: print(get_formatted_message(str(error), 'error'), file=sys.stderr) sys.exit(1)
[ "def", "backup", "(", "target_file", ",", "config", "=", "None", ")", ":", "storm_", "=", "get_storm_instance", "(", "config", ")", "try", ":", "storm_", ".", "backup", "(", "target_file", ")", "except", "Exception", "as", "error", ":", "print", "(", "ge...
31.1
12.3
def mkpart(device, part_type, fs_type=None, start=None, end=None): ''' Make a part_type partition for filesystem fs_type, beginning at start and ending at end (by default in megabytes). part_type should be one of "primary", "logical", or "extended". CLI Examples: .. code-block:: bash ...
[ "def", "mkpart", "(", "device", ",", "part_type", ",", "fs_type", "=", "None", ",", "start", "=", "None", ",", "end", "=", "None", ")", ":", "if", "part_type", "not", "in", "set", "(", "[", "'primary'", ",", "'logical'", ",", "'extended'", "]", ")", ...
30.95
26.55
def generate_encoded_user_data( env='dev', region='us-east-1', generated=None, group_name='', pipeline_type='', canary=False, ): r"""Generate base64 encoded User Data. Args: env (str): Deployment environment, e.g. dev, stage. region (str): AWS Reg...
[ "def", "generate_encoded_user_data", "(", "env", "=", "'dev'", ",", "region", "=", "'us-east-1'", ",", "generated", "=", "None", ",", "group_name", "=", "''", ",", "pipeline_type", "=", "''", ",", "canary", "=", "False", ",", ")", ":", "# We need to handle t...
31.849057
17.226415
def _sample_batch(): """Determine if a batch should be processed and if not, pop off all of the pending metrics for that batch. :rtype: bool """ if _sample_probability == 1.0 or random.random() < _sample_probability: return True # Pop off all the metrics for the batch for database...
[ "def", "_sample_batch", "(", ")", ":", "if", "_sample_probability", "==", "1.0", "or", "random", ".", "random", "(", ")", "<", "_sample_probability", ":", "return", "True", "# Pop off all the metrics for the batch", "for", "database", "in", "_measurements", ":", "...
29.857143
20.642857
def convert_table(self, table_name, cls_att=None): ''' Returns the specified table as an orange example table. :param table_name: table name to convert :cls_att: class attribute name :rtype: orange.ExampleTable ''' import Orange cols = self.d...
[ "def", "convert_table", "(", "self", ",", "table_name", ",", "cls_att", "=", "None", ")", ":", "import", "Orange", "cols", "=", "self", ".", "db", ".", "cols", "[", "table_name", "]", "attributes", ",", "metas", ",", "class_var", "=", "[", "]", ",", ...
43.97619
18.880952
def signature_base_string(http_method, base_str_uri, normalized_encoded_request_parameters): """**Construct the signature base string.** Per `section 3.4.1.1`_ of the spec. For example, the HTTP request:: POST /request?b5=%3D%253D&a3=a&c%40=&a2=r%20b HTTP/1.1 Host...
[ "def", "signature_base_string", "(", "http_method", ",", "base_str_uri", ",", "normalized_encoded_request_parameters", ")", ":", "# The signature base string is constructed by concatenating together,", "# in order, the following HTTP request elements:", "# 1. The HTTP request method in uppe...
39.365079
24.031746
def get_nearest_entry(self, entry, type_measurement): """! @brief Find nearest entry of node for the specified entry. @param[in] entry (cfentry): Entry that is used for calculation distance. @param[in] type_measurement (measurement_type): Measurement type that is used for o...
[ "def", "get_nearest_entry", "(", "self", ",", "entry", ",", "type_measurement", ")", ":", "min_key", "=", "lambda", "cur_entity", ":", "cur_entity", ".", "get_distance", "(", "entry", ",", "type_measurement", ")", "return", "min", "(", "self", ".", "__entries"...
46.538462
29.846154
def wait(self, number, patience): """ Waits and resets if necessary. """ # inspect indicator for our number waiting = int(self.client.get(self.keys.indicator)) != number # wait until someone announces our number while waiting: message = self.subscription.listen(patie...
[ "def", "wait", "(", "self", ",", "number", ",", "patience", ")", ":", "# inspect indicator for our number", "waiting", "=", "int", "(", "self", ".", "client", ".", "get", "(", "self", ".", "keys", ".", "indicator", ")", ")", "!=", "number", "# wait until s...
37.1
16.9
def strokewidth(self, w=None): '''Set the stroke width. :param w: Stroke width. :return: If no width was specified then current width is returned. ''' if w is not None: self._canvas.strokewidth = w else: return self._canvas.strokewidth
[ "def", "strokewidth", "(", "self", ",", "w", "=", "None", ")", ":", "if", "w", "is", "not", "None", ":", "self", ".", "_canvas", ".", "strokewidth", "=", "w", "else", ":", "return", "self", ".", "_canvas", ".", "strokewidth" ]
29.9
17.5
def extract_self_cert(signed_raw: str) -> Identity: """ Return self-certified Identity instance from the signed raw Revocation document :param signed_raw: Signed raw document string :return: """ lines = signed_raw.splitlines(True) n = 0 version = int(Rev...
[ "def", "extract_self_cert", "(", "signed_raw", ":", "str", ")", "->", "Identity", ":", "lines", "=", "signed_raw", ".", "splitlines", "(", "True", ")", "n", "=", "0", "version", "=", "int", "(", "Revocation", ".", "parse_field", "(", "\"Version\"", ",", ...
28.375
27.25
def add_action_view(self, name, url, actions, **kwargs): """Creates an ActionsView instance and registers it. """ view = ActionsView(name, url=url, self_var=self, **kwargs) if isinstance(actions, dict): for group, actions in actions.iteritems(): view.actions.e...
[ "def", "add_action_view", "(", "self", ",", "name", ",", "url", ",", "actions", ",", "*", "*", "kwargs", ")", ":", "view", "=", "ActionsView", "(", "name", ",", "url", "=", "url", ",", "self_var", "=", "self", ",", "*", "*", "kwargs", ")", "if", ...
43.272727
15.727273
def __monkey_patch_juman_lines(self, input_str): # type: (text_type)->text_type """* What you can do - It overwrites juman_line() method because this method causes TypeError in python3 """ assert isinstance(self.juman, pyknp.Juman) if not self.juman.socket and not self.ju...
[ "def", "__monkey_patch_juman_lines", "(", "self", ",", "input_str", ")", ":", "# type: (text_type)->text_type", "assert", "isinstance", "(", "self", ".", "juman", ",", "pyknp", ".", "Juman", ")", "if", "not", "self", ".", "juman", ".", "socket", "and", "not", ...
54.176471
21.176471
def remove(self, attendees): """ Remove the provided attendees from the event :param attendees: list of attendees to add :type attendees: str or tuple(str, str) or Attendee or list[str] or list[tuple(str,str)] or list[Attendee] """ if isinstance(attendees, (list, tuple)...
[ "def", "remove", "(", "self", ",", "attendees", ")", ":", "if", "isinstance", "(", "attendees", ",", "(", "list", ",", "tuple", ")", ")", ":", "attendees", "=", "{", "attendee", ".", "address", "if", "isinstance", "(", "attendee", ",", "Attendee", ")",...
38.16
13.64
def _run_get_data_background(macs, queue, shared_data, bt_device): """ Background process function for RuuviTag Sensors """ run_flag = RunFlag() def add_data(data): if not shared_data['run_flag']: run_flag.running = False data[1]['time'] = datetime.utcnow().isoformat()...
[ "def", "_run_get_data_background", "(", "macs", ",", "queue", ",", "shared_data", ",", "bt_device", ")", ":", "run_flag", "=", "RunFlag", "(", ")", "def", "add_data", "(", "data", ")", ":", "if", "not", "shared_data", "[", "'run_flag'", "]", ":", "run_flag...
26.466667
19.533333
def awd_lstm_lm_1150(dataset_name=None, vocab=None, pretrained=False, ctx=cpu(), root=os.path.join(get_home_dir(), 'models'), **kwargs): r"""3-layer LSTM language model with weight-drop, variational dropout, and tied weights. Embedding size is 400, and hidden layer size is 1150. Param...
[ "def", "awd_lstm_lm_1150", "(", "dataset_name", "=", "None", ",", "vocab", "=", "None", ",", "pretrained", "=", "False", ",", "ctx", "=", "cpu", "(", ")", ",", "root", "=", "os", ".", "path", ".", "join", "(", "get_home_dir", "(", ")", ",", "'models'...
46.043478
18.456522
def benchmark(args): """ %prog benchmark at bedfile Compare SynFind, MCScanx, iADHoRe and OrthoFinder against the truth. """ p = OptionParser(benchmark.__doc__) opts, args = p.parse_args(args) if len(args) != 2: sys.exit(not p.print_help()) pf, bedfile = args truth = pf + ...
[ "def", "benchmark", "(", "args", ")", ":", "p", "=", "OptionParser", "(", "benchmark", ".", "__doc__", ")", "opts", ",", "args", "=", "p", ".", "parse_args", "(", "args", ")", "if", "len", "(", "args", ")", "!=", "2", ":", "sys", ".", "exit", "("...
29.171053
16.802632
def make_csv(self): """ Get the text representation of a report element as csv. """ import csv try: from StringIO import StringIO # Python 2.7 except ImportError: from io import StringIO out = StringIO() writer = csv.writer(out, d...
[ "def", "make_csv", "(", "self", ")", ":", "import", "csv", "try", ":", "from", "StringIO", "import", "StringIO", "# Python 2.7", "except", "ImportError", ":", "from", "io", "import", "StringIO", "out", "=", "StringIO", "(", ")", "writer", "=", "csv", ".", ...
37.210526
19.052632
def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'description') and self.description is not None: _dict['description'] = self.description if hasattr(self, 'destination_field') and self.destination_field...
[ "def", "_to_dict", "(", "self", ")", ":", "_dict", "=", "{", "}", "if", "hasattr", "(", "self", ",", "'description'", ")", "and", "self", ".", "description", "is", "not", "None", ":", "_dict", "[", "'description'", "]", "=", "self", ".", "description",...
53.333333
21.285714
def _process_response(self, response: Response): '''Handle the response and update the internal state.''' _logger.debug('Handling response') self._redirect_tracker.load(response) if self._redirect_tracker.is_redirect(): self._process_redirect() self._loop_type =...
[ "def", "_process_response", "(", "self", ",", "response", ":", "Response", ")", ":", "_logger", ".", "debug", "(", "'Handling response'", ")", "self", ".", "_redirect_tracker", ".", "load", "(", "response", ")", "if", "self", ".", "_redirect_tracker", ".", "...
36.35
17.55
def clean_markdown(text): """ Parse markdown sintaxt to html. """ result = text if isinstance(text, str): result = ''.join( BeautifulSoup(markdown(text), 'lxml').findAll(text=True)) return result
[ "def", "clean_markdown", "(", "text", ")", ":", "result", "=", "text", "if", "isinstance", "(", "text", ",", "str", ")", ":", "result", "=", "''", ".", "join", "(", "BeautifulSoup", "(", "markdown", "(", "text", ")", ",", "'lxml'", ")", ".", "findAll...
21
18.272727
def random_draw(self, size=None): """Draw random samples of the hyperparameters. Parameters ---------- size : None, int or array-like, optional The number/shape of samples to draw. If None, only one sample is returned. Default is None. """ ...
[ "def", "random_draw", "(", "self", ",", "size", "=", "None", ")", ":", "return", "scipy", ".", "asarray", "(", "[", "scipy", ".", "stats", ".", "gamma", ".", "rvs", "(", "a", ",", "loc", "=", "0", ",", "scale", "=", "1.0", "/", "b", ",", "size"...
42.5
21
def _load_calib(self): """Load and compute intrinsic and extrinsic calibration parameters.""" # We'll build the calibration parameters as a dictionary, then # convert it to a namedtuple to prevent it from being modified later data = {} # Load the calibration file calib_f...
[ "def", "_load_calib", "(", "self", ")", ":", "# We'll build the calibration parameters as a dictionary, then", "# convert it to a namedtuple to prevent it from being modified later", "data", "=", "{", "}", "# Load the calibration file", "calib_filepath", "=", "os", ".", "path", "...
43.581818
20.818182
def _PrintStorageInformationAsJSON(self, storage_reader): """Writes a summary of sessions as machine-readable JSON. Args: storage_reader (StorageReader): storage reader. """ serializer = json_serializer.JSONAttributeContainerSerializer storage_counters = self._CalculateStorageCounters(storage...
[ "def", "_PrintStorageInformationAsJSON", "(", "self", ",", "storage_reader", ")", ":", "serializer", "=", "json_serializer", ".", "JSONAttributeContainerSerializer", "storage_counters", "=", "self", ".", "_CalculateStorageCounters", "(", "storage_reader", ")", "storage_coun...
43.52381
15.047619
def remove_tag(self, name, user, message=None, date=None): """ Removes tag with the given ``name``. :param name: name of the tag to be removed :param user: full username, i.e.: "Joe Doe <joe.doe@example.com>" :param message: message of the tag's removal commit :param dat...
[ "def", "remove_tag", "(", "self", ",", "name", ",", "user", ",", "message", "=", "None", ",", "date", "=", "None", ")", ":", "if", "name", "not", "in", "self", ".", "tags", ":", "raise", "TagDoesNotExistError", "(", "\"Tag %s does not exist\"", "%", "nam...
40.9
17.7
def _Close(self): """Closes the file system. Raises: IOError: if the close failed. """ self._vshadow_volume.close() self._vshadow_volume = None self._file_object.close() self._file_object = None
[ "def", "_Close", "(", "self", ")", ":", "self", ".", "_vshadow_volume", ".", "close", "(", ")", "self", ".", "_vshadow_volume", "=", "None", "self", ".", "_file_object", ".", "close", "(", ")", "self", ".", "_file_object", "=", "None" ]
20
16.090909
def destroy_image(self, image_id_or_slug): """ This method allows you to destroy an image. There is no way to restore a deleted image so be careful and ensure your data is properly backed up. Required parameters image_id: Numeric, this is the id of the image...
[ "def", "destroy_image", "(", "self", ",", "image_id_or_slug", ")", ":", "if", "not", "image_id_or_slug", ":", "msg", "=", "'image_id_or_slug is required to destroy an image!'", "raise", "DOPException", "(", "msg", ")", "json", "=", "self", ".", "request", "(", "'/...
34.611111
23.277778
def adapt(obj, to_cls): """ Will adapt `obj` to an instance of `to_cls`. First sees if `obj` has an `__adapt__` method and uses it to adapt. If that fails it checks if `to_cls` has an `__adapt__` classmethod and uses it to adapt. IF that fails, MRO is used. If that fails, a `TypeError` is raise...
[ "def", "adapt", "(", "obj", ",", "to_cls", ")", ":", "if", "obj", "is", "None", ":", "return", "obj", "elif", "isinstance", "(", "obj", ",", "to_cls", ")", ":", "return", "obj", "errors", "=", "[", "]", "if", "hasattr", "(", "obj", ",", "'__adapt__...
33.375
18.925
def get_instance(self, payload): """ Build an instance of CertificateInstance :param dict payload: Payload response from the API :returns: twilio.rest.preview.deployed_devices.fleet.certificate.CertificateInstance :rtype: twilio.rest.preview.deployed_devices.fleet.certificate.C...
[ "def", "get_instance", "(", "self", ",", "payload", ")", ":", "return", "CertificateInstance", "(", "self", ".", "_version", ",", "payload", ",", "fleet_sid", "=", "self", ".", "_solution", "[", "'fleet_sid'", "]", ",", ")" ]
44.1
27.5
def _dbc_decorate_namespace(bases: List[type], namespace: MutableMapping[str, Any]) -> None: """ Collect invariants, preconditions and postconditions from the bases and decorate all the methods. Instance methods are simply replaced with the decorated function/ Properties, class methods and static methods a...
[ "def", "_dbc_decorate_namespace", "(", "bases", ":", "List", "[", "type", "]", ",", "namespace", ":", "MutableMapping", "[", "str", ",", "Any", "]", ")", "->", "None", ":", "_collapse_invariants", "(", "bases", "=", "bases", ",", "namespace", "=", "namespa...
48.473684
34.157895
def trim(self, lower=None, upper=None): """Trim upper values in accordance with :math:`IC \\leq ICMAX`. >>> from hydpy.models.hland import * >>> parameterstep('1d') >>> nmbzones(5) >>> icmax(2.0) >>> states.ic(-1.0, 0.0, 1.0, 2.0, 3.0) >>> states.ic ic(0....
[ "def", "trim", "(", "self", ",", "lower", "=", "None", ",", "upper", "=", "None", ")", ":", "if", "upper", "is", "None", ":", "control", "=", "self", ".", "subseqs", ".", "seqs", ".", "model", ".", "parameters", ".", "control", "upper", "=", "contr...
35.333333
12.666667
def current_function(frame): """ Get reference to currently running function from inspect/trace stack frame. Parameters ---------- frame : stack frame Stack frame obtained via trace or inspect Returns ------- fnc : function reference Currently running function """ ...
[ "def", "current_function", "(", "frame", ")", ":", "if", "frame", "is", "None", ":", "return", "None", "code", "=", "frame", ".", "f_code", "# Attempting to extract the function reference for these calls appears", "# to be problematic", "if", "code", ".", "co_name", "...
28.710526
22.605263
def calculate_border_width(self): """ Calculate the width of the menu border. This will be the width of the maximum allowable dimensions (usually the screen size), minus the left and right margins and the newline character. For example, given a maximum width of 80 characters, with left a...
[ "def", "calculate_border_width", "(", "self", ")", ":", "return", "self", ".", "max_dimension", ".", "width", "-", "self", ".", "margins", ".", "left", "-", "self", ".", "margins", ".", "right", "-", "1" ]
51.545455
29.727273
def write(self, file_name, delim=',', sep='\t'): """Write a directed hypergraph to a file, where nodes are represented as strings. Each column is separated by "sep", and the individual tail nodes and head nodes are delimited by "delim". The header line is currently ignored, but c...
[ "def", "write", "(", "self", ",", "file_name", ",", "delim", "=", "','", ",", "sep", "=", "'\\t'", ")", ":", "out_file", "=", "open", "(", "file_name", ",", "'w'", ")", "# write first header line", "out_file", ".", "write", "(", "\"tail\"", "+", "sep", ...
36.106383
21.808511
def parse_samtools_rmdup(self): """ Find Samtools rmdup logs and parse their data """ self.samtools_rmdup = dict() for f in self.find_log_files('samtools/rmdup', filehandles=True): # Example below: # [bam_rmdupse_core] 26602816 / 103563641 = 0.2569 in library ' ' ...
[ "def", "parse_samtools_rmdup", "(", "self", ")", ":", "self", ".", "samtools_rmdup", "=", "dict", "(", ")", "for", "f", "in", "self", ".", "find_log_files", "(", "'samtools/rmdup'", ",", "filehandles", "=", "True", ")", ":", "# Example below:", "# [bam_rmdupse...
44.737705
20.229508
def facts(self, **kwargs): """Get all facts of this node. Additional arguments may also be specified that will be passed to the query function. """ return self.__api.facts(query=EqualsOperator("certname", self.name), **kwargs)
[ "def", "facts", "(", "self", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "__api", ".", "facts", "(", "query", "=", "EqualsOperator", "(", "\"certname\"", ",", "self", ".", "name", ")", ",", "*", "*", "kwargs", ")" ]
47.5
11.833333
def auth(self, request): """ let's auth the user to the Service """ client = self.get_evernote_client() request_token = client.get_request_token(self.callback_url(request)) # Save the request token information for later request.session['oauth_token'] = request...
[ "def", "auth", "(", "self", ",", "request", ")", ":", "client", "=", "self", ".", "get_evernote_client", "(", ")", "request_token", "=", "client", ".", "get_request_token", "(", "self", ".", "callback_url", "(", "request", ")", ")", "# Save the request token i...
48.230769
16.538462
def move_state(self, direction, activate): """ Set the camera position move state :param direction: What direction to update :param activate: Start or stop moving in the direction """ if direction == RIGHT: self._xdir = POSITIVE if activate else STILL ...
[ "def", "move_state", "(", "self", ",", "direction", ",", "activate", ")", ":", "if", "direction", "==", "RIGHT", ":", "self", ".", "_xdir", "=", "POSITIVE", "if", "activate", "else", "STILL", "elif", "direction", "==", "LEFT", ":", "self", ".", "_xdir", ...
39.157895
11.684211
def teardown(self): """ Teardown the link. Removes endpoints from properties I{links} collection. @return: self @rtype: L{Link} """ pA, pB = self.endpoints if pA in pB.links: pB.links.remove(pA) if pB in pA.links: pA.links.r...
[ "def", "teardown", "(", "self", ")", ":", "pA", ",", "pB", "=", "self", ".", "endpoints", "if", "pA", "in", "pB", ".", "links", ":", "pB", ".", "links", ".", "remove", "(", "pA", ")", "if", "pB", "in", "pA", ".", "links", ":", "pA", ".", "lin...
25.923077
13
def tuples_as_bytes(cmds): """Format list of tuples to CAM message with format /key:val. Parameters ---------- cmds : list of tuples List of commands as tuples. Returns ------- bytes Sequence of /key:val. Example ------- :: >>> tuples_as_bytes([('cmd',...
[ "def", "tuples_as_bytes", "(", "cmds", ")", ":", "cmds", "=", "OrderedDict", "(", "cmds", ")", "# override equal keys", "tmp", "=", "[", "]", "for", "key", ",", "val", "in", "cmds", ".", "items", "(", ")", ":", "key", "=", "str", "(", "key", ")", "...
20.75
21.464286
def exact_volume_sphere(rvec, pos, radius, zscale=1.0, volume_error=1e-5, function=sphere_analytical_gaussian, max_radius_change=1e-2, args=()): """ Perform an iterative method to calculate the effective sphere that perfectly (up to the volume_error) conserves volume. Return the resulting image ...
[ "def", "exact_volume_sphere", "(", "rvec", ",", "pos", ",", "radius", ",", "zscale", "=", "1.0", ",", "volume_error", "=", "1e-5", ",", "function", "=", "sphere_analytical_gaussian", ",", "max_radius_change", "=", "1e-2", ",", "args", "=", "(", ")", ")", "...
35.04
22.24
def get_all_keys(self, headers=None, callback=None, **params): """ A lower-level method for listing contents of a bucket. This closely models the actual S3 API and requires you to manually handle the paging of results. For a higher-level method that handles the details of paging...
[ "def", "get_all_keys", "(", "self", ",", "headers", "=", "None", ",", "callback", "=", "None", ",", "*", "*", "params", ")", ":", "return", "self", ".", "_get_all", "(", "[", "(", "'Contents'", ",", "self", ".", "key_class", ")", ",", "(", "'CommonPr...
46.96875
25.03125
def _hjoin_multiline(join_char, strings): """Horizontal join of multiline strings """ cstrings = [string.split("\n") for string in strings] max_num_lines = max(len(item) for item in cstrings) pp = [] for k in range(max_num_lines): p = [cstring[k] for cstring in cstrings] pp.appen...
[ "def", "_hjoin_multiline", "(", "join_char", ",", "strings", ")", ":", "cstrings", "=", "[", "string", ".", "split", "(", "\"\\n\"", ")", "for", "string", "in", "strings", "]", "max_num_lines", "=", "max", "(", "len", "(", "item", ")", "for", "item", "...
36.545455
12.909091
def get_caller_module(): """ Returns the name of the caller's module as a string. >>> get_caller_module() '__main__' """ stack = inspect.stack() assert len(stack) > 1 caller = stack[2][0] return caller.f_globals['__name__']
[ "def", "get_caller_module", "(", ")", ":", "stack", "=", "inspect", ".", "stack", "(", ")", "assert", "len", "(", "stack", ")", ">", "1", "caller", "=", "stack", "[", "2", "]", "[", "0", "]", "return", "caller", ".", "f_globals", "[", "'__name__'", ...
22.727273
14.181818
def set_policy_priorities(self, priorities_json): '''**Description** Change the policy evaluation order **Arguments** - priorities_json: a description of the new policy order. **Success Return Value** A JSON object representing the updated list of policy ids...
[ "def", "set_policy_priorities", "(", "self", ",", "priorities_json", ")", ":", "try", ":", "json", ".", "loads", "(", "priorities_json", ")", "except", "Exception", "as", "e", ":", "return", "[", "False", ",", "\"priorities json is not valid json: {}\"", ".", "f...
36.636364
30.272727
def create_annotation_node(self, annotation): """ Return an annotation node. """ annotation_node = URIRef(str(annotation.spdx_id)) type_triple = (annotation_node, RDF.type, self.spdx_namespace.Annotation) self.graph.add(type_triple) annotator_node = Literal(annot...
[ "def", "create_annotation_node", "(", "self", ",", "annotation", ")", ":", "annotation_node", "=", "URIRef", "(", "str", "(", "annotation", ".", "spdx_id", ")", ")", "type_triple", "=", "(", "annotation_node", ",", "RDF", ".", "type", ",", "self", ".", "sp...
50.090909
22.454545
def get(self, name): """Get the set of compatible packages given a resolvable name.""" resolvable, packages, parent, constraint_only = self._collapse().get( self.normalize(name), _ResolvedPackages.empty()) return packages
[ "def", "get", "(", "self", ",", "name", ")", ":", "resolvable", ",", "packages", ",", "parent", ",", "constraint_only", "=", "self", ".", "_collapse", "(", ")", ".", "get", "(", "self", ".", "normalize", "(", "name", ")", ",", "_ResolvedPackages", ".",...
47.4
18
def utime(self, path, times=None, ns=None, follow_symlinks=True): """Change the access and modified times of a file. Args: path: (str) Path to the file. times: 2-tuple of int or float numbers, of the form (atime, mtime) which is used to set the access and modifie...
[ "def", "utime", "(", "self", ",", "path", ",", "times", "=", "None", ",", "ns", "=", "None", ",", "follow_symlinks", "=", "True", ")", ":", "self", ".", "_handle_utime_arg_errors", "(", "ns", ",", "times", ")", "try", ":", "file_object", "=", "self", ...
43.625
19.729167
def ReadStoredProcedure(self, sproc_link, options=None): """Reads a stored procedure. :param str sproc_link: The link to the stored procedure. :param dict options: The request options for the request. :return: The read Stored Procedure. :rtyp...
[ "def", "ReadStoredProcedure", "(", "self", ",", "sproc_link", ",", "options", "=", "None", ")", ":", "if", "options", "is", "None", ":", "options", "=", "{", "}", "path", "=", "base", ".", "GetPathFromLink", "(", "sproc_link", ")", "sproc_id", "=", "base...
28.45
18.7
def get_alias_dict(config_obj): """ Return a dictionary consisting of all aliases known to eg. The format is {'alias': 'resolved_program'}. If the aliases file does not exist, returns an empty dict. """ if not config_obj.examples_dir: return {} alias_file_path = _get_alias_file_pa...
[ "def", "get_alias_dict", "(", "config_obj", ")", ":", "if", "not", "config_obj", ".", "examples_dir", ":", "return", "{", "}", "alias_file_path", "=", "_get_alias_file_path", "(", "config_obj", ")", "if", "not", "os", ".", "path", ".", "isfile", "(", "alias_...
28.222222
18.888889
async def verify_chain_of_trust(chain): """Build and verify the chain of trust. Args: chain (ChainOfTrust): the chain we're operating on Raises: CoTError: on failure """ log_path = os.path.join(chain.context.config["task_log_dir"], "chain_of_trust.log") scriptworker_log = logg...
[ "async", "def", "verify_chain_of_trust", "(", "chain", ")", ":", "log_path", "=", "os", ".", "path", ".", "join", "(", "chain", ".", "context", ".", "config", "[", "\"task_log_dir\"", "]", ",", "\"chain_of_trust.log\"", ")", "scriptworker_log", "=", "logging",...
39.804878
18.04878
def get(self, block=True, timeout=None): '''Remove and return an item from the queue. If optional args 'block' is true and 'timeout' is None (the default), block if necessary until an item is available. If 'timeout' is a non-negative number, it blocks at most 'timeout' seconds and raise...
[ "def", "get", "(", "self", ",", "block", "=", "True", ",", "timeout", "=", "None", ")", ":", "self", ".", "_parent", ".", "_check_closing", "(", ")", "with", "self", ".", "_parent", ".", "_sync_not_empty", ":", "if", "not", "block", ":", "if", "not",...
45.909091
15.909091
def _setElegant(self, **infiles): """ set input parameters for elegant tracking, available keys: 'ltefile', 'elefile' """ ltefile, elefile = infiles['ltefile'], infiles['elefile'] self.lattice_file = ltefile self.elegant_file = elefile
[ "def", "_setElegant", "(", "self", ",", "*", "*", "infiles", ")", ":", "ltefile", ",", "elefile", "=", "infiles", "[", "'ltefile'", "]", ",", "infiles", "[", "'elefile'", "]", "self", ".", "lattice_file", "=", "ltefile", "self", ".", "elegant_file", "=",...
45
7
def get_ids(self, features, threshold=0.0, func=np.sum, get_weights=False): """ Returns a list of all studies in the table that meet the desired feature-based criteria. Will most commonly be used to retrieve studies that use one or more features with some minimum frequency; e.g.,: ...
[ "def", "get_ids", "(", "self", ",", "features", ",", "threshold", "=", "0.0", ",", "func", "=", "np", ".", "sum", ",", "get_weights", "=", "False", ")", ":", "if", "isinstance", "(", "features", ",", "str", ")", ":", "features", "=", "[", "features",...
50.552632
22.473684
def retag(self, tagging, tag=None): """ Copies the object, applying a new tagging to it :param tagging: A dict containing the keys "explicit" and "implicit". Legacy API allows a unicode string of "implicit" or "explicit". :param tag: A integer tag nu...
[ "def", "retag", "(", "self", ",", "tagging", ",", "tag", "=", "None", ")", ":", "# This is required to preserve the old API", "if", "not", "isinstance", "(", "tagging", ",", "dict", ")", ":", "tagging", "=", "{", "tagging", ":", "tag", "}", "new_obj", "=",...
33.761905
21.095238
def _unlinkUser(self): """Remove the UID of the current Contact in the User properties and update all relevant own properties. """ KEY = "linked_contact_uid" # Nothing to do if no user is linked if not self.hasUser(): return False user = self.getUser...
[ "def", "_unlinkUser", "(", "self", ")", ":", "KEY", "=", "\"linked_contact_uid\"", "# Nothing to do if no user is linked", "if", "not", "self", ".", "hasUser", "(", ")", ":", "return", "False", "user", "=", "self", ".", "getUser", "(", ")", "username", "=", ...
31
16.888889
def snapshot(self, lock=False): """Create a snapshot of latest objects in bucket. :param lock: Create the new bucket in a locked state. :returns: Newly created bucket containing copied ObjectVersion. """ with db.session.begin_nested(): bucket = Bucket( ...
[ "def", "snapshot", "(", "self", ",", "lock", "=", "False", ")", ":", "with", "db", ".", "session", ".", "begin_nested", "(", ")", ":", "bucket", "=", "Bucket", "(", "default_location", "=", "self", ".", "default_location", ",", "default_storage_class", "="...
33.3
18
def init_datastore(config): """ Take the config definition and initialize the datastore. The config must contain either a 'datastore' parameter, which will be simply returned, or must contain a 'factory' which is a callable or entry point definition. The callable should take the remainder of ...
[ "def", "init_datastore", "(", "config", ")", ":", "if", "'datastore'", "in", "config", ":", "# the datastore has already been initialized, just use it.", "return", "config", "[", "'datastore'", "]", "factory", "=", "config", ".", "pop", "(", "'factory'", ")", "if", ...
37.761905
15.952381
def slicenet_internal(inputs, targets, target_space, hparams, run_decoder=True): """The slicenet model, main step used for training.""" with tf.variable_scope("slicenet"): # Project to hidden size if necessary if inputs.get_shape().as_list()[-1] != hparams.hidden_size: inputs = common_layers.conv_bloc...
[ "def", "slicenet_internal", "(", "inputs", ",", "targets", ",", "target_space", ",", "hparams", ",", "run_decoder", "=", "True", ")", ":", "with", "tf", ".", "variable_scope", "(", "\"slicenet\"", ")", ":", "# Project to hidden size if necessary", "if", "inputs", ...
39.828571
17.657143
def download(self, FILENAME=None): """Downloads the files related to the query.""" resultFilename = None url = self.__url+'/services' result = Util.retrieveJsonResponseFromServer(url) dataItems = result['data'] for item in dataItems: plugin = P...
[ "def", "download", "(", "self", ",", "FILENAME", "=", "None", ")", ":", "resultFilename", "=", "None", "url", "=", "self", ".", "__url", "+", "'/services'", "result", "=", "Util", ".", "retrieveJsonResponseFromServer", "(", "url", ")", "dataItems", "=", "r...
49.857143
18.964286
def motif3struct_bin(A): ''' Structural motifs are patterns of local connectivity. Motif frequency is the frequency of occurrence of motifs around a node. Parameters ---------- A : NxN np.ndarray binary directed connection matrix Returns ------- F : 13xN np.ndarray ...
[ "def", "motif3struct_bin", "(", "A", ")", ":", "from", "scipy", "import", "io", "import", "os", "fname", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ",", "motiflib", ")", "mot", "=", "io", ".",...
32.826923
19.365385
def post(request): """ Create a Gallery """ defaultname = 'New Gallery %i' % Gallery.objects.all().count() data = request.POST or json.loads(request.body)['body'] title = data.get('title', defaultname) description = data.get('description', '') security = int(data.get('security', Gallery.PUBLIC))...
[ "def", "post", "(", "request", ")", ":", "defaultname", "=", "'New Gallery %i'", "%", "Gallery", ".", "objects", ".", "all", "(", ")", ".", "count", "(", ")", "data", "=", "request", ".", "POST", "or", "json", ".", "loads", "(", "request", ".", "body...
31.578947
18.421053
def find_command(cmd, path=None, pathext=None): """ Taken `from Django http://bit.ly/1njB3Y9>`_. """ if path is None: path = os.environ.get('PATH', '').split(os.pathsep) if isinstance(path, string_types): path = [path] # check if there are path extensions for Windows executables...
[ "def", "find_command", "(", "cmd", ",", "path", "=", "None", ",", "pathext", "=", "None", ")", ":", "if", "path", "is", "None", ":", "path", "=", "os", ".", "environ", ".", "get", "(", "'PATH'", ",", "''", ")", ".", "split", "(", "os", ".", "pa...
29.1
16.166667
def get_bitcoind_info(self): """ Get bitcoind info. Try the cache, and on cache miss, fetch from bitcoind and cache. """ cached_bitcoind_info = self.get_cached_bitcoind_info() if cached_bitcoind_info: return cached_bitcoind_info bitcoind_opts = defa...
[ "def", "get_bitcoind_info", "(", "self", ")", ":", "cached_bitcoind_info", "=", "self", ".", "get_cached_bitcoind_info", "(", ")", "if", "cached_bitcoind_info", ":", "return", "cached_bitcoind_info", "bitcoind_opts", "=", "default_bitcoind_opts", "(", "virtualchain", "....
34
21.52
def after_return(self, status, retval, task_id, args, kwargs, einfo): """ After a task has run (both succesfully or with a failure) clear the lock if "unlock_before_run" is False. """ # Only clear the lock after the task's execution if the # "unlock_before_run" option is ...
[ "def", "after_return", "(", "self", ",", "status", ",", "retval", ",", "task_id", ",", "args", ",", "kwargs", ",", "einfo", ")", ":", "# Only clear the lock after the task's execution if the", "# \"unlock_before_run\" option is False", "if", "not", "self", ".", "unloc...
44.8
10.6
def is_valid(self): """ Checks recursively if the tree is valid It is valid if each node splits correctly """ if not self: return True if self.left and self.data[self.axis] < self.left.data[self.axis]: return False if self.right and self.data[self.axis...
[ "def", "is_valid", "(", "self", ")", ":", "if", "not", "self", ":", "return", "True", "if", "self", ".", "left", "and", "self", ".", "data", "[", "self", ".", "axis", "]", "<", "self", ".", "left", ".", "data", "[", "self", ".", "axis", "]", ":...
29.2
26.266667
def serialize_link(ctx, document, elem, root): """Serilaze link element. This works only for external links at the moment. """ _a = etree.SubElement(root, 'a') for el in elem.elements: _ser = ctx.get_serializer(el) if _ser: _td = _ser(ctx, document, el, _a) el...
[ "def", "serialize_link", "(", "ctx", ",", "document", ",", "elem", ",", "root", ")", ":", "_a", "=", "etree", ".", "SubElement", "(", "root", ",", "'a'", ")", "for", "el", "in", "elem", ".", "elements", ":", "_ser", "=", "ctx", ".", "get_serializer",...
28.875
22.625
def process_pool(self, limited_run=False): """Return a pool for multiprocess operations, sized either to the number of CPUS, or a configured value""" from multiprocessing import cpu_count from ambry.bundle.concurrent import Pool, init_library if self.processes: cpus = self....
[ "def", "process_pool", "(", "self", ",", "limited_run", "=", "False", ")", ":", "from", "multiprocessing", "import", "cpu_count", "from", "ambry", ".", "bundle", ".", "concurrent", "import", "Pool", ",", "init_library", "if", "self", ".", "processes", ":", "...
42.2
21.133333
def _ForemanOp(self): """Sends Foreman checks periodically.""" period = config.CONFIG["Client.foreman_check_frequency"] self._threads["Worker"].SendReply( rdf_protodict.DataBlob(), session_id=rdfvalue.FlowSessionID(flow_name="Foreman"), require_fastpoll=False) time.sleep(period)
[ "def", "_ForemanOp", "(", "self", ")", ":", "period", "=", "config", ".", "CONFIG", "[", "\"Client.foreman_check_frequency\"", "]", "self", ".", "_threads", "[", "\"Worker\"", "]", ".", "SendReply", "(", "rdf_protodict", ".", "DataBlob", "(", ")", ",", "sess...
39
12.25
def _colorize(val, color): """Colorize a string using termcolor or colorama. If any of them are available. """ if termcolor is not None: val = termcolor.colored(val, color) elif colorama is not None: val = TERMCOLOR2COLORAMA[color] + val + colorama.Style.RESET_ALL return val
[ "def", "_colorize", "(", "val", ",", "color", ")", ":", "if", "termcolor", "is", "not", "None", ":", "val", "=", "termcolor", ".", "colored", "(", "val", ",", "color", ")", "elif", "colorama", "is", "not", "None", ":", "val", "=", "TERMCOLOR2COLORAMA",...
27.909091
16.636364
def validate(self, text, **kwargs): """Returns a boolean to indicate if this is a valid instance of the type.""" cleaned = self.clean(text, **kwargs) return cleaned is not None
[ "def", "validate", "(", "self", ",", "text", ",", "*", "*", "kwargs", ")", ":", "cleaned", "=", "self", ".", "clean", "(", "text", ",", "*", "*", "kwargs", ")", "return", "cleaned", "is", "not", "None" ]
40.8
3
def _proc_uri(self, request, result): """ Process the URI rules for the request. Both the desired API version and desired content type can be determined from those rules. :param request: The Request object provided by WebOb. :param result: The Result object to store the...
[ "def", "_proc_uri", "(", "self", ",", "request", ",", "result", ")", ":", "if", "result", ":", "# Result has already been fully determined", "return", "# First, determine the version based on the URI prefix", "for", "prefix", ",", "version", "in", "self", ".", "uris", ...
36.828571
18.6
def __capture_screenshot(webdriver, folder_location, file_name): "Capture a screenshot" # Check folder location exists. if not os.path.exists(folder_location): os.makedirs(folder_location) file_location = os.path.join(folder_location, file_name) if isinstance(webdri...
[ "def", "__capture_screenshot", "(", "webdriver", ",", "folder_location", ",", "file_name", ")", ":", "# Check folder location exists.", "if", "not", "os", ".", "path", ".", "exists", "(", "folder_location", ")", ":", "os", ".", "makedirs", "(", "folder_location", ...
47.578947
20.526316
def call(self, parameters): """ Call an endpoint given the parameters :param parameters: Dictionary of parameters :type parameters: dict :rtype: text """ # DEV ! parameters = { key: str(parameters[key]) for key in parameters if parameters[key] is not ...
[ "def", "call", "(", "self", ",", "parameters", ")", ":", "# DEV !", "parameters", "=", "{", "key", ":", "str", "(", "parameters", "[", "key", "]", ")", "for", "key", "in", "parameters", "if", "parameters", "[", "key", "]", "is", "not", "None", "}", ...
33.421053
17.842105
def stream_keys(self, bucket, timeout=None): """ Streams keys from a bucket, returning an iterator that yields lists of keys. """ msg_code = riak.pb.messages.MSG_CODE_LIST_KEYS_REQ codec = self._get_codec(msg_code) msg = codec.encode_stream_keys(bucket, timeout) ...
[ "def", "stream_keys", "(", "self", ",", "bucket", ",", "timeout", "=", "None", ")", ":", "msg_code", "=", "riak", ".", "pb", ".", "messages", ".", "MSG_CODE_LIST_KEYS_REQ", "codec", "=", "self", ".", "_get_codec", "(", "msg_code", ")", "msg", "=", "codec...
39.8
9.2
def space_wave(phase, amplitude=12, frequency=0.1): """ Function: space_wave Summary: This function is used to generate a wave-like padding spacement based on the variable lambda Examples: >>> print('\n'.join(space_wave(x) for x in range(100)) █ ███ ...
[ "def", "space_wave", "(", "phase", ",", "amplitude", "=", "12", ",", "frequency", "=", "0.1", ")", ":", "wave", "=", "cycle", "(", "horizontal", ")", "return", "''", ".", "join", "(", "(", "next", "(", "wave", ")", "for", "x", "in", "range", "(", ...
32.657895
19.605263
def create(cls, paas_info, vhost, alter_zone, background): """ Create a new vhost. """ if not background and not cls.intty(): background = True params = {'paas_id': paas_info['id'], 'vhost': vhost, 'zone_alter': alter_zone} result = cls.ca...
[ "def", "create", "(", "cls", ",", "paas_info", ",", "vhost", ",", "alter_zone", ",", "background", ")", ":", "if", "not", "background", "and", "not", "cls", ".", "intty", "(", ")", ":", "background", "=", "True", "params", "=", "{", "'paas_id'", ":", ...
31.166667
17.444444
def get_activities_by_query(self, activity_query): """Gets a list of ``Activities`` matching the given activity query. arg: activity_query (osid.learning.ActivityQuery): the activity query return: (osid.learning.ActivityList) - the returned ``ActivityList`` ...
[ "def", "get_activities_by_query", "(", "self", ",", "activity_query", ")", ":", "# Implemented from template for", "# osid.resource.ResourceQuerySession.get_resources_by_query", "and_list", "=", "list", "(", ")", "or_list", "=", "list", "(", ")", "for", "term", "in", "a...
48.390244
21.073171
def _full_axis_reduce(self, axis, func, alternate_index=None): """Applies map that reduce Manager to series but require knowledge of full axis. Args: func: Function to reduce the Manager by. This function takes in a Manager. axis: axis to apply the function to. alter...
[ "def", "_full_axis_reduce", "(", "self", ",", "axis", ",", "func", ",", "alternate_index", "=", "None", ")", ":", "result", "=", "self", ".", "data", ".", "map_across_full_axis", "(", "axis", ",", "func", ")", "if", "axis", "==", "0", ":", "columns", "...
50.526316
28.263158
def _exec_requested_job(self): """Execute the requested job after the timer has timeout.""" self._timer.stop() self._job(*self._args, **self._kwargs)
[ "def", "_exec_requested_job", "(", "self", ")", ":", "self", ".", "_timer", ".", "stop", "(", ")", "self", ".", "_job", "(", "*", "self", ".", "_args", ",", "*", "*", "self", ".", "_kwargs", ")" ]
42.5
7.5
def _validate_query(query): """Validate and clean up a query to be sent to Search. Cleans the query string, removes unneeded parameters, and validates for correctness. Does not modify the original argument. Raises an Exception on invalid input. Arguments: query (dict): The query to validate...
[ "def", "_validate_query", "(", "query", ")", ":", "query", "=", "deepcopy", "(", "query", ")", "# q is always required", "if", "query", "[", "\"q\"", "]", "==", "BLANK_QUERY", "[", "\"q\"", "]", ":", "raise", "ValueError", "(", "\"No query specified.\"", ")", ...
36.461538
19.717949
def is_child(self, node): """Check if a node is a child of the current node Parameters ---------- node : instance of Node The potential child. Returns ------- child : bool Whether or not the node is a child. """ if node in...
[ "def", "is_child", "(", "self", ",", "node", ")", ":", "if", "node", "in", "self", ".", "children", ":", "return", "True", "for", "c", "in", "self", ".", "children", ":", "if", "c", ".", "is_child", "(", "node", ")", ":", "return", "True", "return"...
23.947368
16.157895