text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def with_revision(self, label, number): """ Returns a Tag with a given revision """ t = self.clone() t.revision = Revision(label, number) return t
[ "def", "with_revision", "(", "self", ",", "label", ",", "number", ")", ":", "t", "=", "self", ".", "clone", "(", ")", "t", ".", "revision", "=", "Revision", "(", "label", ",", "number", ")", "return", "t" ]
26.857143
0.010309
def importer(name, extensions=None, sniff=None): ''' @importer(name) is a decorator that declares that the following function is an file loading function that should be registered with the neuropythy load function. See also the forget_importer function. Any importer function must take, as its f...
[ "def", "importer", "(", "name", ",", "extensions", "=", "None", ",", "sniff", "=", "None", ")", ":", "name", "=", "name", ".", "lower", "(", ")", "if", "name", "in", "importers", ":", "raise", "ValueError", "(", "'An importer for type %s already exists; see ...
50.172414
0.00944
def lookup(source, keys, fallback = None): """Traverses the source, looking up each key. Returns None if can't find anything instead of raising an exception.""" try: for key in keys: source = source[key] return source except (KeyError, AttributeError, TypeError): return fallback
[ "def", "lookup", "(", "source", ",", "keys", ",", "fallback", "=", "None", ")", ":", "try", ":", "for", "key", "in", "keys", ":", "source", "=", "source", "[", "key", "]", "return", "source", "except", "(", "KeyError", ",", "AttributeError", ",", "Ty...
37.125
0.026316
def _create_project(self, path): """Create a new project.""" self.open_project(path=path) self.setup_menu_actions() self.add_to_recent(path)
[ "def", "_create_project", "(", "self", ",", "path", ")", ":", "self", ".", "open_project", "(", "path", "=", "path", ")", "self", ".", "setup_menu_actions", "(", ")", "self", ".", "add_to_recent", "(", "path", ")" ]
34.4
0.011364
def execute_script(code_block, example_globals, image_path, fig_count, src_file, gallery_conf): """Executes the code block of the example file""" time_elapsed = 0 stdout = '' # We need to execute the code print('plotting code blocks in %s' % src_file) plt.close('all') cw...
[ "def", "execute_script", "(", "code_block", ",", "example_globals", ",", "image_path", ",", "fig_count", ",", "src_file", ",", "gallery_conf", ")", ":", "time_elapsed", "=", "0", "stdout", "=", "''", "# We need to execute the code", "print", "(", "'plotting code blo...
33.405405
0.000393
def action_rm(self): """ Delete a shortcut """ name = self.args['<name>'] if self.args['all']: # delete all if ask_yes_no('Really delete ALL shortcuts?', default='no'): self.db_exec(''' DELETE FROM shortcuts ''') print_ms...
[ "def", "action_rm", "(", "self", ")", ":", "name", "=", "self", ".", "args", "[", "'<name>'", "]", "if", "self", ".", "args", "[", "'all'", "]", ":", "# delete all", "if", "ask_yes_no", "(", "'Really delete ALL shortcuts?'", ",", "default", "=", "'no'", ...
25.205128
0.001959
def Stichlmair_wet(Vg, Vl, rhog, rhol, mug, voidage, specific_area, C1, C2, C3, H=1): r'''Calculates dry pressure drop across a packed column, using the Stichlmair [1]_ correlation. Uses three regressed constants for each type of packing, and voidage and specific area. This model is for irrigated column...
[ "def", "Stichlmair_wet", "(", "Vg", ",", "Vl", ",", "rhog", ",", "rhol", ",", "mug", ",", "voidage", ",", "specific_area", ",", "C1", ",", "C2", ",", "C3", ",", "H", "=", "1", ")", ":", "dp", "=", "6.0", "*", "(", "1.0", "-", "voidage", ")", ...
33.638095
0.00165
def _load_plugins(namespace, instantiate=True): """ Loads all the plugins for the given namespace Args: namespace(str): Namespace string, as in the setuptools entry_points instantiate(bool): If true, will instantiate the plugins too Returns: dict of str, object: Returns the lis...
[ "def", "_load_plugins", "(", "namespace", ",", "instantiate", "=", "True", ")", ":", "mgr", "=", "ExtensionManager", "(", "namespace", "=", "namespace", ",", "on_load_failure_callback", "=", "(", "lambda", "_", ",", "ep", ",", "err", ":", "LOGGER", ".", "w...
28.724138
0.001161
def pack_bits( longbits ): """Crunch a 64-bit int (8 bool bytes) into a bitfield.""" byte = longbits & (0x0101010101010101) byte = (byte | (byte>>7)) & (0x0003000300030003) byte = (byte | (byte>>14)) & (0x0000000f0000000f) byte = (byte | (byte>>28)) & (0x00000000000000ff) return byte
[ "def", "pack_bits", "(", "longbits", ")", ":", "byte", "=", "longbits", "&", "(", "0x0101010101010101", ")", "byte", "=", "(", "byte", "|", "(", "byte", ">>", "7", ")", ")", "&", "(", "0x0003000300030003", ")", "byte", "=", "(", "byte", "|", "(", "...
43.142857
0.019481
def normalize_range(e, n): """ Return the range tuple normalized for an ``n``-element object. The semantics of a range is slightly different than that of a slice. In particular, a range is similar to a list in meaning (and on Py2 it was eagerly expanded into a list). Thus we do not allow the range...
[ "def", "normalize_range", "(", "e", ",", "n", ")", ":", "if", "e", ".", "step", ">", "0", ":", "count", "=", "max", "(", "0", ",", "(", "e", ".", "stop", "-", "e", ".", "start", "-", "1", ")", "//", "e", ".", "step", "+", "1", ")", "else"...
37.486486
0.000703
def communicate(self): """Retrieve information.""" self._communicate_first = True self._process.waitForFinished() enco = self._get_encoding() if self._partial_stdout is None: raw_stdout = self._process.readAllStandardOutput() stdout = handle_qbytearray(ra...
[ "def", "communicate", "(", "self", ")", ":", "self", ".", "_communicate_first", "=", "True", "self", ".", "_process", ".", "waitForFinished", "(", ")", "enco", "=", "self", ".", "_get_encoding", "(", ")", "if", "self", ".", "_partial_stdout", "is", "None",...
28.178571
0.002451
def _pre_request(self, url, method = u"get", data = None, headers=None, **kwargs): """ hook for manipulating the _pre request data """ header = { u"Content-Type": u"application/json", u"User-Agent": u"salesking_api_py_v1", } if headers: ...
[ "def", "_pre_request", "(", "self", ",", "url", ",", "method", "=", "u\"get\"", ",", "data", "=", "None", ",", "headers", "=", "None", ",", "*", "*", "kwargs", ")", ":", "header", "=", "{", "u\"Content-Type\"", ":", "u\"application/json\"", ",", "u\"User...
34.133333
0.01711
def get_config_argparse(suppress=None): """ Create an ArgumentParser which listens for the following common options: - --config - --help - --quiet - --verbose - --version Arguments --------- suppress_help: list of strings Defines what options to suppress from being added to the ArgumentParser. Provide th...
[ "def", "get_config_argparse", "(", "suppress", "=", "None", ")", ":", "if", "suppress", "is", "None", ":", "suppress", "=", "[", "]", "config_parser", "=", "ArgumentParser", "(", "description", "=", "\"Looking for config\"", ",", "add_help", "=", "(", "not", ...
43.052632
0.030484
async def transaction(self, func, *watches, **kwargs): """ Convenience method for executing the callable `func` as a transaction while watching all keys specified in `watches`. The 'func' callable should expect a single argument which is a Pipeline object. """ shard_hint ...
[ "async", "def", "transaction", "(", "self", ",", "func", ",", "*", "watches", ",", "*", "*", "kwargs", ")", ":", "shard_hint", "=", "kwargs", ".", "pop", "(", "'shard_hint'", ",", "None", ")", "value_from_callable", "=", "kwargs", ".", "pop", "(", "'va...
47.166667
0.001732
def trim(docstring): """ Remove the tabs to spaces, and remove the extra spaces / tabs that are in front of the text in docstrings. Implementation taken from http://www.python.org/dev/peps/pep-0257/ """ if not docstring: return '' # Convert tabs to spaces (following the normal Pytho...
[ "def", "trim", "(", "docstring", ")", ":", "if", "not", "docstring", ":", "return", "''", "# Convert tabs to spaces (following the normal Python rules)", "# and split into a list of lines:", "lines", "=", "six", ".", "u", "(", "docstring", ")", ".", "expandtabs", "(",...
33.4
0.001942
def generate_view_data(self): """Generate the views.""" self.view_data['version'] = '{} {}'.format('Glances', __version__) self.view_data['psutil_version'] = ' with psutil {}'.format(psutil_version) try: self.view_data['configuration_file'] = 'Configuration file: {}'.format(...
[ "def", "generate_view_data", "(", "self", ")", ":", "self", ".", "view_data", "[", "'version'", "]", "=", "'{} {}'", ".", "format", "(", "'Glances'", ",", "__version__", ")", "self", ".", "view_data", "[", "'psutil_version'", "]", "=", "' with psutil {}'", "...
81.714286
0.009872
def create(cls, name, datacenter, backends, vhosts, algorithm, ssl_enable, zone_alter): """ Create a webaccelerator """ datacenter_id_ = int(Datacenter.usable_id(datacenter)) params = { 'datacenter_id': datacenter_id_, 'name': name, 'lb': {'algo...
[ "def", "create", "(", "cls", ",", "name", ",", "datacenter", ",", "backends", ",", "vhosts", ",", "algorithm", ",", "ssl_enable", ",", "zone_alter", ")", ":", "datacenter_id_", "=", "int", "(", "Datacenter", ".", "usable_id", "(", "datacenter", ")", ")", ...
46.361702
0.001348
def print_logs(redis_client, threads_stopped): """Prints log messages from workers on all of the nodes. Args: redis_client: A client to the primary Redis shard. threads_stopped (threading.Event): A threading event used to signal to the thread that it should exit. """ pubsub_...
[ "def", "print_logs", "(", "redis_client", ",", "threads_stopped", ")", ":", "pubsub_client", "=", "redis_client", ".", "pubsub", "(", "ignore_subscribe_messages", "=", "True", ")", "pubsub_client", ".", "subscribe", "(", "ray", ".", "gcs_utils", ".", "LOG_FILE_CHA...
45.34
0.000432
def _request_finished(self, reply): """Callback for download once the request has finished.""" url = to_text_string(reply.url().toEncoded(), encoding='utf-8') if url in self._paths: path = self._paths[url] if url in self._workers: worker = self._workers[url] ...
[ "def", "_request_finished", "(", "self", ",", "reply", ")", ":", "url", "=", "to_text_string", "(", "reply", ".", "url", "(", ")", ".", "toEncoded", "(", ")", ",", "encoding", "=", "'utf-8'", ")", "if", "url", "in", "self", ".", "_paths", ":", "path"...
36.982143
0.000941
def rgb2short(rgb): """ Find the closest xterm-256 approximation to the given RGB value. @param rgb: Hex code representing an RGB value, eg, 'abcdef' @returns: String between 0 and 255, compatible with xterm. >>> rgb2short('123456') ('23', '005f5f') >>> rgb2short('ffffff') ('231', 'ffffff') ...
[ "def", "rgb2short", "(", "rgb", ")", ":", "incs", "=", "(", "0x00", ",", "0x5f", ",", "0x87", ",", "0xaf", ",", "0xd7", ",", "0xff", ")", "# Break 6-char RGB code into 3 integer vals.", "parts", "=", "[", "int", "(", "h", ",", "16", ")", "for", "h", ...
33.5625
0.009955
def get_node(manager, handle_id, legacy=True): """ :param manager: Manager to handle sessions and transactions :param handle_id: Unique id :param legacy: Backwards compatibility :type manager: norduniclient.contextmanager.Neo4jDBSessionManager :type handle_id: str|unicode :type legacy: Bool...
[ "def", "get_node", "(", "manager", ",", "handle_id", ",", "legacy", "=", "True", ")", ":", "q", "=", "'MATCH (n:Node { handle_id: {handle_id} }) RETURN n'", "with", "manager", ".", "session", "as", "s", ":", "result", "=", "s", ".", "run", "(", "q", ",", "...
32.190476
0.001437
def render_profile(cls, raw_profile, profile_name, target_override, cli_vars): """This is a containment zone for the hateful way we're rendering profiles. """ renderer = ConfigRenderer(cli_vars=cli_vars) # rendering profiles is a bit complex. Two constrain...
[ "def", "render_profile", "(", "cls", ",", "raw_profile", ",", "profile_name", ",", "target_override", ",", "cli_vars", ")", ":", "renderer", "=", "ConfigRenderer", "(", "cli_vars", "=", "cli_vars", ")", "# rendering profiles is a bit complex. Two constraints cause trouble...
43.25
0.00212
def cli(argv=None): """CLI entry point for mozdownload.""" kwargs = parse_arguments(argv or sys.argv[1:]) log_level = kwargs.pop('log_level') logging.basicConfig(format='%(levelname)s | %(message)s', level=log_level) logger = logging.getLogger(__name__) # Configure logging levels for sub modul...
[ "def", "cli", "(", "argv", "=", "None", ")", ":", "kwargs", "=", "parse_arguments", "(", "argv", "or", "sys", ".", "argv", "[", "1", ":", "]", ")", "log_level", "=", "kwargs", ".", "pop", "(", "'log_level'", ")", "logging", ".", "basicConfig", "(", ...
35.7
0.000909
def appendSpacePadding(str, blocksize=AES_blocksize): 'Pad with spaces' pad_len = paddingLength(len(str), blocksize) padding = '\0'*pad_len return str + padding
[ "def", "appendSpacePadding", "(", "str", ",", "blocksize", "=", "AES_blocksize", ")", ":", "pad_len", "=", "paddingLength", "(", "len", "(", "str", ")", ",", "blocksize", ")", "padding", "=", "'\\0'", "*", "pad_len", "return", "str", "+", "padding" ]
24.571429
0.039326
def partial_distance_covariance(x, y, z): """ Partial distance covariance estimator. Compute the estimator for the partial distance covariance of the random vectors corresponding to :math:`x` and :math:`y` with respect to the random variable corresponding to :math:`z`. Parameters ---------...
[ "def", "partial_distance_covariance", "(", "x", ",", "y", ",", "z", ")", ":", "a", "=", "_u_distance_matrix", "(", "x", ")", "b", "=", "_u_distance_matrix", "(", "y", ")", "c", "=", "_u_distance_matrix", "(", "z", ")", "proj", "=", "u_complementary_project...
31.775862
0.000526
def has_wrap_around_links(self, minimum_working=0.9): """Test if a machine has wrap-around connections installed. Since the Machine object does not explicitly define whether a machine has wrap-around links they must be tested for directly. This test performs a "fuzzy" test on the number...
[ "def", "has_wrap_around_links", "(", "self", ",", "minimum_working", "=", "0.9", ")", ":", "working", "=", "0", "for", "x", "in", "range", "(", "self", ".", "width", ")", ":", "if", "(", "x", ",", "0", ",", "Links", ".", "south", ")", "in", "self",...
37.326087
0.001135
def disambiguate_entity(key, text): """Resolve ambiguity between entities with same dimensionality.""" new_ent = l.DERIVED_ENT[key][0] if len(l.DERIVED_ENT[key]) > 1: transformed = TFIDF_MODEL.transform([text]) scores = CLF.predict_proba(transformed).tolist()[0] scores = sorted(zip(...
[ "def", "disambiguate_entity", "(", "key", ",", "text", ")", ":", "new_ent", "=", "l", ".", "DERIVED_ENT", "[", "key", "]", "[", "0", "]", "if", "len", "(", "l", ".", "DERIVED_ENT", "[", "key", "]", ")", ">", "1", ":", "transformed", "=", "TFIDF_MOD...
39.470588
0.001456
def init_params(self, protocol_interface, phy_interface): """Initializing parameters. """ self.lldp_cfgd = False self.local_intf = protocol_interface self.phy_interface = phy_interface self.remote_evb_cfgd = False self.remote_evb_mode = None self.remote_mgmt_addr ...
[ "def", "init_params", "(", "self", ",", "protocol_interface", ",", "phy_interface", ")", ":", "self", ".", "lldp_cfgd", "=", "False", "self", ".", "local_intf", "=", "protocol_interface", "self", ".", "phy_interface", "=", "phy_interface", "self", ".", "remote_e...
37.2
0.002096
def parse_changesets(text): """ Returns dictionary with *start*, *main* and *end* ids. Examples:: >>> parse_changesets('aaabbb') {'start': None, 'main': 'aaabbb', 'end': None} >>> parse_changesets('aaabbb..cccddd') {'start': 'aaabbb', 'main': None, 'end': 'cccddd'} """...
[ "def", "parse_changesets", "(", "text", ")", ":", "text", "=", "text", ".", "strip", "(", ")", "CID_RE", "=", "r'[a-zA-Z0-9]+'", "if", "not", "'..'", "in", "text", ":", "m", "=", "re", ".", "match", "(", "r'^(?P<cid>%s)$'", "%", "CID_RE", ",", "text", ...
27.533333
0.002339
def get_item_ids_metadata(self): """get the metadata for item""" metadata = dict(self._item_ids_metadata) metadata.update({'existing_id_values': self.my_osid_object_form._my_map['itemIds']}) return Metadata(**metadata)
[ "def", "get_item_ids_metadata", "(", "self", ")", ":", "metadata", "=", "dict", "(", "self", ".", "_item_ids_metadata", ")", "metadata", ".", "update", "(", "{", "'existing_id_values'", ":", "self", ".", "my_osid_object_form", ".", "_my_map", "[", "'itemIds'", ...
49.2
0.012
def static_full_sizes(width, height, tilesize): """Generator for scaled-down full image sizes. Positional arguments: width -- width of full size image height -- height of full size image tilesize -- width and height of tiles Yields [sw,sh], the size for each full-region tile that is less than ...
[ "def", "static_full_sizes", "(", "width", ",", "height", ",", "tilesize", ")", ":", "# FIXME - Not sure what correct algorithm is for this, from", "# observation of Openseadragon it seems that one keeps halving", "# the pixel size of the full image until until both width and", "# height ar...
45.090909
0.000658
def _request(self, url, method='GET', params=None): """Internal stream request handling""" self.connected = True retry_counter = 0 method = method.lower() func = getattr(self.client, method) params, _ = _transparent_params(params) def _send(retry_counter): ...
[ "def", "_request", "(", "self", ",", "url", ",", "method", "=", "'GET'", ",", "params", "=", "None", ")", ":", "self", ".", "connected", "=", "True", "retry_counter", "=", "0", "method", "=", "method", ".", "lower", "(", ")", "func", "=", "getattr", ...
39.820896
0.000732
def write_moc_fits_hdu(moc): """Create a FITS table HDU representation of a MOC. """ # Ensure data are normalized. moc.normalize() # Determine whether a 32 or 64 bit column is required. if moc.order < 14: moc_type = np.int32 col_type = 'J' else: moc_type = np.int64 ...
[ "def", "write_moc_fits_hdu", "(", "moc", ")", ":", "# Ensure data are normalized.", "moc", ".", "normalize", "(", ")", "# Determine whether a 32 or 64 bit column is required.", "if", "moc", ".", "order", "<", "14", ":", "moc_type", "=", "np", ".", "int32", "col_type...
33.6
0.000445
def get_config(cli_args=None, config_path=None): """ Perform standard setup - get the merged config :param cli_args dict: A dictionary of CLI arguments :param config_path string: Path to the config file to load :return dict: A dictionary of config values drawn from different sources """ co...
[ "def", "get_config", "(", "cli_args", "=", "None", ",", "config_path", "=", "None", ")", ":", "config", "=", "Config", "(", "app_name", "=", "\"MYAPP\"", ",", "cli_args", "=", "cli_args", ",", "config_path", "=", "config_path", ")", "config_dict", "=", "co...
34.5
0.002016
def filter(self, u): """Filter the valid identities for this matcher. :param u: unique identity which stores the identities to filter :returns: a list of identities valid to work with this matcher. :raises ValueError: when the unique identity is not an instance of UniqueId...
[ "def", "filter", "(", "self", ",", "u", ")", ":", "if", "not", "isinstance", "(", "u", ",", "UniqueIdentity", ")", ":", "raise", "ValueError", "(", "\"<u> is not an instance of UniqueIdentity\"", ")", "filtered", "=", "[", "]", "for", "id_", "in", "u", "."...
32.625
0.001488
def multinomial_resample(weights): """ This is the naive form of roulette sampling where we compute the cumulative sum of the weights and then use binary search to select the resampled point based on a uniformly distributed random number. Run time is O(n log n). You do not want to use this algorithm in ...
[ "def", "multinomial_resample", "(", "weights", ")", ":", "cumulative_sum", "=", "np", ".", "cumsum", "(", "weights", ")", "cumulative_sum", "[", "-", "1", "]", "=", "1.", "# avoid round-off errors: ensures sum is exactly one", "return", "np", ".", "searchsorted", ...
36.791667
0.002208
def _factors_for_expand_delta(expr): """Yield factors from expr, mixing sympy and QNET Auxiliary routine for :func:`_expand_delta`. """ from qnet.algebra.core.scalar_algebra import ScalarValue from qnet.algebra.core.abstract_quantum_algebra import ( ScalarTimesQuantumExpression) if isin...
[ "def", "_factors_for_expand_delta", "(", "expr", ")", ":", "from", "qnet", ".", "algebra", ".", "core", ".", "scalar_algebra", "import", "ScalarValue", "from", "qnet", ".", "algebra", ".", "core", ".", "abstract_quantum_algebra", "import", "(", "ScalarTimesQuantum...
37.470588
0.001531
def error(self, msg): """Override/enhance default error method to display tracebacks.""" print("***", msg, file=self.stdout) if not self.config.show_traceback_on_error: return etype, evalue, tb = sys.exc_info() if tb and tb.tb_frame.f_code.co_name == "default": ...
[ "def", "error", "(", "self", ",", "msg", ")", ":", "print", "(", "\"***\"", ",", "msg", ",", "file", "=", "self", ".", "stdout", ")", "if", "not", "self", ".", "config", ".", "show_traceback_on_error", ":", "return", "etype", ",", "evalue", ",", "tb"...
41.166667
0.001978
def _guess_sequence_type_from_string(self, seq): '''Return 'protein' if there is >10% amino acid residues in the (string) seq parameter, else 'nucleotide'. Raise Exception if a non-standard character is encountered''' # Define expected residues for each sequence type aa_chars = [...
[ "def", "_guess_sequence_type_from_string", "(", "self", ",", "seq", ")", ":", "# Define expected residues for each sequence type", "aa_chars", "=", "[", "'P'", ",", "'V'", ",", "'L'", ",", "'I'", ",", "'M'", ",", "'F'", ",", "'Y'", ",", "'W'", ",", "'H'", ",...
45.076923
0.019215
def convert_tscube_old(infile, outfile): """Convert between old and new TSCube formats.""" inhdulist = fits.open(infile) # If already in the new-style format just write and exit if 'DLOGLIKE_SCAN' in inhdulist['SCANDATA'].columns.names: if infile != outfile: inhdulist.writeto(outfil...
[ "def", "convert_tscube_old", "(", "infile", ",", "outfile", ")", ":", "inhdulist", "=", "fits", ".", "open", "(", "infile", ")", "# If already in the new-style format just write and exit", "if", "'DLOGLIKE_SCAN'", "in", "inhdulist", "[", "'SCANDATA'", "]", ".", "col...
41.352201
0.000149
def close(self): """Return this instance's socket to the connection pool. """ if not self.__closed: self.__closed = True self.pool.return_socket(self.sock) self.sock, self.pool = None, None
[ "def", "close", "(", "self", ")", ":", "if", "not", "self", ".", "__closed", ":", "self", ".", "__closed", "=", "True", "self", ".", "pool", ".", "return_socket", "(", "self", ".", "sock", ")", "self", ".", "sock", ",", "self", ".", "pool", "=", ...
34.714286
0.008032
def _prepare_record(self, group): """ compute record dtype and parents dict fro this group Parameters ---------- group : dict MDF group dict Returns ------- parents, dtypes : dict, numpy.dtype mapping of channels to records fields, record...
[ "def", "_prepare_record", "(", "self", ",", "group", ")", ":", "parents", ",", "dtypes", "=", "group", ".", "parents", ",", "group", ".", "types", "no_parent", "=", "None", ",", "None", "if", "parents", "is", "None", ":", "channel_group", "=", "group", ...
42.113924
0.001762
def _get_dynamic_data(self, validated_data): """ Returns dict of data, not declared in serializer fields. Should be called after self.is_valid(). """ result = {} for key in self.initial_data: if key not in validated_data: try: ...
[ "def", "_get_dynamic_data", "(", "self", ",", "validated_data", ")", ":", "result", "=", "{", "}", "for", "key", "in", "self", ".", "initial_data", ":", "if", "key", "not", "in", "validated_data", ":", "try", ":", "field", "=", "self", ".", "fields", "...
42.130435
0.002018
def binary(self): """Load and return the path to the native engine binary.""" lib_name = '{}.so'.format(NATIVE_ENGINE_MODULE) lib_path = os.path.join(safe_mkdtemp(), lib_name) try: with closing(pkg_resources.resource_stream(__name__, lib_name)) as input_fp: # NB: The header stripping code ...
[ "def", "binary", "(", "self", ")", ":", "lib_name", "=", "'{}.so'", ".", "format", "(", "NATIVE_ENGINE_MODULE", ")", "lib_path", "=", "os", ".", "path", ".", "join", "(", "safe_mkdtemp", "(", ")", ",", "lib_name", ")", "try", ":", "with", "closing", "(...
50.833333
0.008584
def _canon_decode_camera_info(self, camera_info_tag): """ Decode the variable length encoded camera info section. """ model = self.tags.get('Image Model', None) if not model: return model = str(model.values) camera_info_tags = None for (model_...
[ "def", "_canon_decode_camera_info", "(", "self", ",", "camera_info_tag", ")", ":", "model", "=", "self", ".", "tags", ".", "get", "(", "'Image Model'", ",", "None", ")", "if", "not", "model", ":", "return", "model", "=", "str", "(", "model", ".", "values...
38.488372
0.001768
def retrieve_metadata_server(metadata_key): """Retrieve the metadata key in the metadata server. See: https://cloud.google.com/compute/docs/storing-retrieving-metadata :type metadata_key: str :param metadata_key: Key of the metadata which will form the url. You can also supply...
[ "def", "retrieve_metadata_server", "(", "metadata_key", ")", ":", "url", "=", "METADATA_URL", "+", "metadata_key", "try", ":", "response", "=", "requests", ".", "get", "(", "url", ",", "headers", "=", "METADATA_HEADERS", ")", "if", "response", ".", "status_cod...
32.62963
0.001103
def _populate_calibration_data(self): """Populate calibration data. From datasheet Bosch BME280 Environmental sensor. """ calibration_t = [] calibration_p = [] calibration_h = [] raw_data = [] try: for i in range(0x88, 0x88 + 24): ...
[ "def", "_populate_calibration_data", "(", "self", ")", ":", "calibration_t", "=", "[", "]", "calibration_p", "=", "[", "]", "calibration_h", "=", "[", "]", "raw_data", "=", "[", "]", "try", ":", "for", "i", "in", "range", "(", "0x88", ",", "0x88", "+",...
41.754098
0.000767
def import_from_xls( filename_or_fobj, sheet_name=None, sheet_index=0, start_row=None, start_column=None, end_row=None, end_column=None, *args, **kwargs ): """Return a rows.Table created from imported XLS file.""" source = Source.from_file(filename_or_fobj, mode="rb", plugin...
[ "def", "import_from_xls", "(", "filename_or_fobj", ",", "sheet_name", "=", "None", ",", "sheet_index", "=", "0", ",", "start_row", "=", "None", ",", "start_column", "=", "None", ",", "end_row", "=", "None", ",", "end_column", "=", "None", ",", "*", "args",...
36.339623
0.001011
def current_vm(self): """current vm""" try: _, _, _, _, vm = self._callstack[-1] return vm except IndexError: return None
[ "def", "current_vm", "(", "self", ")", ":", "try", ":", "_", ",", "_", ",", "_", ",", "_", ",", "vm", "=", "self", ".", "_callstack", "[", "-", "1", "]", "return", "vm", "except", "IndexError", ":", "return", "None" ]
25
0.01105
def systemctl_reload(): ''' .. versionadded:: 0.15.0 Reloads systemctl, an action needed whenever unit files are updated. CLI Example: .. code-block:: bash salt '*' service.systemctl_reload ''' out = __salt__['cmd.run_all']( _systemctl_cmd('--system daemon-reload'), ...
[ "def", "systemctl_reload", "(", ")", ":", "out", "=", "__salt__", "[", "'cmd.run_all'", "]", "(", "_systemctl_cmd", "(", "'--system daemon-reload'", ")", ",", "python_shell", "=", "False", ",", "redirect_stderr", "=", "True", ")", "if", "out", "[", "'retcode'"...
24.545455
0.001783
def set_config_item(self, key, value): """ Set a config key to a provided value. The value can be a list for the keys supporting multiple values. """ try: old_value = self.get_config_item(key) except KeyError: old_value = None # Ge...
[ "def", "set_config_item", "(", "self", ",", "key", ",", "value", ")", ":", "try", ":", "old_value", "=", "self", ".", "get_config_item", "(", "key", ")", "except", "KeyError", ":", "old_value", "=", "None", "# Get everything to unicode with python2", "if", "is...
34.62
0.001124
def update_document_indicators(self, doc_id, citations, accesses): """ Atualiza os indicadores de acessos e citações de um determinado doc_id. exemplo de doc_id: S0021-25712009000400007-spa """ headers = {'content-type': 'application/json'} data = { ...
[ "def", "update_document_indicators", "(", "self", ",", "doc_id", ",", "citations", ",", "accesses", ")", ":", "headers", "=", "{", "'content-type'", ":", "'application/json'", "}", "data", "=", "{", "\"add\"", ":", "{", "\"doc\"", ":", "{", "\"id\"", ":", ...
26.555556
0.002018
def slice( self, serie_node, node, radius, small_radius, angle, start_angle, center, val, i, metadata ): """Draw a pie slice""" if angle == 2 * pi: angle = nearly_2pi if angle > 0: to = [ coord_abs_project(center, radius, start...
[ "def", "slice", "(", "self", ",", "serie_node", ",", "node", ",", "radius", ",", "small_radius", ",", "angle", ",", "start_angle", ",", "center", ",", "val", ",", "i", ",", "metadata", ")", ":", "if", "angle", "==", "2", "*", "pi", ":", "angle", "=...
35.973684
0.002137
def install(level=None, **kw): """ Enable colored terminal output for Python's :mod:`logging` module. :param level: The default logging level (an integer or a string with a level name, defaults to :data:`DEFAULT_LOG_LEVEL`). :param logger: The logger to which the stream handler should...
[ "def", "install", "(", "level", "=", "None", ",", "*", "*", "kw", ")", ":", "logger", "=", "kw", ".", "get", "(", "'logger'", ")", "or", "logging", ".", "getLogger", "(", ")", "reconfigure", "=", "kw", ".", "get", "(", "'reconfigure'", ",", "True",...
55.890476
0.000921
def clip_out_of_image(self): """ Clip off all parts from all bounding boxes that are outside of the image. Returns ------- imgaug.BoundingBoxesOnImage Bounding boxes, clipped to fall within the image dimensions. """ bbs_cut = [bb.clip_out_of_image(se...
[ "def", "clip_out_of_image", "(", "self", ")", ":", "bbs_cut", "=", "[", "bb", ".", "clip_out_of_image", "(", "self", ".", "shape", ")", "for", "bb", "in", "self", ".", "bounding_boxes", "if", "bb", ".", "is_partly_within_image", "(", "self", ".", "shape", ...
36.230769
0.008282
def _inner_convert_old_schema(self, node, depth): """ Internal recursion helper for L{_convert_old_schema}. @param node: A node in the associative list tree as described in _convert_old_schema. A two tuple of (name, parameter). @param depth: The depth that the node is at. Th...
[ "def", "_inner_convert_old_schema", "(", "self", ",", "node", ",", "depth", ")", ":", "name", ",", "parameter_description", "=", "node", "if", "not", "isinstance", "(", "parameter_description", ",", "list", ")", ":", "# This is a leaf, i.e., an actual L{Parameter} ins...
48.823529
0.001181
def hook_param(self, hook, p): """Parse a hook parameter""" hook.listparam.append(p.pair) return True
[ "def", "hook_param", "(", "self", ",", "hook", ",", "p", ")", ":", "hook", ".", "listparam", ".", "append", "(", "p", ".", "pair", ")", "return", "True" ]
27.5
0.00885
def visit_Call(self, node): """ Transform call site to have normal function call. Examples -------- For methods: >> a = [1, 2, 3] >> a.append(1) Becomes >> __list__.append(a, 1) For functions: >> __builtin__.dict.fromkeys([1, ...
[ "def", "visit_Call", "(", "self", ",", "node", ")", ":", "node", "=", "self", ".", "generic_visit", "(", "node", ")", "# Only attributes function can be Pythonic and should be normalized", "if", "isinstance", "(", "node", ".", "func", ",", "ast", ".", "Attribute",...
40.666667
0.000593
def _filtered_values(self, x: dict, feature_set: list=None): ''' :x: dict which contains feature names and values :return: pairs of values which shows number of feature makes filter function true or false ''' feature_set = feature_set or x n = sum(self.filter_func(x[i]) f...
[ "def", "_filtered_values", "(", "self", ",", "x", ":", "dict", ",", "feature_set", ":", "list", "=", "None", ")", ":", "feature_set", "=", "feature_set", "or", "x", "n", "=", "sum", "(", "self", ".", "filter_func", "(", "x", "[", "i", "]", ")", "fo...
48
0.012788
def estimategaps(args): """ %prog estimategaps input.bed Estimate sizes of inter-scaffold gaps. The AGP file generated by path() command has unknown gap sizes with a generic number of Ns (often 100 Ns). The AGP file `input.chr.agp` will be modified in-place. """ p = OptionParser(estimategap...
[ "def", "estimategaps", "(", "args", ")", ":", "p", "=", "OptionParser", "(", "estimategaps", ".", "__doc__", ")", "p", ".", "add_option", "(", "\"--minsize\"", ",", "default", "=", "100", ",", "type", "=", "\"int\"", ",", "help", "=", "\"Minimum gap size\"...
33.75
0.000847
def sbo(self, name): """Build all dependencies of a package """ if (self.meta.rsl_deps in ["on", "ON"] and "--resolve-off" not in self.flag): sys.setrecursionlimit(10000) dependencies = [] requires = SBoGrep(name).requires() if requ...
[ "def", "sbo", "(", "self", ",", "name", ")", ":", "if", "(", "self", ".", "meta", ".", "rsl_deps", "in", "[", "\"on\"", ",", "\"ON\"", "]", "and", "\"--resolve-off\"", "not", "in", "self", ".", "flag", ")", ":", "sys", ".", "setrecursionlimit", "(", ...
40.086957
0.002119
def xs(self, key, axis=1): """ Return slice of panel along selected axis. Parameters ---------- key : object Label axis : {'items', 'major', 'minor}, default 1/'major' Returns ------- y : ndim(self)-1 Notes ----- ...
[ "def", "xs", "(", "self", ",", "key", ",", "axis", "=", "1", ")", ":", "axis", "=", "self", ".", "_get_axis_number", "(", "axis", ")", "if", "axis", "==", "0", ":", "return", "self", "[", "key", "]", "self", ".", "_consolidate_inplace", "(", ")", ...
28.757576
0.002039
def predict(self, n_periods=10, exogenous=None, return_conf_int=False, alpha=0.05): """Forecast future values Generate predictions (forecasts) ``n_periods`` in the future. Note that if ``exogenous`` variables were used in the model fit, they will be expected for the pred...
[ "def", "predict", "(", "self", ",", "n_periods", "=", "10", ",", "exogenous", "=", "None", ",", "return_conf_int", "=", "False", ",", "alpha", "=", "0.05", ")", ":", "check_is_fitted", "(", "self", ",", "'arima_res_'", ")", "if", "not", "isinstance", "("...
46.6
0.000901
def rotate(self, l, u): """rotate l radians around axis u""" cl = math.cos(l) sl = math.sin(l) x = (cl + u.x * u.x * (1 - cl)) * self.x + (u.x * u.y * (1 - cl) - u.z * sl) * self.y + ( u.x * u.z * (1 - cl) + u.y * sl) * self.z y = (u.y * u.x * (1 - cl) + u.z * sl) * self....
[ "def", "rotate", "(", "self", ",", "l", ",", "u", ")", ":", "cl", "=", "math", ".", "cos", "(", "l", ")", "sl", "=", "math", ".", "sin", "(", "l", ")", "x", "=", "(", "cl", "+", "u", ".", "x", "*", "u", ".", "x", "*", "(", "1", "-", ...
51
0.014446
def remove(path, force=False): ''' Remove the named file or directory Args: path (str): The path to the file or directory to remove. force (bool): Remove even if marked Read-Only. Default is False Returns: bool: True if successful, False if unsuccessful CLI Example: ....
[ "def", "remove", "(", "path", ",", "force", "=", "False", ")", ":", "# This must be a recursive function in windows to properly deal with", "# Symlinks. The shutil.rmtree function will remove the contents of", "# the Symlink source in windows.", "path", "=", "os", ".", "path", "....
32.016667
0.00101
def _upgrade_broker(broker): """ Extract the poller state from Broker and replace it with the industrial strength poller for this OS. Must run on the Broker thread. """ # This function is deadly! The act of calling start_receive() generates log # messages which must be silenced as the upgrade pr...
[ "def", "_upgrade_broker", "(", "broker", ")", ":", "# This function is deadly! The act of calling start_receive() generates log", "# messages which must be silenced as the upgrade progresses, otherwise the", "# poller state will change as it is copied, resulting in write fds that are", "# lost. (D...
40.733333
0.000799
def closest(self, tag): """Match closest ancestor.""" return CSSMatch(self.selectors, tag, self.namespaces, self.flags).closest()
[ "def", "closest", "(", "self", ",", "tag", ")", ":", "return", "CSSMatch", "(", "self", ".", "selectors", ",", "tag", ",", "self", ".", "namespaces", ",", "self", ".", "flags", ")", ".", "closest", "(", ")" ]
35.75
0.020548
def create_frame(command): """Create and return empty Frame from Command.""" # pylint: disable=too-many-branches,too-many-return-statements if command == Command.GW_ERROR_NTF: return FrameErrorNotification() if command == Command.GW_COMMAND_SEND_REQ: return FrameCommandSendRequest() ...
[ "def", "create_frame", "(", "command", ")", ":", "# pylint: disable=too-many-branches,too-many-return-statements", "if", "command", "==", "Command", ".", "GW_ERROR_NTF", ":", "return", "FrameErrorNotification", "(", ")", "if", "command", "==", "Command", ".", "GW_COMMAN...
41.828283
0.000236
def build_logger( name=os.getenv( "LOG_NAME", "client"), config="logging.json", log_level=logging.INFO, log_config_path="{}/logging.json".format( os.getenv( "LOG_CFG", os.path.dirname(os.path.realpath(__file__))))): """build_logger :param name: na...
[ "def", "build_logger", "(", "name", "=", "os", ".", "getenv", "(", "\"LOG_NAME\"", ",", "\"client\"", ")", ",", "config", "=", "\"logging.json\"", ",", "log_level", "=", "logging", ".", "INFO", ",", "log_config_path", "=", "\"{}/logging.json\"", ".", "format",...
29.1875
0.001036
def get_config_set(self, section, option): """Returns a set with each value per config file in it. """ values = set() for cp, filename, fp in self.layers: filename = filename # pylint fp = fp # pylint if cp.has_option(section, option): values.add(cp.get(section, option)) return values
[ "def", "get_config_set", "(", "self", ",", "section", ",", "option", ")", ":", "values", "=", "set", "(", ")", "for", "cp", ",", "filename", ",", "fp", "in", "self", ".", "layers", ":", "filename", "=", "filename", "# pylint", "fp", "=", "fp", "# pyl...
29.9
0.042208
def validator_for(schema, default=_LATEST_VERSION): """ Retrieve the validator class appropriate for validating the given schema. Uses the :validator:`$schema` property that should be present in the given schema to look up the appropriate validator class. Arguments: schema (collections.Ma...
[ "def", "validator_for", "(", "schema", ",", "default", "=", "_LATEST_VERSION", ")", ":", "if", "schema", "is", "True", "or", "schema", "is", "False", "or", "u\"$schema\"", "not", "in", "schema", ":", "return", "default", "if", "schema", "[", "u\"$schema\"", ...
31.264706
0.000912
def init_logging(config): """Initialize base logger named 'wsgidav'. The base logger is filtered by the `verbose` configuration option. Log entries will have a time stamp and thread id. :Parameters: verbose : int Verbosity configuration (0..5) enable_loggers : string list ...
[ "def", "init_logging", "(", "config", ")", ":", "verbose", "=", "config", ".", "get", "(", "\"verbose\"", ",", "3", ")", "enable_loggers", "=", "config", ".", "get", "(", "\"enable_loggers\"", ",", "[", "]", ")", "if", "enable_loggers", "is", "None", ":"...
39.186441
0.00232
def mcc_t(self,ifig=None,lims=[0,15,0,25],label=None,colour=None, mask=False,s2ms=False,dashes=None): """ Plot mass of [oclark01@scandium 15M_led_f_print_nets]$ cp ../15M_led_f_ppcno/ective core as a function of time. Parameters ---------- ifig : integer or string ...
[ "def", "mcc_t", "(", "self", ",", "ifig", "=", "None", ",", "lims", "=", "[", "0", ",", "15", ",", "0", ",", "25", "]", ",", "label", "=", "None", ",", "colour", "=", "None", ",", "mask", "=", "False", ",", "s2ms", "=", "False", ",", "dashes"...
29.67619
0.018634
def _format_text(self, title, text, color, ellide=False): """ Create HTML template for calltips and tooltips. This will display title and text as separate sections and add `...` if `ellide` is True and the text is too long. """ template = ''' <div sty...
[ "def", "_format_text", "(", "self", ",", "title", ",", "text", ",", "color", ",", "ellide", "=", "False", ")", ":", "template", "=", "'''\r\n <div style=\\'font-family: \"{font_family}\";\r\n font-size: {title_size}pt;\r\n ...
30.803922
0.001234
def fix_code(source, options=None, encoding=None, apply_config=False): """Return fixed source code. "encoding" will be used to decode "source" if it is a byte string. """ options = _get_options(options, apply_config) if not isinstance(source, unicode): source = source.decode(encoding or g...
[ "def", "fix_code", "(", "source", ",", "options", "=", "None", ",", "encoding", "=", "None", ",", "apply_config", "=", "False", ")", ":", "options", "=", "_get_options", "(", "options", ",", "apply_config", ")", "if", "not", "isinstance", "(", "source", ...
31.384615
0.002381
def changes_str2(self, tab_string=' '): ''' Returns a string in a more compact format describing the changes. The output better alligns with the one in recursive_diff. ''' changes = [] for item in self._get_recursive_difference(type='intersect'): if item.dif...
[ "def", "changes_str2", "(", "self", ",", "tab_string", "=", "' '", ")", ":", "changes", "=", "[", "]", "for", "item", "in", "self", ".", "_get_recursive_difference", "(", "type", "=", "'intersect'", ")", ":", "if", "item", ".", "diffs", ":", "changes", ...
50.6
0.001552
def run(self): ''' Set up and run ''' self._setup_kafka() self._load_plugins() self._setup_stats() self._main_loop()
[ "def", "run", "(", "self", ")", ":", "self", ".", "_setup_kafka", "(", ")", "self", ".", "_load_plugins", "(", ")", "self", ".", "_setup_stats", "(", ")", "self", ".", "_main_loop", "(", ")" ]
20.625
0.011628
def logout(self): """ Logout cookie based user. """ resp = super(CookieSession, self).request('DELETE', self._session_url) resp.raise_for_status()
[ "def", "logout", "(", "self", ")", ":", "resp", "=", "super", "(", "CookieSession", ",", "self", ")", ".", "request", "(", "'DELETE'", ",", "self", ".", "_session_url", ")", "resp", ".", "raise_for_status", "(", ")" ]
30.166667
0.010753
def push_image(registry, image): # type: (str, Dict[str, Any]) -> None """ Push the given image to selected repository. Args: registry (str): The name of the registry we're pushing to. This is the address of the repository without the protocol specification (no http(s)://) ...
[ "def", "push_image", "(", "registry", ",", "image", ")", ":", "# type: (str, Dict[str, Any]) -> None", "values", "=", "{", "'registry'", ":", "registry", ",", "'image'", ":", "image", "[", "'name'", "]", ",", "}", "log", ".", "info", "(", "\"Pushing <33>{regis...
36.842105
0.001393
def inject(*args, **kwargs): """ Mark a class or function for injection, meaning that a DI container knows that it should inject dependencies into it. Normally you won't need this as the injector will inject the required arguments anyway, but it can be used to inject properties into a class wit...
[ "def", "inject", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "def", "wrapper", "(", "obj", ")", ":", "if", "inspect", ".", "isclass", "(", "obj", ")", "or", "callable", "(", "obj", ")", ":", "_inject_object", "(", "obj", ",", "*", "args"...
38
0.001222
def phases_with(self, **kwargs) -> [PhaseOutput]: """ Filters phases. If no arguments are passed all phases are returned. Arguments must be key value pairs, with phase, data or pipeline as the key. Parameters ---------- kwargs Filters, e.g. pipeline=pipeline1...
[ "def", "phases_with", "(", "self", ",", "*", "*", "kwargs", ")", "->", "[", "PhaseOutput", "]", ":", "return", "[", "phase", "for", "phase", "in", "self", ".", "phases", "if", "all", "(", "[", "getattr", "(", "phase", ",", "key", ")", "==", "value"...
38.083333
0.008547
def node(self,port, hub_address=("localhost", 4444)): ''' java -jar selenium-server.jar -role node -port 5555 -hub http://127.0.0.1:4444/grid/register/ @param port: listen port of selenium node @param hub_address: hub address which node will connect to ''' self._ip, self._...
[ "def", "node", "(", "self", ",", "port", ",", "hub_address", "=", "(", "\"localhost\"", ",", "4444", ")", ")", ":", "self", ".", "_ip", ",", "self", ".", "_port", "=", "hub_address", "self", ".", "command", "=", "[", "self", ".", "_conf", "[", "\"j...
67.75
0.014572
def print_cli(msg, retries=10, step=0.01): ''' Wrapper around print() that suppresses tracebacks on broken pipes (i.e. when salt output is piped to less and less is stopped prematurely). ''' while retries: try: try: print(msg) except UnicodeEncodeError...
[ "def", "print_cli", "(", "msg", ",", "retries", "=", "10", ",", "step", "=", "0.01", ")", ":", "while", "retries", ":", "try", ":", "try", ":", "print", "(", "msg", ")", "except", "UnicodeEncodeError", ":", "print", "(", "msg", ".", "encode", "(", ...
31.56
0.00123
def verify_file(fp, password): 'Returns whether a scrypt encrypted file is valid.' sf = ScryptFile(fp = fp, password = password) for line in sf: pass sf.close() return sf.valid
[ "def", "verify_file", "(", "fp", ",", "password", ")", ":", "sf", "=", "ScryptFile", "(", "fp", "=", "fp", ",", "password", "=", "password", ")", "for", "line", "in", "sf", ":", "pass", "sf", ".", "close", "(", ")", "return", "sf", ".", "valid" ]
30.142857
0.032258
def match_file(pattern, filename): ''' The function will match a pattern in a file and return a rex object, which will have all the matches found in the file. ''' # Validate user data. if pattern is None: return None if os.stat(filename).st_size == 0: return None rexo...
[ "def", "match_file", "(", "pattern", ",", "filename", ")", ":", "# Validate user data.", "if", "pattern", "is", "None", ":", "return", "None", "if", "os", ".", "stat", "(", "filename", ")", ".", "st_size", "==", "0", ":", "return", "None", "rexobj", "=",...
21.555556
0.002466
def execute_fields_serially( self, parent_type: GraphQLObjectType, source_value: Any, path: Optional[ResponsePath], fields: Dict[str, List[FieldNode]], ) -> AwaitableOrValue[Dict[str, Any]]: """Execute the given fields serially. Implements the "Evaluating sel...
[ "def", "execute_fields_serially", "(", "self", ",", "parent_type", ":", "GraphQLObjectType", ",", "source_value", ":", "Any", ",", "path", ":", "Optional", "[", "ResponsePath", "]", ",", "fields", ":", "Dict", "[", "str", ",", "List", "[", "FieldNode", "]", ...
38.959184
0.002044
def new(cls, script, commit, params, campaign_dir, overwrite=False): """ Initialize a new class instance with a set configuration and filename. The created database has the same name of the campaign directory. Args: script (str): the ns-3 name of the script that will be use...
[ "def", "new", "(", "cls", ",", "script", ",", "commit", ",", "params", ",", "campaign_dir", ",", "overwrite", "=", "False", ")", ":", "# We only accept absolute paths", "if", "not", "Path", "(", "campaign_dir", ")", ".", "is_absolute", "(", ")", ":", "rais...
42.614035
0.001207
def add_params(endpoint, params): """ Combine query endpoint and params. Example:: >>> add_params("https://www.google.com/search", {"q": "iphone"}) https://www.google.com/search?q=iphone """ p = PreparedRequest() p.prepare(url=endpoint, params=params) if PY2: # pragma: no ...
[ "def", "add_params", "(", "endpoint", ",", "params", ")", ":", "p", "=", "PreparedRequest", "(", ")", "p", ".", "prepare", "(", "url", "=", "endpoint", ",", "params", "=", "params", ")", "if", "PY2", ":", "# pragma: no cover", "return", "unicode", "(", ...
26.133333
0.002463
def trace_plot(precisions, path, n_edges=20, ground_truth=None, edges=[]): """Plot the change in precision (or covariance) coefficients as a function of changing lambda and l1-norm. Always ignores diagonals. Parameters ----------- precisions : array of len(path) 2D ndarray, shape (n_features, n_fe...
[ "def", "trace_plot", "(", "precisions", ",", "path", ",", "n_edges", "=", "20", ",", "ground_truth", "=", "None", ",", "edges", "=", "[", "]", ")", ":", "_check_path", "(", "path", ")", "assert", "len", "(", "path", ")", "==", "len", "(", "precisions...
35.438095
0.001046
def p_event_statement(self, p): 'event_statement : senslist SEMICOLON' p[0] = EventStatement(p[1], lineno=p.lineno(1)) p.set_lineno(0, p.lineno(1))
[ "def", "p_event_statement", "(", "self", ",", "p", ")", ":", "p", "[", "0", "]", "=", "EventStatement", "(", "p", "[", "1", "]", ",", "lineno", "=", "p", ".", "lineno", "(", "1", ")", ")", "p", ".", "set_lineno", "(", "0", ",", "p", ".", "lin...
42
0.011696
def do_move(self, dt, buttons): """ Updates velocity and returns Rects for start/finish positions """ assert isinstance(dt, int) or isinstance(dt, float) assert isinstance(buttons, dict) newVel = self.velocity # Redirect existing vel to new direction. nv...
[ "def", "do_move", "(", "self", ",", "dt", ",", "buttons", ")", ":", "assert", "isinstance", "(", "dt", ",", "int", ")", "or", "isinstance", "(", "dt", ",", "float", ")", "assert", "isinstance", "(", "buttons", ",", "dict", ")", "newVel", "=", "self",...
28.724138
0.002323
def load_identity(config = Config()): """Load the default identity from the configuration. If there is no default identity, a KeyError is raised. """ return Identity(name = config.get('user', 'name'), email_ = config.get('user', 'email'), **config.get_section...
[ "def", "load_identity", "(", "config", "=", "Config", "(", ")", ")", ":", "return", "Identity", "(", "name", "=", "config", ".", "get", "(", "'user'", ",", "'name'", ")", ",", "email_", "=", "config", ".", "get", "(", "'user'", ",", "'email'", ")", ...
40.25
0.024316
def fit(self, Z, **fit_params): """TODO: rewrite docstring Fit all transformers using X. Parameters ---------- X : array-like or sparse matrix, shape (n_samples, n_features) Input data, used to fit transformers. """ fit_params_steps = dict((step, {}) ...
[ "def", "fit", "(", "self", ",", "Z", ",", "*", "*", "fit_params", ")", ":", "fit_params_steps", "=", "dict", "(", "(", "step", ",", "{", "}", ")", "for", "step", ",", "_", "in", "self", ".", "transformer_list", ")", "for", "pname", ",", "pval", "...
39.95
0.002445
def SheetList(name, src, **kwargs): 'Creates a Sheet from a list of homogenous dicts or namedtuples.' if not src: status('no content in ' + name) return if isinstance(src[0], dict): return ListOfDictSheet(name, source=src, **kwargs) elif isinstance(src[0], tuple): if ge...
[ "def", "SheetList", "(", "name", ",", "src", ",", "*", "*", "kwargs", ")", ":", "if", "not", "src", ":", "status", "(", "'no content in '", "+", "name", ")", "return", "if", "isinstance", "(", "src", "[", "0", "]", ",", "dict", ")", ":", "return", ...
33.866667
0.001916
def string_list_to_array(l): """ Turns a Python unicode string list into a Java String array. :param l: the string list :type: list :rtype: java string array :return: JB_Object """ result = javabridge.get_env().make_object_array(len(l), javabridge.get_env().find_class("java/lang/String"...
[ "def", "string_list_to_array", "(", "l", ")", ":", "result", "=", "javabridge", ".", "get_env", "(", ")", ".", "make_object_array", "(", "len", "(", "l", ")", ",", "javabridge", ".", "get_env", "(", ")", ".", "find_class", "(", "\"java/lang/String\"", ")",...
35.692308
0.008403
def addgroup(name, group): ''' Add user to a group Args: name (str): The user name to add to the group group (str): The name of the group to which to add the user Returns: bool: True if successful, otherwise False CLI Example: .. code-block:: bash salt '*' u...
[ "def", "addgroup", "(", "name", ",", "group", ")", ":", "if", "six", ".", "PY2", ":", "name", "=", "_to_unicode", "(", "name", ")", "group", "=", "_to_unicode", "(", "group", ")", "name", "=", "_cmd_quote", "(", "name", ")", "group", "=", "_cmd_quote...
21.8
0.001255
def fix_journal_name(journal, knowledge_base): """Convert journal name to Inspire's short form.""" if not journal: return '', '' if not knowledge_base: return journal, '' if len(journal) < 2: return journal, '' volume = '' if (journal[-1] <= 'Z' and journal[-1] >= 'A') \ ...
[ "def", "fix_journal_name", "(", "journal", ",", "knowledge_base", ")", ":", "if", "not", "journal", ":", "return", "''", ",", "''", "if", "not", "knowledge_base", ":", "return", "journal", ",", "''", "if", "len", "(", "journal", ")", "<", "2", ":", "re...
35.259259
0.001022
def set_default(cls, name): """Replaces the current application default depot""" if name not in cls._depots: raise RuntimeError('%s depot has not been configured' % (name,)) cls._default_depot = name
[ "def", "set_default", "(", "cls", ",", "name", ")", ":", "if", "name", "not", "in", "cls", ".", "_depots", ":", "raise", "RuntimeError", "(", "'%s depot has not been configured'", "%", "(", "name", ",", ")", ")", "cls", ".", "_default_depot", "=", "name" ]
46.2
0.008511
def check_auth(self, username, password): ''' This function is called to check if a username password combination is valid. ''' return username == self.queryname and password == self.querypw
[ "def", "check_auth", "(", "self", ",", "username", ",", "password", ")", ":", "return", "username", "==", "self", ".", "queryname", "and", "password", "==", "self", ".", "querypw" ]
53.75
0.009174
def copy(self, origTypeID, newTypeID): """copy(string, string) -> None Duplicates the vType with ID origTypeID. The newly created vType is assigned the ID newTypeID """ self._connection._sendStringCmd( tc.CMD_SET_VEHICLETYPE_VARIABLE, tc.COPY, origTypeID, newTypeID)
[ "def", "copy", "(", "self", ",", "origTypeID", ",", "newTypeID", ")", ":", "self", ".", "_connection", ".", "_sendStringCmd", "(", "tc", ".", "CMD_SET_VEHICLETYPE_VARIABLE", ",", "tc", ".", "COPY", ",", "origTypeID", ",", "newTypeID", ")" ]
43.571429
0.009646