text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
async def create( cls, architecture: str, mac_addresses: typing.Sequence[str], power_type: str, power_parameters: typing.Mapping[str, typing.Any] = None, *, subarchitecture: str = None, min_hwe_kernel: str = None, hostname: str = None, domain: typing.Union[int...
[ "async", "def", "create", "(", "cls", ",", "architecture", ":", "str", ",", "mac_addresses", ":", "typing", ".", "Sequence", "[", "str", "]", ",", "power_type", ":", "str", ",", "power_parameters", ":", "typing", ".", "Mapping", "[", "str", ",", "typing"...
43.886364
0.001013
def declare_local_operator(self, type, raw_model=None): ''' This function is used to declare new local operator. ''' onnx_name = self.get_unique_operator_name(str(type)) operator = Operator(onnx_name, self.name, type, raw_model, self.target_opset) self.operators[onnx_name...
[ "def", "declare_local_operator", "(", "self", ",", "type", ",", "raw_model", "=", "None", ")", ":", "onnx_name", "=", "self", ".", "get_unique_operator_name", "(", "str", "(", "type", ")", ")", "operator", "=", "Operator", "(", "onnx_name", ",", "self", "....
43.625
0.008427
def remove_short_sci_segs(self, minSegLength): """ Function to remove all science segments shorter than a specific length. Also updates the file on disk to remove these segments. Parameters ----------- minSegLength : int Maximum length of science segm...
[ "def", "remove_short_sci_segs", "(", "self", ",", "minSegLength", ")", ":", "newsegment_list", "=", "segments", ".", "segmentlist", "(", ")", "for", "key", ",", "seglist", "in", "self", ".", "segment_dict", ".", "items", "(", ")", ":", "newsegment_list", "="...
38.285714
0.002427
def list_bindings(site): ''' Get all configured IIS bindings for the specified site. Args: site (str): The name if the IIS Site Returns: dict: A dictionary of the binding names and properties. CLI Example: .. code-block:: bash salt '*' win_iis.list_bindings site ...
[ "def", "list_bindings", "(", "site", ")", ":", "ret", "=", "dict", "(", ")", "sites", "=", "list_sites", "(", ")", "if", "site", "not", "in", "sites", ":", "log", ".", "warning", "(", "'Site not found: %s'", ",", "site", ")", "return", "ret", "ret", ...
19.275862
0.001704
def get_account_invitation(self, account_id, invitation_id, **kwargs): # noqa: E501 """Details of a user invitation. # noqa: E501 An endpoint for retrieving the details of an active user invitation sent for a new or an existing user to join the account. **Example usage:** `curl https://api.us-east-...
[ "def", "get_account_invitation", "(", "self", ",", "account_id", ",", "invitation_id", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'asynchronous'", ")", ":", ...
62.227273
0.001439
def _get_scripts(self, scripts_path_rel, files_deployment, script_type, project_path): """ Gets scripts from specified folders """ scripts_dict = {} if scripts_path_rel: self._logger.debug('Getting scripts with {0} definitions'.format(script_type)) scrip...
[ "def", "_get_scripts", "(", "self", ",", "scripts_path_rel", ",", "files_deployment", ",", "script_type", ",", "project_path", ")", ":", "scripts_dict", "=", "{", "}", "if", "scripts_path_rel", ":", "self", ".", "_logger", ".", "debug", "(", "'Getting scripts wi...
46.647059
0.009889
def __attr_name(self, name): """ Return suitable and valid attribute name. This method replaces dash char to underscore. If name is invalid ValueError exception is raised :param name: cookie attribute name :return: str """ if name not in self.cookie_attr_value_compliance.keys(): suggested_name = name.re...
[ "def", "__attr_name", "(", "self", ",", "name", ")", ":", "if", "name", "not", "in", "self", ".", "cookie_attr_value_compliance", ".", "keys", "(", ")", ":", "suggested_name", "=", "name", ".", "replace", "(", "'_'", ",", "'-'", ")", ".", "lower", "(",...
38.461538
0.027344
def ssh_configured(name, service_running, ssh_key=None, ssh_key_file=None, service_policy=None, service_restart=False, certificate_verify=False): ''' Manage the SSH configuration for a host includin...
[ "def", "ssh_configured", "(", "name", ",", "service_running", ",", "ssh_key", "=", "None", ",", "ssh_key_file", "=", "None", ",", "service_policy", "=", "None", ",", "service_restart", "=", "False", ",", "certificate_verify", "=", "False", ")", ":", "ret", "...
39.858586
0.002225
def on(self, handler): """Attach a handler (any Python callable) for the event.""" if not hasattr(handler, '__call__'): raise TypeError('handler is not a callable object.') self.handlers.add(handler)
[ "def", "on", "(", "self", ",", "handler", ")", ":", "if", "not", "hasattr", "(", "handler", ",", "'__call__'", ")", ":", "raise", "TypeError", "(", "'handler is not a callable object.'", ")", "self", ".", "handlers", ".", "add", "(", "handler", ")" ]
46.2
0.008511
def __get_variance_increase_distance(self, entry): """! @brief Calculates variance increase distance between current and specified clusters. @param[in] entry (cfentry): Clustering feature to which distance should be obtained. @return (double) Variance increase dis...
[ "def", "__get_variance_increase_distance", "(", "self", ",", "entry", ")", ":", "linear_part_12", "=", "list_math_addition", "(", "self", ".", "linear_sum", ",", "entry", ".", "linear_sum", ")", "variance_part_first", "=", "(", "self", ".", "square_sum", "+", "e...
61.217391
0.01958
def _gen_ipython_string(func, args, defaults, original_doc): """Provides auto-complete hint to ipython. If the first line in a docstring is fn(arg1=, arg2=) then they are added to auto-complete. This cannot be called on an instance method. Args: func: The function that will be modified. args: The arg...
[ "def", "_gen_ipython_string", "(", "func", ",", "args", ",", "defaults", ",", "original_doc", ")", ":", "magic_string", "=", "'%s('", "%", "func", ".", "__name__", "if", "defaults", ":", "default_offset", "=", "len", "(", "args", ")", "-", "len", "(", "d...
33.064516
0.011374
def get(self, key): """ Get data associated with provided key. """ return self._object_class(json.loads(self._db[key]))
[ "def", "get", "(", "self", ",", "key", ")", ":", "return", "self", ".", "_object_class", "(", "json", ".", "loads", "(", "self", ".", "_db", "[", "key", "]", ")", ")" ]
35
0.013986
def parse_dataset_key(dataset_key): """Parse a dataset URL or path and return the owner and the dataset id :param dataset_key: Dataset key (in the form of owner/id) or dataset URL :type dataset_key: str :returns: User name of the dataset owner and ID of the dataset :rtype: dataset_owner, dataset_id...
[ "def", "parse_dataset_key", "(", "dataset_key", ")", ":", "match", "=", "re", ".", "match", "(", "DATASET_KEY_PATTERN", ",", "dataset_key", ")", "if", "not", "match", ":", "raise", "ValueError", "(", "'Invalid dataset key. Key must include user and '", "'dataset names...
43.304348
0.000982
def save_code(self, authorization_code): """ Creates a new entry of an auth code in the database. :param authorization_code: An instance of :class:`oauth2.datatype.AuthorizationCode`. :return: `True` if everything went fine. """ auth_c...
[ "def", "save_code", "(", "self", ",", "authorization_code", ")", ":", "auth_code_id", "=", "self", ".", "execute", "(", "self", ".", "create_auth_code_query", ",", "authorization_code", ".", "client_id", ",", "authorization_code", ".", "code", ",", "authorization_...
41.608696
0.002043
def parse(json, query_path, expected_vars=NO_VARS): """ INTENDED TO TREAT JSON AS A STREAM; USING MINIMAL MEMORY WHILE IT ITERATES THROUGH THE STRUCTURE. ASSUMING THE JSON IS LARGE, AND HAS A HIGH LEVEL ARRAY STRUCTURE, IT WILL yield EACH OBJECT IN THAT ARRAY. NESTED ARRAYS ARE HANDLED BY REPEATIN...
[ "def", "parse", "(", "json", ",", "query_path", ",", "expected_vars", "=", "NO_VARS", ")", ":", "if", "hasattr", "(", "json", ",", "\"read\"", ")", ":", "# ASSUME IT IS A STREAM", "temp", "=", "json", "def", "get_more", "(", ")", ":", "return", "temp", "...
36.552901
0.001545
def bbox(self): "Return the envelope as a Bound Box string compatible with (bb) params" return ",".join(str(attr) for attr in (self.xmin, self.ymin, self.xmax, self.ymax))
[ "def", "bbox", "(", "self", ")", ":", "return", "\",\"", ".", "join", "(", "str", "(", "attr", ")", "for", "attr", "in", "(", "self", ".", "xmin", ",", "self", ".", "ymin", ",", "self", ".", "xmax", ",", "self", ".", "ymax", ")", ")" ]
53.25
0.018519
def _lookup_proxmox_task(upid): ''' Retrieve the (latest) logs and retrieve the status for a UPID. This can be used to verify whether a task has completed. ''' log.debug('Getting creation status for upid: %s', upid) tasks = query('get', 'cluster/tasks') if tasks: for task in tasks: ...
[ "def", "_lookup_proxmox_task", "(", "upid", ")", ":", "log", ".", "debug", "(", "'Getting creation status for upid: %s'", ",", "upid", ")", "tasks", "=", "query", "(", "'get'", ",", "'cluster/tasks'", ")", "if", "tasks", ":", "for", "task", "in", "tasks", ":...
29.533333
0.002188
def api_get(uri, key=None): """ Simple API endpoint get, return only the keys we care about """ response = get_json(uri) if response: if type(response) == list: r = response[0] elif type(response) == dict: r = response if type(r) == dict: ...
[ "def", "api_get", "(", "uri", ",", "key", "=", "None", ")", ":", "response", "=", "get_json", "(", "uri", ")", "if", "response", ":", "if", "type", "(", "response", ")", "==", "list", ":", "r", "=", "response", "[", "0", "]", "elif", "type", "(",...
25.888889
0.00207
def write(self, data): """Write data to the GoogleCloudStorage file. Args: data: string containing the data to be written. """ start_time = time.time() self._get_write_buffer().write(data) ctx = context.get() operation.counters.Increment(COUNTER_IO_WRITE_BYTES, len(data))(ctx) ope...
[ "def", "write", "(", "self", ",", "data", ")", ":", "start_time", "=", "time", ".", "time", "(", ")", "self", ".", "_get_write_buffer", "(", ")", ".", "write", "(", "data", ")", "ctx", "=", "context", ".", "get", "(", ")", "operation", ".", "counte...
34.25
0.00237
def aggregate(self, pipeline, **kwargs): """Execute an aggregation pipeline on this collection. The aggregation can be run on a secondary if the client is connected to a replica set and its ``read_preference`` is not :attr:`PRIMARY`. :Parameters: - `pipeline`: a single comman...
[ "def", "aggregate", "(", "self", ",", "pipeline", ",", "*", "*", "kwargs", ")", ":", "cursor_class", "=", "create_class_with_framework", "(", "AgnosticLatentCommandCursor", ",", "self", ".", "_framework", ",", "self", ".", "__module__", ")", "# Latent cursor that ...
38.225806
0.000823
def attrs(self): """ Returns a dictionary of the archive's attributes. """ return dict((k, v) for k, v in iteritems(self.__dict__) if k is not "sdk")
[ "def", "attrs", "(", "self", ")", ":", "return", "dict", "(", "(", "k", ",", "v", ")", "for", "k", ",", "v", "in", "iteritems", "(", "self", ".", "__dict__", ")", "if", "k", "is", "not", "\"sdk\"", ")" ]
35.4
0.016575
def _set_options(self, qobj_config=None, backend_options=None): """Set the backend options for all experiments in a qobj""" # Reset default options self._initial_unitary = self.DEFAULT_OPTIONS["initial_unitary"] self._chop_threshold = self.DEFAULT_OPTIONS["chop_threshold"] if bac...
[ "def", "_set_options", "(", "self", ",", "qobj_config", "=", "None", ",", "backend_options", "=", "None", ")", ":", "# Reset default options", "self", ".", "_initial_unitary", "=", "self", ".", "DEFAULT_OPTIONS", "[", "\"initial_unitary\"", "]", "self", ".", "_c...
51.914286
0.001621
def ok(self) -> Option[T]: """ Converts from :class:`Result` [T, E] to :class:`option.option_.Option` [T]. Returns: :class:`Option` containing the success value if `self` is :meth:`Result.Ok`, otherwise :data:`option.option_.NONE`. Examples: >>> Ok(1...
[ "def", "ok", "(", "self", ")", "->", "Option", "[", "T", "]", ":", "return", "Option", ".", "Some", "(", "cast", "(", "T", ",", "self", ".", "_val", ")", ")", "if", "self", ".", "_is_ok", "else", "cast", "(", "Option", "[", "T", "]", ",", "NO...
31.866667
0.00813
def setParent(self, other): """ Sets the parent for this layer to the inputed layer. :param other | <XNodeLayer> || None :return <bool> changed """ if self._parent == other: return False # remove this layer from its ...
[ "def", "setParent", "(", "self", ",", "other", ")", ":", "if", "self", ".", "_parent", "==", "other", ":", "return", "False", "# remove this layer from its parent", "if", "self", ".", "_parent", "and", "self", "in", "self", ".", "_parent", ".", "_children", ...
28.25
0.014265
def _translate_cond(self, c): #pylint:disable=no-self-use """ Checks whether this condition can be supported by FastMemory." """ if isinstance(c, claripy.ast.Base) and not c.singlevalued: raise SimFastMemoryError("size not supported") if c is None: return ...
[ "def", "_translate_cond", "(", "self", ",", "c", ")", ":", "#pylint:disable=no-self-use", "if", "isinstance", "(", "c", ",", "claripy", ".", "ast", ".", "Base", ")", "and", "not", "c", ".", "singlevalued", ":", "raise", "SimFastMemoryError", "(", "\"size not...
38.5
0.010152
def import_dashboards(session, data_stream, import_time=None): """Imports dashboards from a stream to databases""" current_tt = int(time.time()) import_time = current_tt if import_time is None else import_time data = json.loads(data_stream.read(), object_hook=decode_dashboards) # TODO: import DRUID ...
[ "def", "import_dashboards", "(", "session", ",", "data_stream", ",", "import_time", "=", "None", ")", ":", "current_tt", "=", "int", "(", "time", ".", "time", "(", ")", ")", "import_time", "=", "current_tt", "if", "import_time", "is", "None", "else", "impo...
44.692308
0.001686
def create_network(name, skip_translate=None, ignore_collisions=False, validate_ip_addrs=True, client_timeout=salt.utils.docker.CLIENT_TIMEOUT, **kwargs): ''' .. versionchanged:: 2018.3.0 Support added for net...
[ "def", "create_network", "(", "name", ",", "skip_translate", "=", "None", ",", "ignore_collisions", "=", "False", ",", "validate_ip_addrs", "=", "True", ",", "client_timeout", "=", "salt", ".", "utils", ".", "docker", ".", "CLIENT_TIMEOUT", ",", "*", "*", "k...
39.179104
0.001022
def norm(x, y=None, ip_B=None): r'''Compute norm (Euclidean and non-Euclidean). :param x: a 2-dimensional ``numpy.array``. :param y: a 2-dimensional ``numpy.array``. :param ip_B: see :py:meth:`inner`. Compute :math:`\sqrt{\langle x,y\rangle}` where the inner product is defined via ``ip_B``. ...
[ "def", "norm", "(", "x", ",", "y", "=", "None", ",", "ip_B", "=", "None", ")", ":", "# Euclidean inner product?", "if", "y", "is", "None", "and", "(", "ip_B", "is", "None", "or", "isinstance", "(", "ip_B", ",", "IdentityLinearOperator", ")", ")", ":", ...
40.375
0.001008
def group_and_sort_statements(stmt_list, ev_totals=None): """Group statements by type and arguments, and sort by prevalence. Parameters ---------- stmt_list : list[Statement] A list of INDRA statements. ev_totals : dict{int: int} A dictionary, keyed by statement hash (shallow) with ...
[ "def", "group_and_sort_statements", "(", "stmt_list", ",", "ev_totals", "=", "None", ")", ":", "def", "_count", "(", "stmt", ")", ":", "if", "ev_totals", "is", "None", ":", "return", "len", "(", "stmt", ".", "evidence", ")", "else", ":", "return", "ev_to...
38.1
0.000365
def _handle_list(self): """Handle a wiki-style list (``#``, ``*``, ``;``, ``:``).""" self._handle_list_marker() while self._read(1) in ("#", "*", ";", ":"): self._head += 1 self._handle_list_marker()
[ "def", "_handle_list", "(", "self", ")", ":", "self", ".", "_handle_list_marker", "(", ")", "while", "self", ".", "_read", "(", "1", ")", "in", "(", "\"#\"", ",", "\"*\"", ",", "\";\"", ",", "\":\"", ")", ":", "self", ".", "_head", "+=", "1", "self...
40.333333
0.008097
def play_random(env, steps): """ Play the environment making uniformly random decisions. Args: env (gym.Env): the initialized gym environment to play steps (int): the number of random steps to take Returns: None """ try: done = True progress = tqdm(rang...
[ "def", "play_random", "(", "env", ",", "steps", ")", ":", "try", ":", "done", "=", "True", "progress", "=", "tqdm", "(", "range", "(", "steps", ")", ")", "for", "_", "in", "progress", ":", "if", "done", ":", "_", "=", "env", ".", "reset", "(", ...
25.192308
0.001471
def process_request(self, request, client_address): """ Call finish_request. """ self.finish_request(request, client_address) self.shutdown_request(request)
[ "def", "process_request", "(", "self", ",", "request", ",", "client_address", ")", ":", "self", ".", "finish_request", "(", "request", ",", "client_address", ")", "self", ".", "shutdown_request", "(", "request", ")" ]
27.285714
0.010152
def memoizedproperty(func): """ Decorator to cause a method to cache it's results in self for each combination of inputs and return the cached result on subsequent calls. Does not support named arguments or arg values that are not hashable. >>> class Foo (object): ... _x = 1 ... @memoiz...
[ "def", "memoizedproperty", "(", "func", ")", ":", "inner_attname", "=", "'__%s'", "%", "func", ".", "__name__", "def", "new_fget", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'_cache_'", ")", ":", "self", ".", "_cache_", "=", "dic...
25.421053
0.000997
def has_path(self, path): '''Check if a path exists below this node. @param path A list of path elements pointing to a node in the tree. For example, ['/', 'localhost', 'dir.host']. The first element in this path should be this node's name. @return True i...
[ "def", "has_path", "(", "self", ",", "path", ")", ":", "with", "self", ".", "_mutex", ":", "if", "path", "[", "0", "]", "==", "self", ".", "_name", ":", "if", "len", "(", "path", ")", "==", "1", ":", "return", "True", "elif", "path", "[", "1", ...
36.032258
0.001744
def app_update_state(app_id,state): """ update app state """ try: create_at = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') conn = get_conn() c = conn.cursor() c.execute("UPDATE app SET state='{0}',change_at='{1}' WHERE id='{2}'".format(state, create_at, app_id)) ...
[ "def", "app_update_state", "(", "app_id", ",", "state", ")", ":", "try", ":", "create_at", "=", "datetime", ".", "datetime", ".", "now", "(", ")", ".", "strftime", "(", "'%Y-%m-%d %H:%M:%S'", ")", "conn", "=", "get_conn", "(", ")", "c", "=", "conn", "....
37.857143
0.016575
def display_overview(self): """Displays the default pipeline inspection overview """ stay_alive = True self.screen = curses.initscr() self.screen.keypad(True) self.screen.nodelay(-1) curses.cbreak() curses.noecho() curses.start_color() ...
[ "def", "display_overview", "(", "self", ")", ":", "stay_alive", "=", "True", "self", ".", "screen", "=", "curses", ".", "initscr", "(", ")", "self", ".", "screen", ".", "keypad", "(", "True", ")", "self", ".", "screen", ".", "nodelay", "(", "-", "1",...
29.384615
0.001689
def _get_mr_params(self): """Converts self to model.MapreduceSpec.params.""" return {"force_writes": self._force_writes, "done_callback": self.done_callback_url, "user_params": self.user_params, "shard_max_attempts": self.shard_max_attempts, "task_max_attempts": s...
[ "def", "_get_mr_params", "(", "self", ")", ":", "return", "{", "\"force_writes\"", ":", "self", ".", "_force_writes", ",", "\"done_callback\"", ":", "self", ".", "done_callback_url", ",", "\"user_params\"", ":", "self", ".", "user_params", ",", "\"shard_max_attemp...
46.230769
0.001631
def main(): """ NAME igrf.py DESCRIPTION This program calculates igrf field values using the routine of Malin and Barraclough (1981) based on d/igrfs from 1900 to 2010. between 1900 and 1000BCE, it uses CALS3K.4, ARCH3K.1 Prior to 1000BCE, it uses PFM9k or CALS10k-4b Cal...
[ "def", "main", "(", ")", ":", "plot", ",", "fmt", "=", "0", ",", "'svg'", "mod", ",", "alt", ",", "make_plot", ",", "lat", ",", "lon", "=", "'cals10k'", ",", "0", ",", "0", ",", "0", ",", "0", "if", "'-loc'", "in", "sys", ".", "argv", ":", ...
38.630682
0.001291
def writeGTiff(a, dst_fn, src_ds=None, bnum=1, ndv=None, gt=None, proj=None, create=False, sparse=False): """Write input array to disk as GeoTiff Parameters ---------- a : np.array or np.ma.array Input array dst_fn : str Output filename src_ds: GDAL Dataset, optional Sou...
[ "def", "writeGTiff", "(", "a", ",", "dst_fn", ",", "src_ds", "=", "None", ",", "bnum", "=", "1", ",", "ndv", "=", "None", ",", "gt", "=", "None", ",", "proj", "=", "None", ",", "create", "=", "False", ",", "sparse", "=", "False", ")", ":", "#If...
37.754902
0.011387
def function_completions( completion_text: str, bel_spec: BELSpec, function_list: list, bel_fmt: str, size: int, ) -> list: """Filter BEL functions by prefix Args: prefix: completion string bel_fmt: short, medium, long BEL formats spec: BEL specification Returns...
[ "def", "function_completions", "(", "completion_text", ":", "str", ",", "bel_spec", ":", "BELSpec", ",", "function_list", ":", "list", ",", "bel_fmt", ":", "str", ",", "size", ":", "int", ",", ")", "->", "list", ":", "# Convert provided function list to correct ...
28.762712
0.00114
def InsertInt16Arg(self, string="", **_): """Inserts an Integer in base16 argument.""" try: int_value = int(string, 16) return self.InsertArg(int_value) except (TypeError, ValueError): raise ParseError("%s is not a valid base16 integer." % string)
[ "def", "InsertInt16Arg", "(", "self", ",", "string", "=", "\"\"", ",", "*", "*", "_", ")", ":", "try", ":", "int_value", "=", "int", "(", "string", ",", "16", ")", "return", "self", ".", "InsertArg", "(", "int_value", ")", "except", "(", "TypeError",...
38.714286
0.01444
def gen_unkn(): """Return an UNKN instruction. """ empty_reg = ReilEmptyOperand() return ReilBuilder.build(ReilMnemonic.UNKN, empty_reg, empty_reg, empty_reg)
[ "def", "gen_unkn", "(", ")", ":", "empty_reg", "=", "ReilEmptyOperand", "(", ")", "return", "ReilBuilder", ".", "build", "(", "ReilMnemonic", ".", "UNKN", ",", "empty_reg", ",", "empty_reg", ",", "empty_reg", ")" ]
31
0.015707
def pearson_correlation_coefficient(predictions, labels, weights_fn=None): """Calculate pearson correlation coefficient. Args: predictions: The raw predictions. labels: The actual labels. weights_fn: Weighting function. Returns: The pearson correlation coefficient. """ del weights_fn _, pe...
[ "def", "pearson_correlation_coefficient", "(", "predictions", ",", "labels", ",", "weights_fn", "=", "None", ")", ":", "del", "weights_fn", "_", ",", "pearson", "=", "tf", ".", "contrib", ".", "metrics", ".", "streaming_pearson_correlation", "(", "predictions", ...
32.133333
0.010081
def _update_modifier_key(self, orig_key, dep_key): """Update a key based on the dataset it will modified (dep). Typical use case is requesting a modified dataset (orig_key). This modified dataset most likely depends on a less-modified dataset (dep_key). The less-modified dataset must co...
[ "def", "_update_modifier_key", "(", "self", ",", "orig_key", ",", "dep_key", ")", ":", "orig_dict", "=", "orig_key", ".", "_asdict", "(", ")", "dep_dict", "=", "dep_key", ".", "_asdict", "(", ")", "# don't change the modifiers", "for", "k", "in", "DATASET_KEYS...
48.1
0.002039
def compute_feed_time_series( feed: "Feed", trip_stats: DataFrame, dates: List[str], freq: str = "5Min" ) -> DataFrame: """ Compute some feed stats in time series form for the given dates and trip stats. Parameters ---------- feed : Feed trip_stats : DataFrame Trip stats to cons...
[ "def", "compute_feed_time_series", "(", "feed", ":", "\"Feed\"", ",", "trip_stats", ":", "DataFrame", ",", "dates", ":", "List", "[", "str", "]", ",", "freq", ":", "str", "=", "\"5Min\"", ")", "->", "DataFrame", ":", "rts", "=", "feed", ".", "compute_rou...
34.135135
0.000385
def get_hosting_device_config(self, client, hosting_device_id): """Get config of hosting_device.""" return client.get((self.resource_path + HOSTING_DEVICE_CONFIG) % hosting_device_id)
[ "def", "get_hosting_device_config", "(", "self", ",", "client", ",", "hosting_device_id", ")", ":", "return", "client", ".", "get", "(", "(", "self", ".", "resource_path", "+", "HOSTING_DEVICE_CONFIG", ")", "%", "hosting_device_id", ")" ]
55.5
0.008889
def get_user_invitation_by_id(self, id): """Retrieve a UserInvitation object by ID.""" return self.db_adapter.get_object(self.UserInvitationClass, id=id)
[ "def", "get_user_invitation_by_id", "(", "self", ",", "id", ")", ":", "return", "self", ".", "db_adapter", ".", "get_object", "(", "self", ".", "UserInvitationClass", ",", "id", "=", "id", ")" ]
55.666667
0.011834
def is_optional(self): """ Returns whether the parameter is optional or required :return: Return True if optional, False if required """ if (('optional' in self.attributes and bool(self.attributes['optional'].strip())) and ('minValue' in self.attributes and self.a...
[ "def", "is_optional", "(", "self", ")", ":", "if", "(", "(", "'optional'", "in", "self", ".", "attributes", "and", "bool", "(", "self", ".", "attributes", "[", "'optional'", "]", ".", "strip", "(", ")", ")", ")", "and", "(", "'minValue'", "in", "self...
40.3
0.009709
def apply(self, compound, orientation='', compound_port=''): """Arrange copies of a Compound as specified by the Pattern. Parameters ---------- compound orientation Returns ------- """ compounds = list() if self.orientations.get(orientat...
[ "def", "apply", "(", "self", ",", "compound", ",", "orientation", "=", "''", ",", "compound_port", "=", "''", ")", ":", "compounds", "=", "list", "(", ")", "if", "self", ".", "orientations", ".", "get", "(", "orientation", ")", ":", "for", "port", "i...
29.222222
0.002454
def create_roots(self, yam): """Create the top-level structure for module `yam`.""" self.local_grammar = SchemaNode("grammar") self.local_grammar.attr = { "ns": yam.search_one("namespace").arg, "nma:module": self.module.arg} src_text = "YANG module '%s'" % yam.arg...
[ "def", "create_roots", "(", "self", ",", "yam", ")", ":", "self", ".", "local_grammar", "=", "SchemaNode", "(", "\"grammar\"", ")", "self", ".", "local_grammar", ".", "attr", "=", "{", "\"ns\"", ":", "yam", ".", "search_one", "(", "\"namespace\"", ")", "...
49.764706
0.00232
def should_compile_incrementally(self, vts, ctx): """Check to see if the compile should try to re-use the existing analysis. Returns true if we should try to compile the target incrementally. """ if not vts.is_incremental: return False if not self._clear_invalid_analysis: return True ...
[ "def", "should_compile_incrementally", "(", "self", ",", "vts", ",", "ctx", ")", ":", "if", "not", "vts", ".", "is_incremental", ":", "return", "False", "if", "not", "self", ".", "_clear_invalid_analysis", ":", "return", "True", "return", "os", ".", "path", ...
35.3
0.008287
def delete_user(username, uid=None, host=None, admin_username=None, admin_password=None): ''' Delete a user CLI Example: .. code-block:: bash salt dell dracr.delete_user [USERNAME] [UID - optional] salt dell dracr.delete_...
[ "def", "delete_user", "(", "username", ",", "uid", "=", "None", ",", "host", "=", "None", ",", "admin_username", "=", "None", ",", "admin_password", "=", "None", ")", ":", "if", "uid", "is", "None", ":", "user", "=", "list_users", "(", ")", "uid", "=...
27.428571
0.001258
def _check_if_zipped(self, path): """ Checks if the filename shows a tar/zip file """ filename = get_file(path).split('.') if filename[-1] in ['bz', 'bz2', 'gz']: return True return False
[ "def", "_check_if_zipped", "(", "self", ",", "path", ")", ":", "filename", "=", "get_file", "(", "path", ")", ".", "split", "(", "'.'", ")", "if", "filename", "[", "-", "1", "]", "in", "[", "'bz'", ",", "'bz2'", ",", "'gz'", "]", ":", "return", "...
25.111111
0.008547
def main(filename1, filename2, recursive=False, backup=False, suffix='~', *other_filenames): '''An example copy script with some example parameters that might be used in a file or directory copy command. :param recursive: -r --recursive copy directories recursively :param backup: -b --...
[ "def", "main", "(", "filename1", ",", "filename2", ",", "recursive", "=", "False", ",", "backup", "=", "False", ",", "suffix", "=", "'~'", ",", "*", "other_filenames", ")", ":", "filenames", "=", "[", "filename1", ",", "filename2", "]", "+", "list", "(...
41.421053
0.001242
def handle_starttag(self, tagName, attributeList, isSelfClosing=False): ''' handle_starttag - Internal for parsing ''' tagName = tagName.lower() inTag = self._inTag if isSelfClosing is False and tagName in IMPLICIT_SELF_CLOSING_TAGS: isSelfClosing = True ...
[ "def", "handle_starttag", "(", "self", ",", "tagName", ",", "attributeList", ",", "isSelfClosing", "=", "False", ")", ":", "tagName", "=", "tagName", ".", "lower", "(", ")", "inTag", "=", "self", ".", "_inTag", "if", "isSelfClosing", "is", "False", "and", ...
31.321429
0.002212
def _mine_get(self, load, skip_verify=False): ''' Gathers the data from the specified minions' mine ''' if not skip_verify: if any(key not in load for key in ('id', 'tgt', 'fun')): return {} if isinstance(load['fun'], six.string_types): fu...
[ "def", "_mine_get", "(", "self", ",", "load", ",", "skip_verify", "=", "False", ")", ":", "if", "not", "skip_verify", ":", "if", "any", "(", "key", "not", "in", "load", "for", "key", "in", "(", "'id'", ",", "'tgt'", ",", "'fun'", ")", ")", ":", "...
35.961039
0.001054
def cli(env, identifier, domain, userfile, tag, hostname, userdata, public_speed, private_speed): """Edit a virtual server's details.""" if userdata and userfile: raise exceptions.ArgumentError( '[-u | --userdata] not allowed with [-F | --userfile]') data = {} if userdata:...
[ "def", "cli", "(", "env", ",", "identifier", ",", "domain", ",", "userfile", ",", "tag", ",", "hostname", ",", "userdata", ",", "public_speed", ",", "private_speed", ")", ":", "if", "userdata", "and", "userfile", ":", "raise", "exceptions", ".", "ArgumentE...
30.15625
0.001004
def git_suffix(fname): """ :returns: `<short git hash>` if Git repository found """ # we assume that the .git folder is two levels above any package # i.e. openquake/engine/../../.git git_path = os.path.join(os.path.dirname(fname), '..', '..', '.git') # macOS complains if we try to execute ...
[ "def", "git_suffix", "(", "fname", ")", ":", "# we assume that the .git folder is two levels above any package", "# i.e. openquake/engine/../../.git", "git_path", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "fname", ")", ",", "'...
39.307692
0.000955
def analyze(qpi, r0, edgekw={}, ret_center=False, ret_edge=False): """Determine refractive index and radius using Canny edge detection Compute the refractive index of a spherical phase object by detection of an edge in the phase image, a subsequent circle fit to the edge, and finally a weighted average...
[ "def", "analyze", "(", "qpi", ",", "r0", ",", "edgekw", "=", "{", "}", ",", "ret_center", "=", "False", ",", "ret_edge", "=", "False", ")", ":", "nmed", "=", "qpi", "[", "\"medium index\"", "]", "px_m", "=", "qpi", "[", "\"pixel size\"", "]", "wl_m",...
29.981481
0.000598
def get(self, key, missing=None, deferred=None, transaction=None, eventual=False): """Retrieve an entity from a single key (if it exists). .. note:: This is just a thin wrapper over :meth:`get_multi`. The backend API does not make a distinction between a single key or ...
[ "def", "get", "(", "self", ",", "key", ",", "missing", "=", "None", ",", "deferred", "=", "None", ",", "transaction", "=", "None", ",", "eventual", "=", "False", ")", ":", "entities", "=", "self", ".", "get_multi", "(", "keys", "=", "[", "key", "]"...
40.6
0.001603
def load_config(filename=None): """Load a configuration from a file or stdin. If `filename` is `None` or "-", then configuration gets read from stdin. Returns: A `ConfigDict`. Raises: ConfigError: If there is an error loading the config. """ try: with _config_stream(filename) as handl...
[ "def", "load_config", "(", "filename", "=", "None", ")", ":", "try", ":", "with", "_config_stream", "(", "filename", ")", "as", "handle", ":", "filename", "=", "handle", ".", "name", "return", "deserialize_config", "(", "handle", ".", "read", "(", ")", "...
35.625
0.001709
def import_module(module): """ | Given a module `service`, try to import it. | It will autodiscovers all the entrypoints | and add them in `ENTRYPOINTS`. :param module: The module's name to import. :type module: str :rtype: None :raises ImportError: When the service/module to start is n...
[ "def", "import_module", "(", "module", ")", ":", "try", ":", "__import__", "(", "'{0}.service'", ".", "format", "(", "module", ")", ")", "except", "ImportError", ":", "LOGGER", ".", "error", "(", "'No module/service found. Quit.'", ")", "sys", ".", "exit", "...
29.9375
0.002024
def success(self, **kwargs): """Returns all arguments received in init and this method call""" response = {'success': True} # check dates can be manipulated response.update(kwargs) response.update(self.kwargs) response['test_argument3'] = datetime.timedelta(days=1) + resp...
[ "def", "success", "(", "self", ",", "*", "*", "kwargs", ")", ":", "response", "=", "{", "'success'", ":", "True", "}", "# check dates can be manipulated", "response", ".", "update", "(", "kwargs", ")", "response", ".", "update", "(", "self", ".", "kwargs",...
44.875
0.008197
def blueprint(self): """The name of the current blueprint""" if self.url_rule and '.' in self.url_rule.endpoint: return self.url_rule.endpoint.rsplit('.', 1)[0]
[ "def", "blueprint", "(", "self", ")", ":", "if", "self", ".", "url_rule", "and", "'.'", "in", "self", ".", "url_rule", ".", "endpoint", ":", "return", "self", ".", "url_rule", ".", "endpoint", ".", "rsplit", "(", "'.'", ",", "1", ")", "[", "0", "]"...
46.25
0.010638
def validate_get_dbs(connection): """ validates the connection object is capable of read access to rethink should be at least one test database by default :param connection: <rethinkdb.net.DefaultConnection> :return: <set> list of databases :raises: ReqlDriverError AssertionError """ r...
[ "def", "validate_get_dbs", "(", "connection", ")", ":", "remote_dbs", "=", "set", "(", "rethinkdb", ".", "db_list", "(", ")", ".", "run", "(", "connection", ")", ")", "assert", "remote_dbs", "return", "remote_dbs" ]
31.076923
0.002404
def _notifications(self): """ Get the number of unread notifications. """ if not self.username or not self.auth_token: if not self.notification_warning: self.py3.notify_user( "Github module needs username and " "auth_tok...
[ "def", "_notifications", "(", "self", ")", ":", "if", "not", "self", ".", "username", "or", "not", "self", ".", "auth_token", ":", "if", "not", "self", ".", "notification_warning", ":", "self", ".", "py3", ".", "notify_user", "(", "\"Github module needs user...
36.795918
0.002161
def get_hstwcs(filename,hdulist,extnum): """ Return the HSTWCS object for a given chip. """ hdrwcs = wcsutil.HSTWCS(hdulist,ext=extnum) hdrwcs.filename = filename hdrwcs.expname = hdulist[extnum].header['expname'] hdrwcs.extver = hdulist[extnum].header['extver'] return hdrwcs
[ "def", "get_hstwcs", "(", "filename", ",", "hdulist", ",", "extnum", ")", ":", "hdrwcs", "=", "wcsutil", ".", "HSTWCS", "(", "hdulist", ",", "ext", "=", "extnum", ")", "hdrwcs", ".", "filename", "=", "filename", "hdrwcs", ".", "expname", "=", "hdulist", ...
36.75
0.013289
def copy_file(src, dest): """ copy single file """ try: shutil.copy2(src , dest) except Exception as ex: print('ERROR copying file' + str(ex))
[ "def", "copy_file", "(", "src", ",", "dest", ")", ":", "try", ":", "shutil", ".", "copy2", "(", "src", ",", "dest", ")", "except", "Exception", "as", "ex", ":", "print", "(", "'ERROR copying file'", "+", "str", "(", "ex", ")", ")" ]
18
0.059603
def _build_doc(self): """ Raises ------ ValueError * If a URL that lxml cannot parse is passed. Exception * Any other ``Exception`` thrown. For example, trying to parse a URL that is syntactically correct on a machine with no internet ...
[ "def", "_build_doc", "(", "self", ")", ":", "from", "lxml", ".", "html", "import", "parse", ",", "fromstring", ",", "HTMLParser", "from", "lxml", ".", "etree", "import", "XMLSyntaxError", "parser", "=", "HTMLParser", "(", "recover", "=", "True", ",", "enco...
31.73913
0.001329
def table_width(outer_widths, outer_border, inner_border): """Determine the width of the entire table including borders and padding. :param iter outer_widths: List of widths (with padding) for each column. :param int outer_border: Sum of left and right outer border visible widths. :param int inner_bord...
[ "def", "table_width", "(", "outer_widths", ",", "outer_border", ",", "inner_border", ")", ":", "column_count", "=", "len", "(", "outer_widths", ")", "# Count how much space outer and inner borders take up.", "non_data_space", "=", "outer_border", "if", "column_count", ":"...
37.25
0.001309
def read_file_chunk(self, source, pos, chunk): '''Read local file chunk''' if chunk==0: return StringIO() data = None with open(source, 'rb') as f: f.seek(pos) data = f.read(chunk) if not data: raise Failure('Unable to read data from source: %s' % source) return StringI...
[ "def", "read_file_chunk", "(", "self", ",", "source", ",", "pos", ",", "chunk", ")", ":", "if", "chunk", "==", "0", ":", "return", "StringIO", "(", ")", "data", "=", "None", "with", "open", "(", "source", ",", "'rb'", ")", "as", "f", ":", "f", "....
28.818182
0.015291
def div_safe( numerator, denominator ): """ Ufunc-extension that returns 0 instead of nan when dividing numpy arrays Parameters ---------- numerator: array-like denominator: scalar or array-like that can be validly divided by the numerator returns a numpy array example: div_safe( [-1...
[ "def", "div_safe", "(", "numerator", ",", "denominator", ")", ":", "#First handle scalars", "if", "np", ".", "isscalar", "(", "numerator", ")", ":", "raise", "ValueError", "(", "\"div_safe should only be used with an array-like numerator\"", ")", "#Then numpy arrays", "...
29.153846
0.015326
def write(text, filename, encoding='utf-8', mode='wb'): """ Write 'text' to file ('filename') assuming 'encoding' in an atomic way Return (eventually new) encoding """ text, encoding = encode(text, encoding) if 'a' in mode: with open(filename, mode) as textfile: textf...
[ "def", "write", "(", "text", ",", "filename", ",", "encoding", "=", "'utf-8'", ",", "mode", "=", "'wb'", ")", ":", "text", ",", "encoding", "=", "encode", "(", "text", ",", "encoding", ")", "if", "'a'", "in", "mode", ":", "with", "open", "(", "file...
34.533333
0.00188
def is_monotonic(df, items=None, increasing=None, strict=False): """ Asserts that the DataFrame is monotonic. Parameters ========== df : Series or DataFrame items : dict mapping columns to conditions (increasing, strict) increasing : None or bool None is either increasing o...
[ "def", "is_monotonic", "(", "df", ",", "items", "=", "None", ",", "increasing", "=", "None", ",", "strict", "=", "False", ")", ":", "if", "items", "is", "None", ":", "items", "=", "{", "k", ":", "(", "increasing", ",", "strict", ")", "for", "k", ...
32.25
0.001505
def resample_run(res, rstate=None, return_idx=False): """ Probes **sampling uncertainties** on a nested sampling run using bootstrap resampling techniques to generate a *realization* of the (expected) prior volume(s) associated with each sample (dead point). This effectively splits a nested sampling...
[ "def", "resample_run", "(", "res", ",", "rstate", "=", "None", ",", "return_idx", "=", "False", ")", ":", "if", "rstate", "is", "None", ":", "rstate", "=", "np", ".", "random", "# Check whether the final set of live points were added to the", "# run.", "nsamps", ...
39.10101
0.000252
def set_agnocomplete(self, klass_or_instance, user): """ Handling the assignation of the agnocomplete object inside the field. A developer may want to use a class or an instance of an :class:`AgnocompleteBase` class to configure her field. Ex:: from agnocomplete imp...
[ "def", "set_agnocomplete", "(", "self", ",", "klass_or_instance", ",", "user", ")", ":", "# If string, use register to fetch the class", "if", "isinstance", "(", "klass_or_instance", ",", "six", ".", "string_types", ")", ":", "registry", "=", "get_agnocomplete_registry"...
45.794872
0.001096
def openfile(cls, filepath): """Class method that opens (load) a vntree pickle file. :param filepath: the file path for the pickle file. :type filepath: str :returns: root node of tree or `False` if failure. :rtype: Node or bool """ if not os.path.isfi...
[ "def", "openfile", "(", "cls", ",", "filepath", ")", ":", "if", "not", "os", ".", "path", ".", "isfile", "(", "filepath", ")", ":", "logger", ".", "error", "(", "\"%s.openfile: arg `filepath`=«%s» not valid.\" %", "(", "l", "s._", "_", "name__, ", "f", "le...
41.6
0.008226
def convert_md_to_rst(source, destination=None, backup_dir=None): """Try to convert the source, an .md (markdown) file, to an .rst (reStructuredText) file at the destination. If the destination isn't provided, it defaults to be the same as the source path except for the filename extension. If the destin...
[ "def", "convert_md_to_rst", "(", "source", ",", "destination", "=", "None", ",", "backup_dir", "=", "None", ")", ":", "# Doing this in the function instead of the module level ensures the", "# error occurs when the function is called, rather than when the module", "# is evaluated.", ...
37.980769
0.000987
def feed(self, data): """ Feed the input stream. :param data: Input string (unicode). """ assert isinstance(data, six.text_type) if _DEBUG_RENDERER_INPUT: self.LOG.write(repr(data).encode('utf-8') + b'\n') self.LOG.flush() # Handle brack...
[ "def", "feed", "(", "self", ",", "data", ")", ":", "assert", "isinstance", "(", "data", ",", "six", ".", "text_type", ")", "if", "_DEBUG_RENDERER_INPUT", ":", "self", ".", "LOG", ".", "write", "(", "repr", "(", "data", ")", ".", "encode", "(", "'utf-...
40.947368
0.002092
def pipe(): """Return the optimum pipe implementation for the capabilities of the active system.""" try: from os import pipe return pipe() except: pipe = Pipe() return pipe.reader_fd, pipe.writer_fd
[ "def", "pipe", "(", ")", ":", "try", ":", "from", "os", "import", "pipe", "return", "pipe", "(", ")", "except", ":", "pipe", "=", "Pipe", "(", ")", "return", "pipe", ".", "reader_fd", ",", "pipe", ".", "writer_fd" ]
24.3
0.019841
def _damerau_levenshtein(a, b): """Returns Damerau-Levenshtein edit distance from a to b.""" memo = {} def distance(x, y): """Recursively defined string distance with memoization.""" if (x, y) in memo: return memo[x, y] if not x: d = len(y) elif not y: d = len(x) else: ...
[ "def", "_damerau_levenshtein", "(", "a", ",", "b", ")", ":", "memo", "=", "{", "}", "def", "distance", "(", "x", ",", "y", ")", ":", "\"\"\"Recursively defined string distance with memoization.\"\"\"", "if", "(", "x", ",", "y", ")", "in", "memo", ":", "ret...
28.730769
0.014249
def prt_details(self, prt=sys.stdout): """Print summary of codes and groups that can be inputs to get_evcodes.""" prt.write('EVIDENCE CODES:\n') for grp, code2nt in self.grp2code2nt.items(): prt.write(' {GROUP}:\n'.format(GROUP=grp)) for code, ntd in code2nt.items(): ...
[ "def", "prt_details", "(", "self", ",", "prt", "=", "sys", ".", "stdout", ")", ":", "prt", ".", "write", "(", "'EVIDENCE CODES:\\n'", ")", "for", "grp", ",", "code2nt", "in", "self", ".", "grp2code2nt", ".", "items", "(", ")", ":", "prt", ".", "write...
57.285714
0.009828
def read_sparse(cls, file_path: str): """Read a sparse representation from a tab-delimited text file. TODO: docstring""" with open(file_path) as fh: next(fh) # skip header line genes = next(fh)[1:-1].split('\t') cells = next(fh)[1:-1].split(...
[ "def", "read_sparse", "(", "cls", ",", "file_path", ":", "str", ")", ":", "with", "open", "(", "file_path", ")", "as", "fh", ":", "next", "(", "fh", ")", "# skip header line", "genes", "=", "next", "(", "fh", ")", "[", "1", ":", "-", "1", "]", "....
32.25
0.008783
def JoinPath(self, path_segments): """Joins the path segments into a path. Args: path_segments (list[str]): path segments. Returns: str: joined path segments prefixed with the path separator. """ # This is an optimized way to combine the path segments into a single path # and combi...
[ "def", "JoinPath", "(", "self", ",", "path_segments", ")", ":", "# This is an optimized way to combine the path segments into a single path", "# and combine multiple successive path separators to one.", "# Split all the path segments based on the path (segment) separator.", "path_segments", ...
33.48
0.001161
def is_defined(self, symbolTable=None): """ True if this macro has been defined """ if symbolTable is None: symbolTable = self.table return symbolTable.defined(self.id_)
[ "def", "is_defined", "(", "self", ",", "symbolTable", "=", "None", ")", ":", "if", "symbolTable", "is", "None", ":", "symbolTable", "=", "self", ".", "table", "return", "symbolTable", ".", "defined", "(", "self", ".", "id_", ")" ]
29.714286
0.009346
def open_closed_files(self): """Open some closed files if they may have new lines. Opening more files may require us to close some of the already open files. """ if not self.can_open_more_files: # If we can't open any more files. Close all of the files. s...
[ "def", "open_closed_files", "(", "self", ")", ":", "if", "not", "self", ".", "can_open_more_files", ":", "# If we can't open any more files. Close all of the files.", "self", ".", "close_all_files", "(", ")", "files_with_no_updates", "=", "[", "]", "while", "len", "("...
41.563636
0.000855
def _parse_value(self, stats, field): """ Pull the specified value from the HTML contents. Given a field, find the corresponding HTML tag for that field and parse its value before returning the value as a string. Parameters ---------- stats : PyQuery object ...
[ "def", "_parse_value", "(", "self", ",", "stats", ",", "field", ")", ":", "value", "=", "utils", ".", "_parse_field", "(", "PLAYER_SCHEME", ",", "stats", ",", "field", ")", "if", "not", "value", "and", "field", "in", "BOXSCORE_RETRY", ":", "value", "=", ...
32.916667
0.00246
def fetcher(ctx, xmlrpc, xmlrpc_host, xmlrpc_port, poolsize, proxy, user_agent, timeout, phantomjs_endpoint, puppeteer_endpoint, splash_endpoint, fetcher_cls, async_mode=True, get_object=False, no_input=False): """ Run Fetcher. """ g = ctx.obj Fetcher = load_cls(None, None, f...
[ "def", "fetcher", "(", "ctx", ",", "xmlrpc", ",", "xmlrpc_host", ",", "xmlrpc_port", ",", "poolsize", ",", "proxy", ",", "user_agent", ",", "timeout", ",", "phantomjs_endpoint", ",", "puppeteer_endpoint", ",", "splash_endpoint", ",", "fetcher_cls", ",", "async_m...
36.090909
0.002453
def get_ipv6_neighbors_table(self): """ Get IPv6 neighbors table information. Return a list of dictionaries having the following set of keys: * interface (string) * mac (string) * ip (string) * age (float) in seconds * state (string) ...
[ "def", "get_ipv6_neighbors_table", "(", "self", ")", ":", "ipv6_neighbors_table", "=", "[", "]", "command", "=", "\"show ipv6 neighbors\"", "output", "=", "self", ".", "_send_command", "(", "command", ")", "ipv6_neighbors", "=", "\"\"", "fields", "=", "re", ".",...
36.480769
0.00154
def paste(region, img, left, above, right, down): """ 将扣的图粘贴到制定图片上 当你粘贴矩形选区的时候必须保证尺寸一致。此外,矩形选区不能在图像外。然而你不必保证矩形选区和原图的颜色模式一致, 因为矩形选区会被自动转换颜色,遗憾的是,只能扣矩形图。 :param region: 扣出的图 :param img: 指定图片 :param left: 左 :param above: 上 :param right: 右 :param down: 下 :return: 被修改过的图片对象,还在内存中...
[ "def", "paste", "(", "region", ",", "img", ",", "left", ",", "above", ",", "right", ",", "down", ")", ":", "region", "=", "region", ".", "transpose", "(", "Image", ".", "ROTATE_180", ")", "box", "=", "(", "left", ",", "above", ",", "right", ",", ...
24.611111
0.002174
def get_siblings_score(self, top_node): """\ we could have long articles that have tons of paragraphs so if we tried to calculate the base score against the total text score of those paragraphs it would be unfair. So we need to normalize the score based on the average scoring ...
[ "def", "get_siblings_score", "(", "self", ",", "top_node", ")", ":", "base", "=", "100000", "paragraphs_number", "=", "0", "paragraphs_score", "=", "0", "nodes_to_check", "=", "self", ".", "parser", ".", "getElementsByTag", "(", "top_node", ",", "tag", "=", ...
44.259259
0.002457
def get_help(self): """ Gets the help text for the command. If its not supplied the doc string is used. """ if self.help: return self.help elif self.__doc__ and self.__doc__.strip(): return self.__doc__.strip() else: return ''
[ "def", "get_help", "(", "self", ")", ":", "if", "self", ".", "help", ":", "return", "self", ".", "help", "elif", "self", ".", "__doc__", "and", "self", ".", "__doc__", ".", "strip", "(", ")", ":", "return", "self", ".", "__doc__", ".", "strip", "("...
30.1
0.009677
def _affine_mult(c:FlowField,m:AffineMatrix)->FlowField: "Multiply `c` by `m` - can adjust for rectangular shaped `c`." if m is None: return c size = c.flow.size() h,w = c.size m[0,1] *= h/w m[1,0] *= w/h c.flow = c.flow.view(-1,2) c.flow = torch.addmm(m[:2,2], c.flow, m[:2,:2].t()).vie...
[ "def", "_affine_mult", "(", "c", ":", "FlowField", ",", "m", ":", "AffineMatrix", ")", "->", "FlowField", ":", "if", "m", "is", "None", ":", "return", "c", "size", "=", "c", ".", "flow", ".", "size", "(", ")", "h", ",", "w", "=", "c", ".", "siz...
33.1
0.035294
def summary_df(df_in, **kwargs): """Make a panda data frame of the mean and std devs of an array of results, including the uncertainties on the values. This is similar to pandas.DataFrame.describe but also includes estimates of the numerical uncertainties. The output DataFrame has multiindex level...
[ "def", "summary_df", "(", "df_in", ",", "*", "*", "kwargs", ")", ":", "true_values", "=", "kwargs", ".", "pop", "(", "'true_values'", ",", "None", ")", "include_true_values", "=", "kwargs", ".", "pop", "(", "'include_true_values'", ",", "False", ")", "incl...
41.1625
0.000297
def resource_group_delete(name, **kwargs): ''' .. versionadded:: 2019.2.0 Delete a resource group from the subscription. :param name: The resource group name to delete. CLI Example: .. code-block:: bash salt-call azurearm_resource.resource_group_delete testgroup ''' result ...
[ "def", "resource_group_delete", "(", "name", ",", "*", "*", "kwargs", ")", ":", "result", "=", "False", "resconn", "=", "__utils__", "[", "'azurearm.get_client'", "]", "(", "'resource'", ",", "*", "*", "kwargs", ")", "try", ":", "group", "=", "resconn", ...
24.16
0.001592
def _ondemand(f): """Decorator to only request information if not in cache already. """ name = f.__name__ def func(self, *args, **kwargs): if not args and not kwargs: if hasattr(self, '_%s' % name): return getattr(self, '_%s' % name) a = f(self, *args, *...
[ "def", "_ondemand", "(", "f", ")", ":", "name", "=", "f", ".", "__name__", "def", "func", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "args", "and", "not", "kwargs", ":", "if", "hasattr", "(", "self", ",", "'_...
27.941176
0.002037
def get_subgroupiteminsertion( cls, itemgroup, model, subgroup, indent) -> str: """Return a string defining the required types for the given combination of an exchange item group and a specific variable subgroup of an application model or class |Node|. Note that for `setitem...
[ "def", "get_subgroupiteminsertion", "(", "cls", ",", "itemgroup", ",", "model", ",", "subgroup", ",", "indent", ")", "->", "str", ":", "blanks1", "=", "' '", "*", "(", "indent", "*", "4", ")", "blanks2", "=", "' '", "*", "(", "(", "indent", "+", "5",...
44.038095
0.000423
def create_healthcheck(self, service_id, version_number, name, host, method="HEAD", path="/", http_version="1.1", timeout=1000, check_interval=5000, expected_response=200, window=5, threshold=3, initial=1): """Create a healthcheck for a particular service and version.""" body = self._form...
[ "def", "create_healthcheck", "(", "self", ",", "service_id", ",", "version_number", ",", "name", ",", "host", ",", "method", "=", "\"HEAD\"", ",", "path", "=", "\"/\"", ",", "http_version", "=", "\"1.1\"", ",", "timeout", "=", "1000", ",", "check_interval", ...
25.6
0.057716
def cli(env, identifier, name, all, note): """Capture one or all disks from a virtual server to a SoftLayer image.""" vsi = SoftLayer.VSManager(env.client) vs_id = helpers.resolve_id(vsi.resolve_ids, identifier, 'VS') capture = vsi.capture(vs_id, name, all, note) table = formatting.KeyValueTable(...
[ "def", "cli", "(", "env", ",", "identifier", ",", "name", ",", "all", ",", "note", ")", ":", "vsi", "=", "SoftLayer", ".", "VSManager", "(", "env", ".", "client", ")", "vs_id", "=", "helpers", ".", "resolve_id", "(", "vsi", ".", "resolve_ids", ",", ...
38.473684
0.001335
def outlineWidth(self, value): """gets/sets the outlineWidth""" if isinstance(value, (int, float, long)) and \ not self._outline is None: self._outline['width'] = value
[ "def", "outlineWidth", "(", "self", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "(", "int", ",", "float", ",", "long", ")", ")", "and", "not", "self", ".", "_outline", "is", "None", ":", "self", ".", "_outline", "[", "'width'", "...
40.6
0.014493