text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def build_fault_model(self, collapse=False, rendered_msr=WC1994(), mfd_config=None): ''' Constructs a full fault model with epistemic uncertainty by enumerating all the possible recurrence models of each fault as separate faults, with the recurrence rates multip...
[ "def", "build_fault_model", "(", "self", ",", "collapse", "=", "False", ",", "rendered_msr", "=", "WC1994", "(", ")", ",", "mfd_config", "=", "None", ")", ":", "self", ".", "source_model", "=", "mtkSourceModel", "(", "self", ".", "id", ",", "self", ".", ...
49.125
0.001871
def _create_fig( *, x_sc=bq.LinearScale, y_sc=bq.LinearScale, x_ax=bq.Axis, y_ax=bq.Axis, fig=bq.Figure, options={}, params={} ): """ Initializes scales and axes for a bqplot figure and returns the resulting blank figure. Each plot component is passed in as a class. The plot ...
[ "def", "_create_fig", "(", "*", ",", "x_sc", "=", "bq", ".", "LinearScale", ",", "y_sc", "=", "bq", ".", "LinearScale", ",", "x_ax", "=", "bq", ".", "Axis", ",", "y_ax", "=", "bq", ".", "Axis", ",", "fig", "=", "bq", ".", "Figure", ",", "options"...
34.368421
0.000745
def spkcvt(trgsta, trgepc, trgctr, trgref, et, outref, refloc, abcorr, obsrvr): """ Return the state, relative to a specified observer, of a target having constant velocity in a specified reference frame. The target's state is provided by the calling program rather than by loaded SPK files. htt...
[ "def", "spkcvt", "(", "trgsta", ",", "trgepc", ",", "trgctr", ",", "trgref", ",", "et", ",", "outref", ",", "refloc", ",", "abcorr", ",", "obsrvr", ")", ":", "trgpos", "=", "stypes", ".", "toDoubleVector", "(", "trgsta", ")", "trgepc", "=", "ctypes", ...
38.413043
0.000552
def _find_usage_ebs(self): """calculate usage for all EBS limits and update Limits""" vols = 0 piops = 0 piops_gb = 0 gp_gb = 0 mag_gb = 0 st_gb = 0 sc_gb = 0 logger.debug("Getting usage for EBS volumes") results = paginate_dict( ...
[ "def", "_find_usage_ebs", "(", "self", ")", ":", "vols", "=", "0", "piops", "=", "0", "piops_gb", "=", "0", "gp_gb", "=", "0", "mag_gb", "=", "0", "st_gb", "=", "0", "sc_gb", "=", "0", "logger", ".", "debug", "(", "\"Getting usage for EBS volumes\"", "...
35.724638
0.00079
def get_keys(self, models, key=None): """ Get all the primary keys for an array of models. :type models: list :type key: str :rtype: list """ return list(set(map(lambda value: value.get_attribute(key) if key else value.get_key(), models)))
[ "def", "get_keys", "(", "self", ",", "models", ",", "key", "=", "None", ")", ":", "return", "list", "(", "set", "(", "map", "(", "lambda", "value", ":", "value", ".", "get_attribute", "(", "key", ")", "if", "key", "else", "value", ".", "get_key", "...
28.8
0.010101
def variable_summaries(var): """Attach a lot of summaries to a Tensor (for TensorBoard visualization).""" with tf.name_scope('summaries'): mean = tf.reduce_mean(var) tf.summary.scalar('mean', mean) with tf.name_scope('stddev'): stddev = tf.sqrt(tf.reduce_mean(tf.square(var - mean))) tf.summary...
[ "def", "variable_summaries", "(", "var", ")", ":", "with", "tf", ".", "name_scope", "(", "'summaries'", ")", ":", "mean", "=", "tf", ".", "reduce_mean", "(", "var", ")", "tf", ".", "summary", ".", "scalar", "(", "'mean'", ",", "mean", ")", "with", "t...
43.272727
0.00823
def read_from_user(input_type, *args, **kwargs): ''' Helper function to prompt user for input of a specific type e.g. float, str, int Designed to work with both python 2 and 3 Yes I know this is ugly. ''' def _read_in(*args, **kwargs): while True: try: tmp = raw_inpu...
[ "def", "read_from_user", "(", "input_type", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "def", "_read_in", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "while", "True", ":", "try", ":", "tmp", "=", "raw_input", "(", "*", "args", ...
32.3125
0.022556
def depth(script, iterations=3, viewpoint=(0, 0, 0), selected=False): """ A laplacian smooth that is constrained to move vertices only along the view direction. Args: script: the FilterScript object or script filename to write the filter to. iterations (int): The number of t...
[ "def", "depth", "(", "script", ",", "iterations", "=", "3", ",", "viewpoint", "=", "(", "0", ",", "0", ",", "0", ")", ",", "selected", "=", "False", ")", ":", "filter_xml", "=", "''", ".", "join", "(", "[", "' <filter name=\"Depth Smooth\">\\n'", ",",...
34.116279
0.000663
def spline_interpolate_by_datetime(datetime_axis, y_axis, datetime_new_axis): """A datetime-version that takes datetime object list as x_axis """ numeric_datetime_axis = [ totimestamp(a_datetime) for a_datetime in datetime_axis ] numeric_datetime_new_axis = [ totimestamp(a_datetime)...
[ "def", "spline_interpolate_by_datetime", "(", "datetime_axis", ",", "y_axis", ",", "datetime_new_axis", ")", ":", "numeric_datetime_axis", "=", "[", "totimestamp", "(", "a_datetime", ")", "for", "a_datetime", "in", "datetime_axis", "]", "numeric_datetime_new_axis", "=",...
34.461538
0.002174
def on_init(app): # pylint: disable=unused-argument """ Run sphinx-apidoc after Sphinx initialization. Read the Docs won't run tox or custom shell commands, so we need this to avoid checking in the generated reStructuredText files. """ docs_path = os.path.abspath(os.path.dirname(__file__)) ...
[ "def", "on_init", "(", "app", ")", ":", "# pylint: disable=unused-argument", "docs_path", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ")", "root_path", "=", "os", ".", "path", ".", "abspath", "(",...
50.125
0.002448
def default_logging_file(self): """ default logging configuration""" import os.path as p import pyemma return p.join(pyemma.__path__[0], Config.DEFAULT_LOGGING_FILE_NAME)
[ "def", "default_logging_file", "(", "self", ")", ":", "import", "os", ".", "path", "as", "p", "import", "pyemma", "return", "p", ".", "join", "(", "pyemma", ".", "__path__", "[", "0", "]", ",", "Config", ".", "DEFAULT_LOGGING_FILE_NAME", ")" ]
39.6
0.009901
def raw_input(self, prompt=''): """Write a prompt and read a line. The returned line does not include the trailing newline. When the user enters the EOF key sequence, EOFError is raised. Optional inputs: - prompt(''): a string to be printed to prompt the user. - c...
[ "def", "raw_input", "(", "self", ",", "prompt", "=", "''", ")", ":", "# Code run by the user may have modified the readline completer state.", "# We must ensure that our completer is back in place.", "if", "self", ".", "has_readline", ":", "self", ".", "set_readline_completer",...
38.435897
0.001952
def uninit(self): """! @brief Uninitialize the flash algo. Before further operations are executed, the algo must be reinited. The target is left in a state where algo does not have to be reloaded when init() is called. @exception FlashFailure """ if self...
[ "def", "uninit", "(", "self", ")", ":", "if", "self", ".", "_active_operation", "is", "None", ":", "return", "if", "self", ".", "_is_api_valid", "(", "'pc_unInit'", ")", ":", "# update core register to execute the uninit subroutine", "result", "=", "self", ".", ...
40.190476
0.012731
def copy(self): """Returns a copy of the object.""" attrs = {k: self.__dict__[k].copy() for k in self.containers} attrs.update({k: cp.deepcopy(self.__dict__[k]) for k in self.shared}) return self.__class__(**attrs)
[ "def", "copy", "(", "self", ")", ":", "attrs", "=", "{", "k", ":", "self", ".", "__dict__", "[", "k", "]", ".", "copy", "(", ")", "for", "k", "in", "self", ".", "containers", "}", "attrs", ".", "update", "(", "{", "k", ":", "cp", ".", "deepco...
48.4
0.00813
def _walk_through(job_dir): ''' Walk though the jid dir and look for jobs ''' serial = salt.payload.Serial(__opts__) for top in os.listdir(job_dir): t_path = os.path.join(job_dir, top) if not os.path.exists(t_path): continue for final in os.listdir(t_path): ...
[ "def", "_walk_through", "(", "job_dir", ")", ":", "serial", "=", "salt", ".", "payload", ".", "Serial", "(", "__opts__", ")", "for", "top", "in", "os", ".", "listdir", "(", "job_dir", ")", ":", "t_path", "=", "os", ".", "path", ".", "join", "(", "j...
31.896552
0.002099
def time(self): """! @brief (list) Returns sampling times when dynamic is measured during simulation. """ if self.__ccore_pcnn_dynamic_pointer is not None: return wrapper.pcnn_dynamic_get_time(self.__ccore_pcnn_dynamic_pointer) return list(ra...
[ "def", "time", "(", "self", ")", ":", "if", "self", ".", "__ccore_pcnn_dynamic_pointer", "is", "not", "None", ":", "return", "wrapper", ".", "pcnn_dynamic_get_time", "(", "self", ".", "__ccore_pcnn_dynamic_pointer", ")", "return", "list", "(", "range", "(", "l...
36.333333
0.01791
def _apply_summaries(self): """Add all summary rows and columns.""" def as_frame(r): if isinstance(r, pd.Series): return r.to_frame() else: return r df = self.data if df.index.nlevels > 1: raise ValueError( ...
[ "def", "_apply_summaries", "(", "self", ")", ":", "def", "as_frame", "(", "r", ")", ":", "if", "isinstance", "(", "r", ",", "pd", ".", "Series", ")", ":", "return", "r", ".", "to_frame", "(", ")", "else", ":", "return", "r", "df", "=", "self", "....
29.827586
0.00224
def get_int(self, arg, min_value=0, default=1, cmdname=None, at_most=None): """If no argument use the default. If arg is a an integer between least min_value and at_most, use that. Otherwise report an error. If there's a stack frame use that in evaluation.""" if arg is N...
[ "def", "get_int", "(", "self", ",", "arg", ",", "min_value", "=", "0", ",", "default", "=", "1", ",", "cmdname", "=", "None", ",", "at_most", "=", "None", ")", ":", "if", "arg", "is", "None", ":", "return", "default", "default", "=", "self", ".", ...
40.725
0.002398
def get_window_by_index(self, index): " Return the Window with this index or None if not found. " for w in self.windows: if w.index == index: return w
[ "def", "get_window_by_index", "(", "self", ",", "index", ")", ":", "for", "w", "in", "self", ".", "windows", ":", "if", "w", ".", "index", "==", "index", ":", "return", "w" ]
38
0.010309
def get_unit_process_ids( self, unit_processes, expect_success=True, pgrep_full=False): """Construct a dict containing unit sentries, process names, and process IDs. :param unit_processes: A dictionary of Amulet sentry instance to list of process names. :param ex...
[ "def", "get_unit_process_ids", "(", "self", ",", "unit_processes", ",", "expect_success", "=", "True", ",", "pgrep_full", "=", "False", ")", ":", "pid_dict", "=", "{", "}", "for", "sentry_unit", ",", "process_list", "in", "six", ".", "iteritems", "(", "unit_...
44.619048
0.00209
def load_json(): """load_json Loads the config.JSON file system object's contents and translate it into a Python object. This python object is then returned. """ try: env = configure.get_env() configure.export_to_json(env) except SystemExit: raise BuildError(msg="configure fail...
[ "def", "load_json", "(", ")", ":", "try", ":", "env", "=", "configure", ".", "get_env", "(", ")", "configure", ".", "export_to_json", "(", "env", ")", "except", "SystemExit", ":", "raise", "BuildError", "(", "msg", "=", "\"configure failed! Could not build ta...
34.266667
0.001894
def generate_features( self, sentence_text, wid ): ''' Generates and returns a list of strings, containing tab-separated features ID, FORM, LEMMA, CPOSTAG, POSTAG, FEATS of the word (the word with index *wid* from the given *sentence_text*). Parameters ----------...
[ "def", "generate_features", "(", "self", ",", "sentence_text", ",", "wid", ")", ":", "assert", "WORDS", "in", "sentence_text", "and", "len", "(", "sentence_text", "[", "WORDS", "]", ")", ">", "0", ",", "\" (!) 'words' layer missing or empty in given Text!\"", "sen...
43.196262
0.015017
def record(self): # type: () -> bytes ''' Generate a string representing the Rock Ridge POSIX Device Number record. Parameters: None. Returns: String containing the Rock Ridge record. ''' if not self._initialized: raise pycdl...
[ "def", "record", "(", "self", ")", ":", "# type: () -> bytes", "if", "not", "self", ".", "_initialized", ":", "raise", "pycdlibexception", ".", "PyCdlibInternalError", "(", "'PN record not yet initialized!'", ")", "return", "b'PN'", "+", "struct", ".", "pack", "("...
37.333333
0.008711
def call(self, path, query=None, get_all_pages=True, side_loading=False): """ Call Zendesk API and return results :param path: The Zendesk API to call :param query: Query parameters :param get_all_pages: Accumulate results over all pages before returning. Due to s...
[ "def", "call", "(", "self", ",", "path", ",", "query", "=", "None", ",", "get_all_pages", "=", "True", ",", "side_loading", "=", "False", ")", ":", "zendesk", "=", "self", ".", "get_conn", "(", ")", "first_request_successful", "=", "False", "while", "not...
45.344262
0.000708
def associate_by_distance(labels_a, labels_b, distance): '''Find the objects that are within a given distance of each other Given two labels matrices and a distance, find pairs of objects that are within the given distance of each other where the distance is the minimum distance between any point i...
[ "def", "associate_by_distance", "(", "labels_a", ",", "labels_b", ",", "distance", ")", ":", "if", "np", ".", "max", "(", "labels_a", ")", "==", "0", "or", "np", ".", "max", "(", "labels_b", ")", "==", "0", ":", "return", "np", ".", "zeros", "(", "...
40.654412
0.009181
def default_value(fieldname, datatype): """ Return the default value for a column. If the column name (e.g. *i-wf*) is defined to have an idiosyncratic value, that value is returned. Otherwise the default value for the column's datatype is returned. Args: fieldname: the column name (e....
[ "def", "default_value", "(", "fieldname", ",", "datatype", ")", ":", "if", "fieldname", "in", "tsdb_coded_attributes", ":", "return", "str", "(", "tsdb_coded_attributes", "[", "fieldname", "]", ")", "else", ":", "return", "_default_datatype_values", ".", "get", ...
31.45
0.001543
def ximshow_rectified(self, slitlet2d_rect): """Display rectified image with spectrails and frontiers. Parameters ---------- slitlet2d_rect : numpy array Array containing the rectified slitlet image """ title = "Slitlet#" + str(self.islitlet) + " (rectify)"...
[ "def", "ximshow_rectified", "(", "self", ",", "slitlet2d_rect", ")", ":", "title", "=", "\"Slitlet#\"", "+", "str", "(", "self", ".", "islitlet", ")", "+", "\" (rectify)\"", "ax", "=", "ximshow", "(", "slitlet2d_rect", ",", "title", "=", "title", ",", "fir...
43.241379
0.00156
def fast_roc(actuals, controls): """ approximates the area under the roc curve for sets of actuals and controls. Uses all values appearing in actuals as thresholds and lower sum interpolation. Also returns arrays of the true positive rate and the false positive rate that can be used for plotting the...
[ "def", "fast_roc", "(", "actuals", ",", "controls", ")", ":", "assert", "(", "type", "(", "actuals", ")", "is", "np", ".", "ndarray", ")", "assert", "(", "type", "(", "controls", ")", "is", "np", ".", "ndarray", ")", "actuals", "=", "np", ".", "rav...
40.589744
0.000617
def _qteFindAppletInSplitter(self, appletObj: QtmacsApplet, split: QtmacsSplitter): """ Return the splitter that holds ``appletObj``. This method recursively searches for ``appletObj`` in the nested splitter hierarchy of the window layout, starting at ...
[ "def", "_qteFindAppletInSplitter", "(", "self", ",", "appletObj", ":", "QtmacsApplet", ",", "split", ":", "QtmacsSplitter", ")", ":", "def", "splitterIter", "(", "split", ")", ":", "\"\"\"\n Iterator over all QtmacsSplitters.\n \"\"\"", "for", "idx",...
34.261905
0.002027
def from_fields(cls, **kwargs): ''' Create an `Atom` instance from a set of fields. This is a slightly faster way to initialize an Atom. **Example** >>> Atom.from_fields(type='Ar', r_array=np.array([0.0, 0.0, 0.0]), ...
[ "def", "from_fields", "(", "cls", ",", "*", "*", "kwargs", ")", ":", "obj", "=", "cls", ".", "__new__", "(", "cls", ")", "for", "name", ",", "field", "in", "obj", ".", "__fields__", ".", "items", "(", ")", ":", "if", "name", "in", "kwargs", ":", ...
29.631579
0.008606
def name(self, src=None): """Return string representing the name of this type.""" if len(self._types) > 1: return "!(%s)" % str("|".join(_get_type_name(tt, src) for tt in self._types)) else: return "!" + _get_type_name(self._types[0], src)
[ "def", "name", "(", "self", ",", "src", "=", "None", ")", ":", "if", "len", "(", "self", ".", "_types", ")", ">", "1", ":", "return", "\"!(%s)\"", "%", "str", "(", "\"|\"", ".", "join", "(", "_get_type_name", "(", "tt", ",", "src", ")", "for", ...
47
0.010453
def bernstein_companion(coeffs): r"""Compute a companion matrix for a polynomial in Bernstein basis. .. note:: This assumes the caller passes in a 1D array but does not check. This takes the polynomial .. math:: f(s) = \sum_{j = 0}^n b_{j, n} \cdot C_j. and uses the variable :mat...
[ "def", "bernstein_companion", "(", "coeffs", ")", ":", "sigma_coeffs", ",", "degree", ",", "effective_degree", "=", "_get_sigma_coeffs", "(", "coeffs", ")", "if", "effective_degree", "==", "0", ":", "return", "np", ".", "empty", "(", "(", "0", ",", "0", ")...
31
0.001455
def load_plugins(group='metrics.plugin.10'): """Load and installed metrics plugins. """ # on using entrypoints: # http://stackoverflow.com/questions/774824/explain-python-entry-points file_processors = [] build_processors = [] for ep in pkg_resources.iter_entry_points(group, name=None): ...
[ "def", "load_plugins", "(", "group", "=", "'metrics.plugin.10'", ")", ":", "# on using entrypoints:", "# http://stackoverflow.com/questions/774824/explain-python-entry-points", "file_processors", "=", "[", "]", "build_processors", "=", "[", "]", "for", "ep", "in", "pkg_reso...
44.466667
0.001468
def _hashing_map(binary_record): """A map function used in hash phase. Reads KeyValue from binary record. Args: binary_record: The binary record. Yields: The (key, value). """ proto = kv_pb.KeyValue() proto.ParseFromString(binary_record) yield (proto.key(), proto.value())
[ "def", "_hashing_map", "(", "binary_record", ")", ":", "proto", "=", "kv_pb", ".", "KeyValue", "(", ")", "proto", ".", "ParseFromString", "(", "binary_record", ")", "yield", "(", "proto", ".", "key", "(", ")", ",", "proto", ".", "value", "(", ")", ")" ...
20.428571
0.016722
def parse_http_header(header_line): """Parse an HTTP header from a string, and return an ``HttpHeader``. ``header_line`` should only contain one line. ``BadHttpHeaderError`` is raised if the string is an invalid header line. """ header_line = header_line.decode().strip() col_idx = header_line....
[ "def", "parse_http_header", "(", "header_line", ")", ":", "header_line", "=", "header_line", ".", "decode", "(", ")", ".", "strip", "(", ")", "col_idx", "=", "header_line", ".", "find", "(", "':'", ")", "if", "col_idx", "<", "1", ":", "raise", "BadHttpHe...
34
0.001789
def _ensure_sliding_windows(self, assets, dts, field, is_perspective_after): """ Ensure that there is a Float64Multiply window for each asset that can provide data for the given parameters. If the corresponding window for the (assets, len(dts), field) does...
[ "def", "_ensure_sliding_windows", "(", "self", ",", "assets", ",", "dts", ",", "field", ",", "is_perspective_after", ")", ":", "end", "=", "dts", "[", "-", "1", "]", "size", "=", "len", "(", "dts", ")", "asset_windows", "=", "{", "}", "needed_assets", ...
38.59434
0.000715
def standardize_table(cls, table): ''' Extract objects from a Gaia DR2 table. ''' print(cls) identifiers = {n+'-id':table[n] for n in cls.identifier_keys} # create skycoord objects N = len(table) coordinates = dict( ra=table['_RAJ2000'].data.data*u.deg,...
[ "def", "standardize_table", "(", "cls", ",", "table", ")", ":", "print", "(", "cls", ")", "identifiers", "=", "{", "n", "+", "'-id'", ":", "table", "[", "n", "]", "for", "n", "in", "cls", ".", "identifier_keys", "}", "# create skycoord objects", "N", "...
45.296296
0.009608
def tricolor_white_bg(self, img): """transforms image from RGB with (0,0,0) showing black to RGB with 0,0,0 showing white takes the Red intensity and sets the new intensity to go from (0, 0.5, 0.5) (for Red=0) to (0, 0, 0) (for Red=1) and so on for the Green and Blue m...
[ "def", "tricolor_white_bg", "(", "self", ",", "img", ")", ":", "tmp", "=", "0.5", "*", "(", "1.0", "-", "(", "img", "-", "img", ".", "min", "(", ")", ")", "/", "(", "img", ".", "max", "(", ")", "-", "img", ".", "min", "(", ")", ")", ")", ...
39.875
0.020408
def to_fits(self): """ Converts a `~regions.ShapeList` to a `~astropy.table.Table` object. """ max_length_coord = 1 coord_x = [] coord_y = [] shapes = [] radius = [] rotangle_deg = [] components = [] reg_reverse_mapping = {value: ...
[ "def", "to_fits", "(", "self", ")", ":", "max_length_coord", "=", "1", "coord_x", "=", "[", "]", "coord_y", "=", "[", "]", "shapes", "=", "[", "]", "radius", "=", "[", "]", "rotangle_deg", "=", "[", "]", "components", "=", "[", "]", "reg_reverse_mapp...
41.014493
0.002415
def _build_pcollection(self, pipeline, folder, split): """Generate examples as dicts.""" beam = tfds.core.lazy_imports.apache_beam split_type = self.builder_config.split_type filename = os.path.join(folder, "{}.tar.gz".format(split_type)) def _extract_data(inputs): """Extracts files from th...
[ "def", "_build_pcollection", "(", "self", ",", "pipeline", ",", "folder", ",", "split", ")", ":", "beam", "=", "tfds", ".", "core", ".", "lazy_imports", ".", "apache_beam", "split_type", "=", "self", ".", "builder_config", ".", "split_type", "filename", "=",...
36.553571
0.00999
def set_default_init_cli_human_cmds(self): # pylint: disable=no-self-use """ Default commands to restore cli to human readable state are echo on, set --vt100 on, set --retcode false. :return: List of default commands to restore cli to human readable format """ post_cli_...
[ "def", "set_default_init_cli_human_cmds", "(", "self", ")", ":", "# pylint: disable=no-self-use", "post_cli_cmds", "=", "[", "]", "post_cli_cmds", ".", "append", "(", "\"echo on\"", ")", "post_cli_cmds", ".", "append", "(", "\"set --vt100 on\"", ")", "post_cli_cmds", ...
44.416667
0.009191
def create_document(self, data, throw_on_exists=False): """ Creates a new document in the remote and locally cached database, using the data provided. If an _id is included in the data then depending on that _id either a :class:`~cloudant.document.Document` or a :class:`~cloudan...
[ "def", "create_document", "(", "self", ",", "data", ",", "throw_on_exists", "=", "False", ")", ":", "docid", "=", "data", ".", "get", "(", "'_id'", ",", "None", ")", "doc", "=", "None", "if", "docid", "and", "docid", ".", "startswith", "(", "'_design/'...
42.088235
0.002049
def remote_get(self, remote='origin'): """Get the fetch and push URL for a specified remote name. :param remote: the remote name used to define the fetch and push URL :type remote: str :returns: remote name and url in tuple form :rtype: tuple """ try: ...
[ "def", "remote_get", "(", "self", ",", "remote", "=", "'origin'", ")", ":", "try", ":", "ret", "=", "self", ".", "run", "(", "[", "'remote'", ",", "'show'", ",", "'-n'", ",", "remote", "]", ")", "lines", "=", "ret", ".", "split", "(", "'\\n'", ")...
39.95
0.002445
def format_currency(value, decimals=2): """ Return a number suitably formatted for display as currency, with thousands separated by commas and up to two decimal points. >>> format_currency(1000) '1,000' >>> format_currency(100) '100' >>> format_currency(999.95) '999.95' >>> form...
[ "def", "format_currency", "(", "value", ",", "decimals", "=", "2", ")", ":", "number", ",", "decimal", "=", "(", "(", "u'%%.%df'", "%", "decimals", ")", "%", "value", ")", ".", "split", "(", "u'.'", ")", "parts", "=", "[", "]", "while", "len", "(",...
26.567568
0.000981
def read_file(file): """Read ``file`` into ``bytes``. :arg file type: path-like or file-like :rtype: bytes """ if hasattr(file, "read"): return file.read() if hasattr(file, "read_bytes"): return file.read_bytes() with open(file, "rb") as f: return f.read()
[ "def", "read_file", "(", "file", ")", ":", "if", "hasattr", "(", "file", ",", "\"read\"", ")", ":", "return", "file", ".", "read", "(", ")", "if", "hasattr", "(", "file", ",", "\"read_bytes\"", ")", ":", "return", "file", ".", "read_bytes", "(", ")",...
21.666667
0.04797
def kl_divergence(res1, res2): """ Computes the `Kullback-Leibler (KL) divergence <https://en.wikipedia.org/wiki/Kullback-Leibler_divergence>`_ *from* the discrete probability distribution defined by `res2` *to* the discrete probability distribution defined by `res1`. Parameters ---------- ...
[ "def", "kl_divergence", "(", "res1", ",", "res2", ")", ":", "# Define our importance weights.", "logp1", ",", "logp2", "=", "res1", ".", "logwt", "-", "res1", ".", "logz", "[", "-", "1", "]", ",", "res2", ".", "logwt", "-", "res2", ".", "logz", "[", ...
42.857143
0.000326
def summary(self): """Summary string of mean and standard deviation. Returns: Summary tensor. """ with tf.name_scope(self._name + '/summary'): mean_summary = tf.cond( self._count > 0, lambda: self._summary('mean', self._mean), str) std_summary = tf.cond( self._coun...
[ "def", "summary", "(", "self", ")", ":", "with", "tf", ".", "name_scope", "(", "self", ".", "_name", "+", "'/summary'", ")", ":", "mean_summary", "=", "tf", ".", "cond", "(", "self", ".", "_count", ">", "0", ",", "lambda", ":", "self", ".", "_summa...
35.416667
0.009174
def switch_user(self, username='', *, token=None): """Log in to Google Music with a different user. Parameters: username (str, Optional): Your Google Music username. Used for keeping stored OAuth tokens for multiple accounts separate. token (dict, Optional): An OAuth token compatible with ``requests-oaut...
[ "def", "switch_user", "(", "self", ",", "username", "=", "''", ",", "*", ",", "token", "=", "None", ")", ":", "if", "self", ".", "logout", "(", ")", ":", "return", "self", ".", "login", "(", "username", ",", "token", "=", "token", ")", "return", ...
29.875
0.028398
def load_profile(ctx, variant_file, update, stats, profile_threshold): """ Command for profiling of samples. User may upload variants used in profiling from a vcf, update the profiles for all samples, and get some stats from the profiles in the database. Profiling is used to monito...
[ "def", "load_profile", "(", "ctx", ",", "variant_file", ",", "update", ",", "stats", ",", "profile_threshold", ")", ":", "adapter", "=", "ctx", ".", "obj", "[", "'adapter'", "]", "if", "variant_file", ":", "load_profile_variants", "(", "adapter", ",", "varia...
33.333333
0.00243
def browse(i): """ Input: { data_uoa - data UOA of the repo } Output: { return - return code = 0, if successful > 0, if error (error) - error text if return > 0 } ...
[ "def", "browse", "(", "i", ")", ":", "o", "=", "i", ".", "get", "(", "'out'", ",", "''", ")", "duoa", "=", "i", ".", "get", "(", "'data_uoa'", ",", "''", ")", "if", "duoa", "==", "''", ":", "return", "{", "'return'", ":", "1", ",", "'error'",...
24.780488
0.029356
def _copy_with_changed_callback(self, new_callback): ''' Dev API used to wrap the callback with decorators. ''' return TimeoutCallback(self._document, new_callback, self._timeout, self._id)
[ "def", "_copy_with_changed_callback", "(", "self", ",", "new_callback", ")", ":", "return", "TimeoutCallback", "(", "self", ".", "_document", ",", "new_callback", ",", "self", ".", "_timeout", ",", "self", ".", "_id", ")" ]
67.666667
0.014634
def expect_err(self, msg) -> E: """ Returns the error value in a :class:`Result`, or raises a ``ValueError`` with the provided message. Args: msg: The error message. Returns: The error value in the :class:`Result` if it is a :meth:`Result.Err...
[ "def", "expect_err", "(", "self", ",", "msg", ")", "->", "E", ":", "if", "self", ".", "_is_ok", ":", "raise", "ValueError", "(", "msg", ")", "return", "cast", "(", "E", ",", "self", ".", "_val", ")" ]
27.821429
0.002481
def write(self, text, add_p_style=True, add_t_style=True): """ see mixed content http://effbot.org/zone/element-infoset.htm#mixed-content Writing is complicated by requirements of odp to ignore duplicate spaces together. Deal with this by splitting on white spaces then d...
[ "def", "write", "(", "self", ",", "text", ",", "add_p_style", "=", "True", ",", "add_t_style", "=", "True", ")", ":", "self", ".", "_add_styles", "(", "add_p_style", ",", "add_t_style", ")", "self", ".", "_add_pending_nodes", "(", ")", "spaces", "=", "["...
33.12766
0.001248
def save(self): ''' Persist changes to rethinkdb. Updates only the fields that have changed. Performs insert rather than update if the document has no primary key or if the primary key is absent from the database. If there have been any changes to nested fields, updates the firs...
[ "def", "save", "(", "self", ")", ":", "should_insert", "=", "False", "try", ":", "self", "[", "self", ".", "pk_field", "]", "# raises KeyError if missing", "if", "self", ".", "_updates", ":", "# r.literal() to replace, not merge with, nested fields", "updates", "=",...
45.230769
0.001248
def del_uid(self, search): """ Find and remove a user id that matches the search string given. This method does not modify the corresponding :py:obj:`~pgpy.PGPUID` object; it only removes it from the list of user ids on the key. :param search: A text string to match name, comment, or em...
[ "def", "del_uid", "(", "self", ",", "search", ")", ":", "u", "=", "self", ".", "get_uid", "(", "search", ")", "if", "u", "is", "None", ":", "raise", "KeyError", "(", "\"uid '{:s}' not found\"", ".", "format", "(", "search", ")", ")", "u", ".", "_pare...
37.133333
0.008757
def DedupVcardFilenames(vcard_dict): """Make sure every vCard in the dictionary has a unique filename.""" remove_keys = [] add_pairs = [] for k, v in vcard_dict.items(): if not len(v) > 1: continue for idx, vcard in enumerate(v): fname, ext = os.path.splitext(k) ...
[ "def", "DedupVcardFilenames", "(", "vcard_dict", ")", ":", "remove_keys", "=", "[", "]", "add_pairs", "=", "[", "]", "for", "k", ",", "v", "in", "vcard_dict", ".", "items", "(", ")", ":", "if", "not", "len", "(", "v", ")", ">", "1", ":", "continue"...
28.818182
0.001527
def crypto_sign_open(signed, pk): """ Verifies the signature of the signed message ``signed`` using the public key ``pk`` and returns the unsigned message. :param signed: bytes :param pk: bytes :rtype: bytes """ message = ffi.new("unsigned char[]", len(signed)) message_len = ffi.new...
[ "def", "crypto_sign_open", "(", "signed", ",", "pk", ")", ":", "message", "=", "ffi", ".", "new", "(", "\"unsigned char[]\"", ",", "len", "(", "signed", ")", ")", "message_len", "=", "ffi", ".", "new", "(", "\"unsigned long long *\"", ")", "if", "lib", "...
32.058824
0.001783
def closeView(self, view=None): """ Closes the inputed view. :param view | <int> || <XView> || None """ if type(view) == int: view = self.widget(view) elif view == None: view = self.currentView() index = self.indexOf(...
[ "def", "closeView", "(", "self", ",", "view", "=", "None", ")", ":", "if", "type", "(", "view", ")", "==", "int", ":", "view", "=", "self", ".", "widget", "(", "view", ")", "elif", "view", "==", "None", ":", "view", "=", "self", ".", "currentView...
22.956522
0.010909
def match(self, name): '''Compare an argument string to the task name.''' if (self.ns + self.name).startswith(name): return True for alias in self.aliases: if (self.ns + alias).startswith(name): return True
[ "def", "match", "(", "self", ",", "name", ")", ":", "if", "(", "self", ".", "ns", "+", "self", ".", "name", ")", ".", "startswith", "(", "name", ")", ":", "return", "True", "for", "alias", "in", "self", ".", "aliases", ":", "if", "(", "self", "...
27
0.035874
def WriteHuntResults(client_id, hunt_id, responses): """Writes hunt results from a given client as part of a given hunt.""" if not hunt.IsLegacyHunt(hunt_id): data_store.REL_DB.WriteFlowResults(responses) hunt.StopHuntIfCPUOrNetworkLimitsExceeded(hunt_id) return hunt_id_urn = rdfvalue.RDFURN("hunts...
[ "def", "WriteHuntResults", "(", "client_id", ",", "hunt_id", ",", "responses", ")", ":", "if", "not", "hunt", ".", "IsLegacyHunt", "(", "hunt_id", ")", ":", "data_store", ".", "REL_DB", ".", "WriteFlowResults", "(", "responses", ")", "hunt", ".", "StopHuntIf...
31.7
0.011224
def QA_util_future_to_realdatetime(trade_datetime): """输入是交易所规定的时间,返回真实时间*适用于通达信的时间转换 Arguments: trade_datetime {[type]} -- [description] Returns: [type] -- [description] """ if len(str(trade_datetime)) == 19: dt = datetime.datetime.strptime( str(trade_datetime)...
[ "def", "QA_util_future_to_realdatetime", "(", "trade_datetime", ")", ":", "if", "len", "(", "str", "(", "trade_datetime", ")", ")", "==", "19", ":", "dt", "=", "datetime", ".", "datetime", ".", "strptime", "(", "str", "(", "trade_datetime", ")", "[", "0", ...
32.481481
0.001107
def top(topfn, test=None, queue=False, **kwargs): ''' Execute a specific top file instead of the default. This is useful to apply configurations from a different environment (for example, dev or prod), without modifying the default top file. queue : False Instead of failing immediately when...
[ "def", "top", "(", "topfn", ",", "test", "=", "None", ",", "queue", "=", "False", ",", "*", "*", "kwargs", ")", ":", "conflict", "=", "_check_queue", "(", "queue", ",", "kwargs", ")", "if", "conflict", "is", "not", "None", ":", "return", "conflict", ...
40.685393
0.001348
def rad_longitude(self): """ Lazy conversion degrees longitude to radians. """ if self._rad_longitude is None: self._rad_longitude = math.radians(self.longitude) return self._rad_longitude
[ "def", "rad_longitude", "(", "self", ")", ":", "if", "self", ".", "_rad_longitude", "is", "None", ":", "self", ".", "_rad_longitude", "=", "math", ".", "radians", "(", "self", ".", "longitude", ")", "return", "self", ".", "_rad_longitude" ]
33.428571
0.008333
def insert(self, value, key): """ Insert a value into a tree rooted at the given node, and return whether this was an insertion or update. Balances the tree during insertion. An update is performed instead of an insertion if a value in the tree compares equal to the new...
[ "def", "insert", "(", "self", ",", "value", ",", "key", ")", ":", "# Base case: Insertion into the empty tree is just creating a new node", "# with no children.", "if", "self", "is", "NULL", ":", "return", "Node", "(", "value", ",", "NULL", ",", "NULL", ",", "True...
37.909091
0.001559
def calc_mean_time_deviation(timepoints, weights, mean_time=None): """Return the weighted deviation of the given timepoints from their mean time. With equal given weights, the is simply the standard deviation of the given time points: >>> from hydpy import calc_mean_time_deviation >>> calc_mea...
[ "def", "calc_mean_time_deviation", "(", "timepoints", ",", "weights", ",", "mean_time", "=", "None", ")", ":", "timepoints", "=", "numpy", ".", "array", "(", "timepoints", ")", "weights", "=", "numpy", ".", "array", "(", "weights", ")", "validtools", ".", ...
36.375
0.000558
def node_iterator(self): """Provides an iterator over the nodes. """ return iter(self._node_attributes) def has_hypernode(self, hypernode): """Determines if a specific hypernode is present in the hypergraph. :param node: reference to hypernode whose presence is being checked....
[ "def", "node_iterator", "(", "self", ")", ":", "return", "iter", "(", "self", ".", "_node_attributes", ")", "def", "has_hypernode", "(", "self", ",", "hypernode", ")", ":", "\"\"\"Determines if a specific hypernode is present in the hypergraph.\n\n :param node: refer...
31.785714
0.0131
def get_cached_data(self, url): """ get cached data for a url if stored in the cache and not outdated Args: url: URL for the Ensembl REST service Returns: data if data in cache, else None """ key = self.get_key_from_url(url) ...
[ "def", "get_cached_data", "(", "self", ",", "url", ")", ":", "key", "=", "self", ".", "get_key_from_url", "(", "url", ")", "with", "self", ".", "conn", "as", "conn", ":", "cursor", "=", "conn", ".", "cursor", "(", ")", "cursor", ".", "execute", "(", ...
33.848485
0.010444
def A(self): """Spectral VAR coefficients. .. math:: \mathbf{A}(f) = \mathbf{I} - \sum_{k=1}^{p} \mathbf{a}^{(k)} \mathrm{e}^{-2\pi f} """ return fft(np.dstack([np.eye(self.m), -self.b]), self.nfft * 2 - 1)[:, :, :self.nfft]
[ "def", "A", "(", "self", ")", ":", "return", "fft", "(", "np", ".", "dstack", "(", "[", "np", ".", "eye", "(", "self", ".", "m", ")", ",", "-", "self", ".", "b", "]", ")", ",", "self", ".", "nfft", "*", "2", "-", "1", ")", "[", ":", ","...
35.875
0.027211
def dims_intersect(self): """Dimensions of the arrays in this list that are used in all arrays """ return set.intersection(*map( set, (getattr(arr, 'dims_intersect', arr.dims) for arr in self)))
[ "def", "dims_intersect", "(", "self", ")", ":", "return", "set", ".", "intersection", "(", "*", "map", "(", "set", ",", "(", "getattr", "(", "arr", ",", "'dims_intersect'", ",", "arr", ".", "dims", ")", "for", "arr", "in", "self", ")", ")", ")" ]
45.2
0.008696
def run(self): """ Calls the `perform()` method defined by subclasses and stores the result in a `results` deque. After the result is determined the `results` deque is analyzed to see if the `passing` flag should be updated. If the check was considered passing and the p...
[ "def", "run", "(", "self", ")", ":", "logger", ".", "debug", "(", "\"Running %s check\"", ",", "self", ".", "name", ")", "try", ":", "result", "=", "self", ".", "perform", "(", ")", "except", "Exception", ":", "logger", ".", "exception", "(", "\"Error ...
38.085714
0.001463
def geosearch(latitude, longitude, title=None, results=10, radius=1000): ''' Do a wikipedia geo search for `latitude` and `longitude` using HTTP API described in http://www.mediawiki.org/wiki/Extension:GeoData Arguments: * latitude (float or decimal.Decimal) * longitude (float or decimal.Decimal) Keywo...
[ "def", "geosearch", "(", "latitude", ",", "longitude", ",", "title", "=", "None", ",", "results", "=", "10", ",", "radius", "=", "1000", ")", ":", "search_params", "=", "{", "'list'", ":", "'geosearch'", ",", "'gsradius'", ":", "radius", ",", "'gscoord'"...
30.658537
0.010023
def debug_print(self): """ Prints the ring for debugging purposes. """ ring = self._fetch_all() print('Hash ring "{key}" replicas:'.format(key=self.key)) now = time.time() n_replicas = len(ring) if ring: print('{:10} {:6} {:7} {}'.format('St...
[ "def", "debug_print", "(", "self", ")", ":", "ring", "=", "self", ".", "_fetch_all", "(", ")", "print", "(", "'Hash ring \"{key}\" replicas:'", ".", "format", "(", "key", "=", "self", ".", "key", ")", ")", "now", "=", "time", ".", "time", "(", ")", "...
32.833333
0.002464
def execute(self, command=None, container_id=None, sudo=False, stream=False): '''execute a command to a container instance based on container_id Parameters ========== container_id: the container_id to delete command: the command to execute to the container sudo: whether to issue ...
[ "def", "execute", "(", "self", ",", "command", "=", "None", ",", "container_id", "=", "None", ",", "sudo", "=", "False", ",", "stream", "=", "False", ")", ":", "sudo", "=", "self", ".", "_get_sudo", "(", "sudo", ")", "container_id", "=", "self", ".",...
35.108108
0.001498
def get_occurrence(event_id, occurrence_id=None, year=None, month=None, day=None, hour=None, minute=None, second=None, tzinfo=None): """ Because occurrences don't have to be persisted, there must be two ways to retrieve them. both need an event, but if its persisted the...
[ "def", "get_occurrence", "(", "event_id", ",", "occurrence_id", "=", "None", ",", "year", "=", "None", ",", "month", "=", "None", ",", "day", "=", "None", ",", "hour", "=", "None", ",", "minute", "=", "None", ",", "second", "=", "None", ",", "tzinfo"...
46.041667
0.000887
def body(cls, description=None, default=None, resource=DefaultResource, **options): """ Define body parameter. """ return cls('body', In.Body, None, resource, description, required=True, default=default, **options)
[ "def", "body", "(", "cls", ",", "description", "=", "None", ",", "default", "=", "None", ",", "resource", "=", "DefaultResource", ",", "*", "*", "options", ")", ":", "return", "cls", "(", "'body'", ",", "In", ".", "Body", ",", "None", ",", "resource"...
43.333333
0.011321
def set_value(self, value): """Set formatted text value.""" self.value = value if self.isVisible(): self.label_value.setText(value)
[ "def", "set_value", "(", "self", ",", "value", ")", ":", "self", ".", "value", "=", "value", "if", "self", ".", "isVisible", "(", ")", ":", "self", ".", "label_value", ".", "setText", "(", "value", ")" ]
32.6
0.011976
def get_bulb_state(self): """Get the relay state.""" self.get_status() try: self.state = self.data['on'] except TypeError: self.state = False return bool(self.state)
[ "def", "get_bulb_state", "(", "self", ")", ":", "self", ".", "get_status", "(", ")", "try", ":", "self", ".", "state", "=", "self", ".", "data", "[", "'on'", "]", "except", "TypeError", ":", "self", ".", "state", "=", "False", "return", "bool", "(", ...
24.666667
0.008696
def optimizer(self, temperature): """ Evaluate G(V, T, P) at the given temperature(and pressure) and minimize it wrt V. 1. Compute the vibrational helmholtz free energy, A_vib. 2. Compute the gibbs free energy as a function of volume, temperature and pressure, G(V,T...
[ "def", "optimizer", "(", "self", ",", "temperature", ")", ":", "G_V", "=", "[", "]", "# G for each volume", "# G = E(V) + PV + A_vib(V, T)", "for", "i", ",", "v", "in", "enumerate", "(", "self", ".", "volumes", ")", ":", "G_V", ".", "append", "(", "self", ...
41.529412
0.001384
def stdDev(self): ''' get the standard deviation from the PSF is evaluated as 2d Gaussian ''' if self._corrPsf is None: self.psf() p = self._corrPsf.copy() mn = p.min() p[p<0.05*p.max()] = mn p-=mn p/=p.sum() ...
[ "def", "stdDev", "(", "self", ")", ":", "if", "self", ".", "_corrPsf", "is", "None", ":", "self", ".", "psf", "(", ")", "p", "=", "self", ".", "_corrPsf", ".", "copy", "(", ")", "mn", "=", "p", ".", "min", "(", ")", "p", "[", "p", "<", "0.0...
23.846154
0.023256
def design_stat_heating(self, value="Heating"): """Corresponds to IDD Field `design_stat_heating` Args: value (str): value for IDD Field `design_stat_heating` Accepted values are: - Heating Default value: Heating if `valu...
[ "def", "design_stat_heating", "(", "self", ",", "value", "=", "\"Heating\"", ")", ":", "if", "value", "is", "not", "None", ":", "try", ":", "value", "=", "str", "(", "value", ")", "except", "ValueError", ":", "raise", "ValueError", "(", "'value {} need to ...
37.8125
0.001612
def ip_address(self, **kwargs): """ Set IP Address on an Interface. Args: int_type (str): Type of interface. (gigabitethernet, tengigabitethernet etc). name (str): Name of interface id. (For interface: 1/0/5, 1/0/10 etc). ip_...
[ "def", "ip_address", "(", "self", ",", "*", "*", "kwargs", ")", ":", "int_type", "=", "str", "(", "kwargs", ".", "pop", "(", "'int_type'", ")", ".", "lower", "(", ")", ")", "name", "=", "str", "(", "kwargs", ".", "pop", "(", "'name'", ")", ")", ...
47.564516
0.000332
def read(self, input_stream, kmip_version=enums.KMIPVersion.KMIP_1_0): """ Read the data encoding the Encrypt response payload and decode it into its constituent parts. Args: input_stream (stream): A data stream containing encoded object data, supporting a re...
[ "def", "read", "(", "self", ",", "input_stream", ",", "kmip_version", "=", "enums", ".", "KMIPVersion", ".", "KMIP_1_0", ")", ":", "super", "(", "EncryptResponsePayload", ",", "self", ")", ".", "read", "(", "input_stream", ",", "kmip_version", "=", "kmip_ver...
36.781818
0.000963
def pp_predict_motifs(fastafile, outfile, analysis="small", organism="hg18", single=False, background="", tools=None, job_server=None, ncpus=8, max_time=-1, stats_fg=None, stats_bg=None): """Parallel prediction of motifs. Utility function for gimmemotifs.denovo.gimme_motifs. Probably better to use that, i...
[ "def", "pp_predict_motifs", "(", "fastafile", ",", "outfile", ",", "analysis", "=", "\"small\"", ",", "organism", "=", "\"hg18\"", ",", "single", "=", "False", ",", "background", "=", "\"\"", ",", "tools", "=", "None", ",", "job_server", "=", "None", ",", ...
35.970588
0.011339
def download_content(**args): """ main function to fetch links and download them """ args = validate_args(**args) if not args['directory']: args['directory'] = args['query'].replace(' ', '-') print("Downloading {0} {1} files on topic {2} from {3} and saving to directory: {4}" .format(args['limit'], args['fi...
[ "def", "download_content", "(", "*", "*", "args", ")", ":", "args", "=", "validate_args", "(", "*", "*", "args", ")", "if", "not", "args", "[", "'directory'", "]", ":", "args", "[", "'directory'", "]", "=", "args", "[", "'query'", "]", ".", "replace"...
38
0.031081
def connection_from_host(self, host, port=None, scheme='http'): """ Get a :class:`ConnectionPool` based on the host, port, and scheme. If ``port`` isn't given, it will be derived from the ``scheme`` using ``urllib3.connectionpool.port_by_scheme``. """ if not host: ...
[ "def", "connection_from_host", "(", "self", ",", "host", ",", "port", "=", "None", ",", "scheme", "=", "'http'", ")", ":", "if", "not", "host", ":", "raise", "LocationValueError", "(", "\"No host specified.\"", ")", "scheme", "=", "scheme", "or", "'http'", ...
33.444444
0.002153
def _wait_for_tasks(tasks, service_instance): ''' Wait for tasks created via the VSAN API ''' log.trace('Waiting for vsan tasks: {0}', ', '.join([six.text_type(t) for t in tasks])) try: vsanapiutils.WaitForTasks(tasks, service_instance) except vim.fault.NoPermission as exc:...
[ "def", "_wait_for_tasks", "(", "tasks", ",", "service_instance", ")", ":", "log", ".", "trace", "(", "'Waiting for vsan tasks: {0}'", ",", "', '", ".", "join", "(", "[", "six", ".", "text_type", "(", "t", ")", "for", "t", "in", "tasks", "]", ")", ")", ...
39.1
0.001248
def get_account_details(self, account): """ Get the account details """ result = self.get_user(account.username) if result is None: result = {} return result
[ "def", "get_account_details", "(", "self", ",", "account", ")", ":", "result", "=", "self", ".", "get_user", "(", "account", ".", "username", ")", "if", "result", "is", "None", ":", "result", "=", "{", "}", "return", "result" ]
32.666667
0.00995
def complete_vrf(arg): """ Returns list of matching VRFs """ search_string = '' if arg is not None: search_string = '^%s' % arg res = VRF.search({ 'operator': 'regex_match', 'val1': 'rt', 'val2': search_string }, { 'max_result': 100000 } ) ret = [] ...
[ "def", "complete_vrf", "(", "arg", ")", ":", "search_string", "=", "''", "if", "arg", "is", "not", "None", ":", "search_string", "=", "'^%s'", "%", "arg", "res", "=", "VRF", ".", "search", "(", "{", "'operator'", ":", "'regex_match'", ",", "'val1'", ":...
19.636364
0.00883
def _get_closest_ansi_color(r, g, b, exclude=()): """ Find closest ANSI color. Return it by name. :param r: Red (Between 0 and 255.) :param g: Green (Between 0 and 255.) :param b: Blue (Between 0 and 255.) :param exclude: A tuple of color names to exclude. (E.g. ``('ansired', )``.) """ ...
[ "def", "_get_closest_ansi_color", "(", "r", ",", "g", ",", "b", ",", "exclude", "=", "(", ")", ")", ":", "assert", "isinstance", "(", "exclude", ",", "tuple", ")", "# When we have a bit of saturation, avoid the gray-like colors, otherwise,", "# too often the distance to...
34.15625
0.001779
def unique_array(arr): """ Returns an array of unique values in the input order. Args: arr (np.ndarray or list): The array to compute unique values on Returns: A new array of unique values """ if not len(arr): return np.asarray(arr) elif pd: if isinstance(arr,...
[ "def", "unique_array", "(", "arr", ")", ":", "if", "not", "len", "(", "arr", ")", ":", "return", "np", ".", "asarray", "(", "arr", ")", "elif", "pd", ":", "if", "isinstance", "(", "arr", ",", "np", ".", "ndarray", ")", "and", "arr", ".", "dtype",...
29.714286
0.002328
def trigger(self): """ calls the call_back function. interrupts the timer to start a new countdown """ self.call_back(*self.args, **self.kwargs) if self.__timer is not None: self.__timer.cancel()
[ "def", "trigger", "(", "self", ")", ":", "self", ".", "call_back", "(", "*", "self", ".", "args", ",", "*", "*", "self", ".", "kwargs", ")", "if", "self", ".", "__timer", "is", "not", "None", ":", "self", ".", "__timer", ".", "cancel", "(", ")" ]
45.4
0.012987
def unhandled(self, key): """Handle other keyboard actions not handled by the ListBox widget. """ self.key = key self.size = self.tui.get_cols_rows() if self.search is True: if self.enter is False and self.no_matches is False: if len(key) == 1 and key...
[ "def", "unhandled", "(", "self", ",", "key", ")", ":", "self", ".", "key", "=", "key", "self", ".", "size", "=", "self", ".", "tui", ".", "get_cols_rows", "(", ")", "if", "self", ".", "search", "is", "True", ":", "if", "self", ".", "enter", "is",...
35.909091
0.002466
def get_user_info(remote): """Get user information from Globus. See the docs here for v2/oauth/userinfo: https://docs.globus.org/api/auth/reference/ """ response = remote.get(GLOBUS_USER_INFO_URL) user_info = get_dict_from_response(response) response.data['username'] = response.data['prefer...
[ "def", "get_user_info", "(", "remote", ")", ":", "response", "=", "remote", ".", "get", "(", "GLOBUS_USER_INFO_URL", ")", "user_info", "=", "get_dict_from_response", "(", "response", ")", "response", ".", "data", "[", "'username'", "]", "=", "response", ".", ...
38.083333
0.002137
def _init_client(self, from_archive=False): """Init client""" return ConfluenceClient(self.url, archive=self.archive, from_archive=from_archive)
[ "def", "_init_client", "(", "self", ",", "from_archive", "=", "False", ")", ":", "return", "ConfluenceClient", "(", "self", ".", "url", ",", "archive", "=", "self", ".", "archive", ",", "from_archive", "=", "from_archive", ")" ]
39.5
0.018634
def asymmetric_round_price_to_penny(price, prefer_round_down, diff=(0.0095 - .005)): """ Asymmetric rounding function for adjusting prices to two places in a way that "improves" the price. For limit prices, this means preferring to round down on buys and preferring t...
[ "def", "asymmetric_round_price_to_penny", "(", "price", ",", "prefer_round_down", ",", "diff", "=", "(", "0.0095", "-", ".005", ")", ")", ":", "# Subtracting an epsilon from diff to enforce the open-ness of the upper", "# bound on buys and the lower bound on sells. Using the actua...
44.357143
0.000788
def _compileSmsRegexes(self): """ Compiles regular expression used for parsing SMS messages based on current mode """ if self._smsTextMode: if self.CMGR_SM_DELIVER_REGEX_TEXT == None: self.CMGR_SM_DELIVER_REGEX_TEXT = re.compile(r'^\+CMGR: "([^"]+)","([^"]+)",[^,]*,"([^"]+)"$...
[ "def", "_compileSmsRegexes", "(", "self", ")", ":", "if", "self", ".", "_smsTextMode", ":", "if", "self", ".", "CMGR_SM_DELIVER_REGEX_TEXT", "==", "None", ":", "self", ".", "CMGR_SM_DELIVER_REGEX_TEXT", "=", "re", ".", "compile", "(", "r'^\\+CMGR: \"([^\"]+)\",\"(...
73.875
0.013378
def make(parser): """ Repo definition management """ parser.add_argument( 'repo_name', metavar='REPO-NAME', help='Name of repo to manage. Can match an entry in cephdeploy.conf' ) parser.add_argument( '--repo-url', help='a repo URL that mirrors/contains ...
[ "def", "make", "(", "parser", ")", ":", "parser", ".", "add_argument", "(", "'repo_name'", ",", "metavar", "=", "'REPO-NAME'", ",", "help", "=", "'Name of repo to manage. Can match an entry in cephdeploy.conf'", ")", "parser", ".", "add_argument", "(", "'--repo-url'"...
19.972973
0.00129
def init_flatpak(): """ If we are in Flatpak, we must build a tessdata/ directory using the .traineddata files from each locale directory """ tessdata_files = glob.glob("/app/share/locale/*/*.traineddata") if len(tessdata_files) <= 0: return os.path.exists("/app") localdir = os.path...
[ "def", "init_flatpak", "(", ")", ":", "tessdata_files", "=", "glob", ".", "glob", "(", "\"/app/share/locale/*/*.traineddata\"", ")", "if", "len", "(", "tessdata_files", ")", "<=", "0", ":", "return", "os", ".", "path", ".", "exists", "(", "\"/app\"", ")", ...
40.055556
0.000677
def GetFormatSpecification(cls): """Retrieves the format specification. Returns: FormatSpecification: format specification. """ format_specification = specification.FormatSpecification(cls.NAME) # OLECF format_specification.AddNewSignature( b'\xd0\xcf\x11\xe0\xa1\xb1\x1a\xe1', of...
[ "def", "GetFormatSpecification", "(", "cls", ")", ":", "format_specification", "=", "specification", ".", "FormatSpecification", "(", "cls", ".", "NAME", ")", "# OLECF", "format_specification", ".", "AddNewSignature", "(", "b'\\xd0\\xcf\\x11\\xe0\\xa1\\xb1\\x1a\\xe1'", ",...
27
0.002105
def get_meta(self): """Get the metadata object for this Thing Returns a [ThingMeta](ThingMeta.m.html#IoticAgent.IOT.ThingMeta.ThingMeta) object """ rdf = self.get_meta_rdf(fmt='n3') return ThingMeta(self, rdf, self._client.default_lang, fmt='n3')
[ "def", "get_meta", "(", "self", ")", ":", "rdf", "=", "self", ".", "get_meta_rdf", "(", "fmt", "=", "'n3'", ")", "return", "ThingMeta", "(", "self", ",", "rdf", ",", "self", ".", "_client", ".", "default_lang", ",", "fmt", "=", "'n3'", ")" ]
40.142857
0.010453