text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def get_member_slackuid(self, slack): """Get a CSHMember object. Arguments: slack -- the Slack UID of the member Returns: None if the Slack UID provided does not correspond to a CSH Member """ members = self.__con__.search_s( CSHMember.__ldap_user_ou...
[ "def", "get_member_slackuid", "(", "self", ",", "slack", ")", ":", "members", "=", "self", ".", "__con__", ".", "search_s", "(", "CSHMember", ".", "__ldap_user_ou__", ",", "ldap", ".", "SCOPE_SUBTREE", ",", "\"(slackuid=%s)\"", "%", "slack", ",", "[", "'ipaU...
29.7
15.15
def _leapfrog_integrator_one_step( target_log_prob_fn, independent_chain_ndims, step_sizes, current_momentum_parts, current_state_parts, current_target_log_prob, current_target_log_prob_grad_parts, state_gradients_are_stopped=False, name=None): """Applies `num_leapfrog_steps` of th...
[ "def", "_leapfrog_integrator_one_step", "(", "target_log_prob_fn", ",", "independent_chain_ndims", ",", "step_sizes", ",", "current_momentum_parts", ",", "current_state_parts", ",", "current_target_log_prob", ",", "current_target_log_prob_grad_parts", ",", "state_gradients_are_stop...
38.613043
20.873913
def check_offset(self): """Check to see if initial position and goal are the same if they are, offset slightly so that the forcing term is not 0""" for d in range(self.dmps): if (self.y0[d] == self.goal[d]): self.goal[d] += 1e-4
[ "def", "check_offset", "(", "self", ")", ":", "for", "d", "in", "range", "(", "self", ".", "dmps", ")", ":", "if", "(", "self", ".", "y0", "[", "d", "]", "==", "self", ".", "goal", "[", "d", "]", ")", ":", "self", ".", "goal", "[", "d", "]"...
39.285714
10.142857
def convert(model, input_features, output_features): """Convert a _imputer model to the protobuf spec. Parameters ---------- model: Imputer A trained Imputer model. input_features: str Name of the input column. output_features: str Name of the output column. Retur...
[ "def", "convert", "(", "model", ",", "input_features", ",", "output_features", ")", ":", "_INTERMEDIATE_FEATURE_NAME", "=", "\"__sparse_vector_features__\"", "n_dimensions", "=", "len", "(", "model", ".", "feature_names_", ")", "input_features", "=", "process_or_validat...
34.216216
23.756757
def get_params(self): """Get signature and params """ params = { 'key': self.get_app_key(), 'uid': self.user_id, 'widget': self.widget_code } products_number = len(self.products) if self.get_api_type() == self.API_GOODS: ...
[ "def", "get_params", "(", "self", ")", ":", "params", "=", "{", "'key'", ":", "self", ".", "get_app_key", "(", ")", ",", "'uid'", ":", "self", ".", "user_id", ",", "'widget'", ":", "self", ".", "widget_code", "}", "products_number", "=", "len", "(", ...
46.887324
30.183099
def pack(self): ''' Pack this exception into a serializable dictionary that is safe for transport via msgpack ''' if six.PY3: return {'message': six.text_type(self), 'args': self.args} return dict(message=self.__unicode__(), args=self.args)
[ "def", "pack", "(", "self", ")", ":", "if", "six", ".", "PY3", ":", "return", "{", "'message'", ":", "six", ".", "text_type", "(", "self", ")", ",", "'args'", ":", "self", ".", "args", "}", "return", "dict", "(", "message", "=", "self", ".", "__u...
36.625
25.375
def yield_pair_gradients(self, index1, index2): """Yields pairs ((s'(r_ij), grad_i v(bar{r}_ij))""" strength = self.strengths[index1, index2] distance = self.distances[index1, index2] yield -6*strength*distance**(-7), np.zeros(3)
[ "def", "yield_pair_gradients", "(", "self", ",", "index1", ",", "index2", ")", ":", "strength", "=", "self", ".", "strengths", "[", "index1", ",", "index2", "]", "distance", "=", "self", ".", "distances", "[", "index1", ",", "index2", "]", "yield", "-", ...
51.4
7.6
def _handle_successor_multitargets(self, job, successor, all_successors): """ Generate new jobs for all possible successor targets when there are more than one possible concrete value for successor.ip :param VFGJob job: The VFGJob instance. :param SimState successor: The succeed...
[ "def", "_handle_successor_multitargets", "(", "self", ",", "job", ",", "successor", ",", "all_successors", ")", ":", "new_jobs", "=", "[", "]", "# Currently we assume a legit jumping target cannot have more than 256 concrete values", "# TODO: make it a setting on VFG", "MAX_NUMBE...
44.191489
26.829787
def predict(self, measurement, output_format='array'): """ Method to predict the class labels for the provided data :param measurement: the point to classify :type measurement: pandas.DataFrame :param output_format: the format to return the scores ('array' or 'st...
[ "def", "predict", "(", "self", ",", "measurement", ",", "output_format", "=", "'array'", ")", ":", "scores", "=", "np", ".", "array", "(", "[", "]", ")", "for", "obs", "in", "self", ".", "observations", ":", "knn", "=", "self", ".", "__get_knn_by_obser...
42.666667
19.25
def focus_changed(self): """Editor focus has changed""" fwidget = QApplication.focusWidget() for finfo in self.data: if fwidget is finfo.editor: self.refresh() self.editor_focus_changed.emit()
[ "def", "focus_changed", "(", "self", ")", ":", "fwidget", "=", "QApplication", ".", "focusWidget", "(", ")", "for", "finfo", "in", "self", ".", "data", ":", "if", "fwidget", "is", "finfo", ".", "editor", ":", "self", ".", "refresh", "(", ")", "self", ...
36
5.285714
def cipher(self): """Applies the Caesar shift cipher. Based on the attributes of the object, applies the Caesar shift cipher to the message attribute. Accepts positive and negative integers as offsets. Required attributes: message offset Returns...
[ "def", "cipher", "(", "self", ")", ":", "# If no offset is selected, pick random one with sufficient distance", "# from original.", "if", "self", ".", "offset", "is", "False", ":", "self", ".", "offset", "=", "randrange", "(", "5", ",", "25", ")", "logging", ".", ...
40.022727
19.704545
def get_smart_contract(self, hex_contract_address: str, is_full: bool = False) -> dict: """ This interface is used to get the information of smart contract based on the specified hexadecimal hash value. :param hex_contract_address: str, a hexadecimal hash value. :param is_full: ...
[ "def", "get_smart_contract", "(", "self", ",", "hex_contract_address", ":", "str", ",", "is_full", ":", "bool", "=", "False", ")", "->", "dict", ":", "if", "not", "isinstance", "(", "hex_contract_address", ",", "str", ")", ":", "raise", "SDKException", "(", ...
54.411765
29.352941
def reverseCommit(self): """ Re-insert the previously removed character(s). """ # Get the text cursor for the current document. tc = self.qteWidget.textCursor() # Mark the previously inserted text and remove it. tc.setPosition(self.cursorPos0, QtGui.QTextCursor.M...
[ "def", "reverseCommit", "(", "self", ")", ":", "# Get the text cursor for the current document.", "tc", "=", "self", ".", "qteWidget", ".", "textCursor", "(", ")", "# Mark the previously inserted text and remove it.", "tc", ".", "setPosition", "(", "self", ".", "cursorP...
37.266667
16.733333
def ConsultarTiposCategoriaEmisor(self, sep="||"): "Obtener el código y descripción para tipos de categorías de emisor" ret = self.client.consultarTiposCategoriaEmisor( authRequest={ 'token': self.Token, 'sign': self.Sign, ...
[ "def", "ConsultarTiposCategoriaEmisor", "(", "self", ",", "sep", "=", "\"||\"", ")", ":", "ret", "=", "self", ".", "client", ".", "consultarTiposCategoriaEmisor", "(", "authRequest", "=", "{", "'token'", ":", "self", ".", "Token", ",", "'sign'", ":", "self",...
63
23.727273
def _create_base_string(method, base, params): """ Returns base string for HMAC-SHA1 signature as specified in: http://oauth.net/core/1.0a/#rfc.section.9.1.3. """ normalized_qs = _normalize_params(params) return _join_by_ampersand(method, base, normalized_qs)
[ "def", "_create_base_string", "(", "method", ",", "base", ",", "params", ")", ":", "normalized_qs", "=", "_normalize_params", "(", "params", ")", "return", "_join_by_ampersand", "(", "method", ",", "base", ",", "normalized_qs", ")" ]
34.625
12.875
def state_definition_to_dict(state_definition: GeneralState) -> AccountState: """Convert a state definition to the canonical dict form. State can either be defined in the canonical form, or as a list of sub states that are then merged to one. Sub states can either be given as dictionaries themselves, or as...
[ "def", "state_definition_to_dict", "(", "state_definition", ":", "GeneralState", ")", "->", "AccountState", ":", "if", "isinstance", "(", "state_definition", ",", "Mapping", ")", ":", "state_dict", "=", "state_definition", "elif", "isinstance", "(", "state_definition"...
34.387755
23.367347
def get_file(cls, filename=None): """ Load settings from an rtv configuration file. """ if filename is None: filename = CONFIG config = configparser.ConfigParser() if os.path.exists(filename): with codecs.open(filename, encoding='utf-8') as fp: ...
[ "def", "get_file", "(", "cls", ",", "filename", "=", "None", ")", ":", "if", "filename", "is", "None", ":", "filename", "=", "CONFIG", "config", "=", "configparser", ".", "ConfigParser", "(", ")", "if", "os", ".", "path", ".", "exists", "(", "filename"...
27.357143
14.5
def _AtNonLeaf(self, attr_value, path): """Called when at a non-leaf value. Should recurse and yield values.""" try: if isinstance(attr_value, collections.Mapping): # If it's dictionary-like, treat the dict key as the attribute.. sub_obj = attr_value.get(path[1]) if len(path) > 2: ...
[ "def", "_AtNonLeaf", "(", "self", ",", "attr_value", ",", "path", ")", ":", "try", ":", "if", "isinstance", "(", "attr_value", ",", "collections", ".", "Mapping", ")", ":", "# If it's dictionary-like, treat the dict key as the attribute..", "sub_obj", "=", "attr_val...
41.62963
15.666667
def get_elemental_abunds(self,cycle,index=None): """ returns the elemental abundances for one cycle, either for the whole star or a specific zone depending upon the value of 'index'. Parameters ---------- cycle : string or integer Model to get the abu...
[ "def", "get_elemental_abunds", "(", "self", ",", "cycle", ",", "index", "=", "None", ")", ":", "isoabunds", "=", "self", ".", "se", ".", "get", "(", "cycle", ",", "'iso_massf'", ")", "A", "=", "array", "(", "self", ".", "se", ".", "A", ")", "Z", ...
34.4
19.6
def p_debugger_statement(self, p): """debugger_statement : DEBUGGER SEMI | DEBUGGER AUTOSEMI """ p[0] = self.asttypes.Debugger(p[1]) p[0].setpos(p)
[ "def", "p_debugger_statement", "(", "self", ",", "p", ")", ":", "p", "[", "0", "]", "=", "self", ".", "asttypes", ".", "Debugger", "(", "p", "[", "1", "]", ")", "p", "[", "0", "]", ".", "setpos", "(", "p", ")" ]
34
6
def psql(self, args): r"""Invoke psql, passing the given command-line arguments. Typical <args> values: ['-c', <sql_string>] or ['-f', <pathname>]. Connection parameters are taken from self. STDIN, STDOUT, and STDERR are inherited from the parent. WARNING: This method uses th...
[ "def", "psql", "(", "self", ",", "args", ")", ":", "argv", "=", "[", "PostgresFinder", ".", "find_root", "(", ")", "/", "'psql'", ",", "'--quiet'", ",", "'-U'", ",", "self", ".", "user", ",", "'-h'", ",", "self", ".", "host", ",", "'-p'", ",", "s...
36.038462
21.230769
def write_output(self, data, args=None, filename=None, label=None): """Write log data to a log file""" if args: if not args.outlog: return 0 if not filename: filename=args.outlog lastpath = '' with open(str(filename), 'w') as output_file: f...
[ "def", "write_output", "(", "self", ",", "data", ",", "args", "=", "None", ",", "filename", "=", "None", ",", "label", "=", "None", ")", ":", "if", "args", ":", "if", "not", "args", ".", "outlog", ":", "return", "0", "if", "not", "filename", ":", ...
49.045455
16.045455
def _check_default(value, parameter, default_chars): '''Returns the default if the value is "empty"''' # not using a set here because it fails when value is unhashable if value in default_chars: if parameter.default is inspect.Parameter.empty: raise ValueError('Value was empty, but no de...
[ "def", "_check_default", "(", "value", ",", "parameter", ",", "default_chars", ")", ":", "# not using a set here because it fails when value is unhashable", "if", "value", "in", "default_chars", ":", "if", "parameter", ".", "default", "is", "inspect", ".", "Parameter", ...
58.5
29
def update(self, value, *args, **kwargs): """ Call this function to inform that an update is available. This function does NOT call finish when value == maximum. :param value: The current index/position of the action. (Should be, but must not be, in the range [min, max]) :param a...
[ "def", "update", "(", "self", ",", "value", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "log", ".", "debug", "(", "'update(value={value}, args={args}, kwargs={kwargs})'", ".", "format", "(", "value", "=", "value", ",", "args", "=", "args", ",", ...
58.9
24.7
def master_primary_name(self) -> Optional[str]: """ Return the name of the primary node of the master instance """ master_primary_name = self.master_replica.primaryName if master_primary_name: return self.master_replica.getNodeName(master_primary_name) return...
[ "def", "master_primary_name", "(", "self", ")", "->", "Optional", "[", "str", "]", ":", "master_primary_name", "=", "self", ".", "master_replica", ".", "primaryName", "if", "master_primary_name", ":", "return", "self", ".", "master_replica", ".", "getNodeName", ...
35.222222
17.222222
def ellipse(self, x, y, width, height, color): """ See the Processing function ellipse(): https://processing.org/reference/ellipse_.html """ self.context.set_source_rgb(*color) self.context.save() self.context.translate(self.tx(x + (width / 2.0)), self.ty(y + (hei...
[ "def", "ellipse", "(", "self", ",", "x", ",", "y", ",", "width", ",", "height", ",", "color", ")", ":", "self", ".", "context", ".", "set_source_rgb", "(", "*", "color", ")", "self", ".", "context", ".", "save", "(", ")", "self", ".", "context", ...
42.5
13.333333
def validate(self, data, schema, **kwargs): """Validate data using schema with ``JSONResolver``.""" if not isinstance(schema, dict): schema = {'$ref': schema} return validate( data, schema, resolver=self.ref_resolver_cls.from_schema(schema), ...
[ "def", "validate", "(", "self", ",", "data", ",", "schema", ",", "*", "*", "kwargs", ")", ":", "if", "not", "isinstance", "(", "schema", ",", "dict", ")", ":", "schema", "=", "{", "'$ref'", ":", "schema", "}", "return", "validate", "(", "data", ","...
36.818182
15.454545
def user_admin_view(model, login_view="Login", template_dir=None): """ :param UserStruct: The User model structure containing other classes :param login_view: The login view interface :param template_dir: The directory containing the view pages :return: UserAdmin Doc: User Admin is a view t...
[ "def", "user_admin_view", "(", "model", ",", "login_view", "=", "\"Login\"", ",", "template_dir", "=", "None", ")", ":", "Pylot", ".", "context_", "(", "COMPONENT_USER_ADMIN", "=", "True", ")", "User", "=", "model", ".", "UserStruct", ".", "User", "LoginView...
36.251429
20.182857
def set_headers(self, headers): """Set headers""" for (header, value) in headers.iteritems(): self.set_header(header, value)
[ "def", "set_headers", "(", "self", ",", "headers", ")", ":", "for", "(", "header", ",", "value", ")", "in", "headers", ".", "iteritems", "(", ")", ":", "self", ".", "set_header", "(", "header", ",", "value", ")" ]
37.25
5.5
def _get_post_data_to_create_dns_entry(self, rtype, name, content, identifier=None): """ Build and return the post date that is needed to create a DNS entry. """ is_update = identifier is not None if is_update: records = self._list_records_internal(identifier=identifi...
[ "def", "_get_post_data_to_create_dns_entry", "(", "self", ",", "rtype", ",", "name", ",", "content", ",", "identifier", "=", "None", ")", ":", "is_update", "=", "identifier", "is", "not", "None", "if", "is_update", ":", "records", "=", "self", ".", "_list_re...
36.066667
19.4
def _process_field_queries(field_dictionary): """ We have a field_dictionary - we want to match the values for an elasticsearch "match" query This is only potentially useful when trying to tune certain search operations """ def field_item(field): """ format field match as "match" item for el...
[ "def", "_process_field_queries", "(", "field_dictionary", ")", ":", "def", "field_item", "(", "field", ")", ":", "\"\"\" format field match as \"match\" item for elasticsearch query \"\"\"", "return", "{", "\"match\"", ":", "{", "field", ":", "field_dictionary", "[", "fie...
35.785714
20.071429
def locales(self, query=None): """Fetches all Locales from the Environment (up to the set limit, can be modified in `query`). # TODO: fix url API Reference: https://www.contentful.com/developers/docs/references/content-delivery-api/#/reference/assets/assets-collection/get-all-assets-of-a-space ...
[ "def", "locales", "(", "self", ",", "query", "=", "None", ")", ":", "if", "query", "is", "None", ":", "query", "=", "{", "}", "return", "self", ".", "_get", "(", "self", ".", "environment_url", "(", "'/locales'", ")", ",", "query", ")" ]
36.863636
27.636364
def _calc_min_width(self, table): """ Calculate the minimum allowable width for a table """ width = len(table.name) cap = table.consumed_capacity["__table__"] width = max(width, 4 + len("%.1f/%d" % (cap["read"], table.read_throughput))) width = max(width, 4 + len("%.1f/%d" % (cap...
[ "def", "_calc_min_width", "(", "self", ",", "table", ")", ":", "width", "=", "len", "(", "table", ".", "name", ")", "cap", "=", "table", ".", "consumed_capacity", "[", "\"__table__\"", "]", "width", "=", "max", "(", "width", ",", "4", "+", "len", "("...
43.15
21.6
def distance(self, x, y): """ Computes the Manhattan distance between vectors x and y. Returns float. """ if scipy.sparse.issparse(x): return numpy.sum(numpy.absolute((x-y).toarray().ravel())) else: return numpy.sum(numpy.absolute(x-y))
[ "def", "distance", "(", "self", ",", "x", ",", "y", ")", ":", "if", "scipy", ".", "sparse", ".", "issparse", "(", "x", ")", ":", "return", "numpy", ".", "sum", "(", "numpy", ".", "absolute", "(", "(", "x", "-", "y", ")", ".", "toarray", "(", ...
36.625
15.375
def glob_in_parents(dir, patterns, upper_limit=None): """Recursive version of GLOB which glob sall parent directories of dir until the first match is found. Returns an empty result if no match is found""" assert(isinstance(dir, str)) assert(isinstance(patterns, list)) result = [] absolute...
[ "def", "glob_in_parents", "(", "dir", ",", "patterns", ",", "upper_limit", "=", "None", ")", ":", "assert", "(", "isinstance", "(", "dir", ",", "str", ")", ")", "assert", "(", "isinstance", "(", "patterns", ",", "list", ")", ")", "result", "=", "[", ...
29.227273
18.045455
def submit_all(self): """ :returns: an IterResult object """ for args in self.task_args: self.submit(*args) return self.get_results()
[ "def", "submit_all", "(", "self", ")", ":", "for", "args", "in", "self", ".", "task_args", ":", "self", ".", "submit", "(", "*", "args", ")", "return", "self", ".", "get_results", "(", ")" ]
25.571429
6.142857
def add_cmd_handler(self, handler_obj): """Registers a new command handler object. All methods on `handler_obj` whose name starts with "cmd_" are registered as a GTP command. For example, the method cmd_genmove will be invoked when the engine receives a genmove command. Args: ...
[ "def", "add_cmd_handler", "(", "self", ",", "handler_obj", ")", ":", "for", "field", "in", "dir", "(", "handler_obj", ")", ":", "if", "field", ".", "startswith", "(", "\"cmd_\"", ")", ":", "cmd", "=", "field", "[", "4", ":", "]", "fn", "=", "getattr"...
40.736842
15.210526
def auto_override(memb): """Decorator applicable to methods, classes or modules (by explicit call). If applied on a module, memb must be a module or a module name contained in sys.modules. See pytypes.set_global_auto_override_decorator to apply this on all modules. Works like override decorator on type ...
[ "def", "auto_override", "(", "memb", ")", ":", "if", "type_util", ".", "_check_as_func", "(", "memb", ")", ":", "return", "override", "(", "memb", ",", "True", ")", "if", "isclass", "(", "memb", ")", ":", "return", "auto_override_class", "(", "memb", ")"...
56.956522
24.304348
def wait_until_gone(self, timeout=0, *args, **selectors): """ Wait for the object which has *selectors* within the given timeout. Return true if the object *disappear* in the given timeout. Else return false. """ return self.device(**selectors).wait.gone(timeout=timeout)
[ "def", "wait_until_gone", "(", "self", ",", "timeout", "=", "0", ",", "*", "args", ",", "*", "*", "selectors", ")", ":", "return", "self", ".", "device", "(", "*", "*", "selectors", ")", ".", "wait", ".", "gone", "(", "timeout", "=", "timeout", ")"...
43.714286
23.428571
def reset_formatter(self): """Rebuild formatter for all handlers.""" for handler in self.handlers: formatter = self.get_formatter(handler) handler.setFormatter(formatter)
[ "def", "reset_formatter", "(", "self", ")", ":", "for", "handler", "in", "self", ".", "handlers", ":", "formatter", "=", "self", ".", "get_formatter", "(", "handler", ")", "handler", ".", "setFormatter", "(", "formatter", ")" ]
41.2
6.2
def CacheStorage_requestCachedResponse(self, cacheId, requestURL): """ Function path: CacheStorage.requestCachedResponse Domain: CacheStorage Method name: requestCachedResponse Parameters: Required arguments: 'cacheId' (type: CacheId) -> Id of cache that contains the enty. 'requestURL' (ty...
[ "def", "CacheStorage_requestCachedResponse", "(", "self", ",", "cacheId", ",", "requestURL", ")", ":", "assert", "isinstance", "(", "requestURL", ",", "(", "str", ",", ")", ")", ",", "\"Argument 'requestURL' must be of type '['str']'. Received type: '%s'\"", "%", "type"...
36.238095
20.142857
def add_config(lines): ''' Add one or more config lines to the switch running config .. code-block:: bash salt '*' onyx.cmd add_config 'snmp-server community TESTSTRINGHERE rw' .. note:: For more than one config added per command, lines should be a list. ''' if not isinstance(...
[ "def", "add_config", "(", "lines", ")", ":", "if", "not", "isinstance", "(", "lines", ",", "list", ")", ":", "lines", "=", "[", "lines", "]", "try", ":", "enable", "(", ")", "configure_terminal", "(", ")", "for", "line", "in", "lines", ":", "sendline...
23.52
24
def overall_state_id(self): """Get the service overall state. The service overall state identifier is the service status including: - the monitored state - the acknowledged state - the downtime state The overall state is (prioritized): - a service is not monitor...
[ "def", "overall_state_id", "(", "self", ")", ":", "overall_state", "=", "0", "if", "not", "self", ".", "monitored", ":", "overall_state", "=", "5", "elif", "self", ".", "acknowledged", ":", "overall_state", "=", "1", "elif", "self", ".", "downtimed", ":", ...
32.175
14.625
def _encode_status(status): """Cast status to bytes representation of current Python version. According to :pep:`3333`, when using Python 3, the response status and headers must be bytes masquerading as unicode; that is, they must be of type "str" but are restricted to code points in th...
[ "def", "_encode_status", "(", "status", ")", ":", "if", "six", ".", "PY2", ":", "return", "status", "if", "not", "isinstance", "(", "status", ",", "str", ")", ":", "raise", "TypeError", "(", "'WSGI response status is not of type str.'", ")", "return", "status"...
41.923077
18.230769
def forward(self, input, target): """ Calculate the loss :param input: prediction logits :param target: target probabilities :return: loss """ n, k = input.shape losses = input.new_zeros(n) for i in range(k): cls_idx = input.new_full...
[ "def", "forward", "(", "self", ",", "input", ",", "target", ")", ":", "n", ",", "k", "=", "input", ".", "shape", "losses", "=", "input", ".", "new_zeros", "(", "n", ")", "for", "i", "in", "range", "(", "k", ")", ":", "cls_idx", "=", "input", "....
29.851852
15.407407
def _api_args_item(self, item): """Glances API RESTful implementation. Return the JSON representation of the Glances command line arguments item HTTP/200 if OK HTTP/400 if item is not found HTTP/404 if others error """ response.content_type = 'application/json; c...
[ "def", "_api_args_item", "(", "self", ",", "item", ")", ":", "response", ".", "content_type", "=", "'application/json; charset=utf-8'", "if", "item", "not", "in", "self", ".", "args", ":", "abort", "(", "400", ",", "\"Unknown argument item %s\"", "%", "item", ...
36.904762
18.857143
def add(self,attrlist,attrvalues): ''' add an attribute :parameter dimlist: list of dimensions :parameter dimvalues: list of values for dimlist ''' for i,d in enumerate(attrlist): self[d] = attrvalues[i]
[ "def", "add", "(", "self", ",", "attrlist", ",", "attrvalues", ")", ":", "for", "i", ",", "d", "in", "enumerate", "(", "attrlist", ")", ":", "self", "[", "d", "]", "=", "attrvalues", "[", "i", "]" ]
30.222222
15.111111
def send(self, item, timeout=-1): """ Send an *item* on this pair. This will block unless our Rever is ready, either forever or until *timeout* milliseconds. """ if not self.ready: self.pause(timeout=timeout) if isinstance(item, Exception): return...
[ "def", "send", "(", "self", ",", "item", ",", "timeout", "=", "-", "1", ")", ":", "if", "not", "self", ".", "ready", ":", "self", ".", "pause", "(", "timeout", "=", "timeout", ")", "if", "isinstance", "(", "item", ",", "Exception", ")", ":", "ret...
35
17
def create_from_name_and_dictionary(self, name, datas): """Return a populated object Parameter from dictionary datas """ parameter = ObjectParameter() self.set_common_datas(parameter, name, datas) if "optional" in datas: parameter.optional = to_boolean(datas["optiona...
[ "def", "create_from_name_and_dictionary", "(", "self", ",", "name", ",", "datas", ")", ":", "parameter", "=", "ObjectParameter", "(", ")", "self", ".", "set_common_datas", "(", "parameter", ",", "name", ",", "datas", ")", "if", "\"optional\"", "in", "datas", ...
36.071429
14.857143
def BuildServiceStub(self, cls): """Constructs the stub class. Args: cls: The class that will be constructed. """ def _ServiceStubInit(stub, rpc_channel): stub.rpc_channel = rpc_channel self.cls = cls cls.__init__ = _ServiceStubInit for method in self.descriptor.methods: ...
[ "def", "BuildServiceStub", "(", "self", ",", "cls", ")", ":", "def", "_ServiceStubInit", "(", "stub", ",", "rpc_channel", ")", ":", "stub", ".", "rpc_channel", "=", "rpc_channel", "self", ".", "cls", "=", "cls", "cls", ".", "__init__", "=", "_ServiceStubIn...
28.230769
14.384615
def store(self, prof_name, prof_type): """ Store a profile with the given name and type. :param str prof_name: Profile name. :param str prof_type: Profile type. """ prof_dir = self.__profile_dir(prof_name) prof_stub = self.__profile_stub(prof_name, prof_type, prof_dir) if not os.path.e...
[ "def", "store", "(", "self", ",", "prof_name", ",", "prof_type", ")", ":", "prof_dir", "=", "self", ".", "__profile_dir", "(", "prof_name", ")", "prof_stub", "=", "self", ".", "__profile_stub", "(", "prof_name", ",", "prof_type", ",", "prof_dir", ")", "if"...
27.457143
14.428571
def add_action(self, dash, dashdash, action_code): """Add a specialized option that is the action to execute.""" option = self.add_option(dash, dashdash, action='callback', callback=self._append_action ) option.action_code = action_code
[ "def", "add_action", "(", "self", ",", "dash", ",", "dashdash", ",", "action_code", ")", ":", "option", "=", "self", ".", "add_option", "(", "dash", ",", "dashdash", ",", "action", "=", "'callback'", ",", "callback", "=", "self", ".", "_append_action", "...
46.5
10.666667
def get_vnetwork_portgroups_input_name(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_vnetwork_portgroups = ET.Element("get_vnetwork_portgroups") config = get_vnetwork_portgroups input = ET.SubElement(get_vnetwork_portgroups, "input") ...
[ "def", "get_vnetwork_portgroups_input_name", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "get_vnetwork_portgroups", "=", "ET", ".", "Element", "(", "\"get_vnetwork_portgroups\"", ")", "config", "="...
39.666667
11.916667
def filter(self, result): """ Filter the specified result based on query criteria. @param result: A potential result. @type result: L{sxbase.SchemaObject} @return: True if result should be excluded. @rtype: boolean """ if result is None: return...
[ "def", "filter", "(", "self", ",", "result", ")", ":", "if", "result", "is", "None", ":", "return", "True", "reject", "=", "result", "in", "self", ".", "history", "if", "reject", ":", "log", ".", "debug", "(", "'result %s, rejected by\\n%s'", ",", "Repr"...
33.214286
12.357143
def calculate_embedding_output_shapes(operator): ''' Allowed input/output patterns are 1. [N, 1] ---> [N, C] 2. [N, 1, 1, 1] ---> [N, C, 1, 1] ''' check_input_and_output_numbers(operator, input_count_range=1, output_count_range=1) check_input_and_output_types(operator, good_input_typ...
[ "def", "calculate_embedding_output_shapes", "(", "operator", ")", ":", "check_input_and_output_numbers", "(", "operator", ",", "input_count_range", "=", "1", ",", "output_count_range", "=", "1", ")", "check_input_and_output_types", "(", "operator", ",", "good_input_types"...
38.24
25.68
def apply_actions(self, name_of_action, actions): """Start to execute an action or a group of actions. This method takes a bunch of actions and runs them on your Tahoma box. :param name_of_action: the label/name for the action :param actions: an array of Action objects ...
[ "def", "apply_actions", "(", "self", ",", "name_of_action", ",", "actions", ")", ":", "header", "=", "BASE_HEADERS", ".", "copy", "(", ")", "header", "[", "'Cookie'", "]", "=", "self", ".", "__cookie", "actions_serialized", "=", "[", "]", "for", "action", ...
30.207547
20.037736
def plot_welch_peaks(f, S, peak_loc=None, title=''): '''Plot welch PSD with peaks as scatter points Args ---- f: ndarray Array of frequencies produced with PSD S: ndarray Array of powers produced with PSD peak_loc: ndarray Indices of peak locations in signal title: s...
[ "def", "plot_welch_peaks", "(", "f", ",", "S", ",", "peak_loc", "=", "None", ",", "title", "=", "''", ")", ":", "plt", ".", "plot", "(", "f", ",", "S", ",", "linewidth", "=", "_linewidth", ")", "plt", ".", "title", "(", "title", ")", "plt", ".", ...
24.192308
19.807692
def prove(x,t,kw,y): """ Computes public key P*kw where <P> = G1. x, t, and y are ignored. They are included only for API compatibility with other Pythia PRF implementations. """ # Verify the key type and compute the pubkey assertScalarType(kw) p = generatorG2() * kw return (p,None...
[ "def", "prove", "(", "x", ",", "t", ",", "kw", ",", "y", ")", ":", "# Verify the key type and compute the pubkey", "assertScalarType", "(", "kw", ")", "p", "=", "generatorG2", "(", ")", "*", "kw", "return", "(", "p", ",", "None", ",", "None", ")" ]
31.7
12.1
def Then2(self, f, arg1, *args, **kwargs): """ `Then2(f, ...)` is equivalent to `ThenAt(2, f, ...)`. Checkout `phi.builder.Builder.ThenAt` for more information. """ args = (arg1,) + args return self.ThenAt(2, f, *args, **kwargs)
[ "def", "Then2", "(", "self", ",", "f", ",", "arg1", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "args", "=", "(", "arg1", ",", ")", "+", "args", "return", "self", ".", "ThenAt", "(", "2", ",", "f", ",", "*", "args", ",", "*", "*", ...
42.5
15.833333
def get_checkerboard_matrix(kernel_width, kernel_type="default", gaussian_param=0.1): """ example matrix for width = 2 -1 -1 1 1 -1 -1 1 1 1 1 -1 -1 1 1 -1 -1 :param kernel_type: :param kernel_width: :return: """ if kernel_type is "gaussian": ...
[ "def", "get_checkerboard_matrix", "(", "kernel_width", ",", "kernel_type", "=", "\"default\"", ",", "gaussian_param", "=", "0.1", ")", ":", "if", "kernel_type", "is", "\"gaussian\"", ":", "return", "get_gaussian_kernel", "(", "kernel_width", ",", "gaussian_param", "...
29.234043
26.425532
def or_(*validation_func # type: ValidationFuncs ): # type: (...) -> Callable """ An 'or' validator: returns `True` if at least one of the provided validators returns `True`. All exceptions will be silently caught. In case of failure, a global `AllValidatorsFailed` failure will be raised, toget...
[ "def", "or_", "(", "*", "validation_func", "# type: ValidationFuncs", ")", ":", "# type: (...) -> Callable", "validation_func", "=", "_process_validation_function_s", "(", "list", "(", "validation_func", ")", ",", "auto_and_wrapper", "=", "False", ")", "if", "len", "(...
45.973684
28.921053
def send(self, chat_id, msg_type, **kwargs): """ 应用推送消息 详情请参考:https://work.weixin.qq.com/api/doc#90000/90135/90248 :param chat_id: 群聊id :param msg_type: 消息类型,可以为text/image/voice/video/file/textcard/news/mpnews/markdown :param kwargs: 具体消息类型的扩展参数 :return: ...
[ "def", "send", "(", "self", ",", "chat_id", ",", "msg_type", ",", "*", "*", "kwargs", ")", ":", "data", "=", "{", "'chatid'", ":", "chat_id", ",", "'safe'", ":", "kwargs", ".", "get", "(", "'safe'", ")", "or", "0", "}", "data", ".", "update", "("...
31.058824
19.529412
def get_site_collection(oqparam): """ Returns a SiteCollection instance by looking at the points and the site model defined by the configuration parameters. :param oqparam: an :class:`openquake.commonlib.oqvalidation.OqParam` instance """ mesh = get_mesh(oqparam) req_site_params = g...
[ "def", "get_site_collection", "(", "oqparam", ")", ":", "mesh", "=", "get_mesh", "(", "oqparam", ")", "req_site_params", "=", "get_gsim_lt", "(", "oqparam", ")", ".", "req_site_params", "if", "oqparam", ".", "inputs", ".", "get", "(", "'site_model'", ")", ":...
42.039216
16.509804
def translate(translationAmt): """Create a translation matrix.""" if not isinstance(translationAmt, Vector3): raise ValueError("translationAmt must be a Vector3") ma4 = Matrix4((1, 0, 0, translationAmt.x), (0, 1, 0, translationAmt.y), (0, ...
[ "def", "translate", "(", "translationAmt", ")", ":", "if", "not", "isinstance", "(", "translationAmt", ",", "Vector3", ")", ":", "raise", "ValueError", "(", "\"translationAmt must be a Vector3\"", ")", "ma4", "=", "Matrix4", "(", "(", "1", ",", "0", ",", "0"...
39
14.2
def single_gate_params(gate, params=None): """Apply a single qubit gate to the qubit. Args: gate(str): the single qubit gate name params(list): the operation parameters op['params'] Returns: tuple: a tuple of U gate parameters (theta, phi, lam) Raises: QiskitError: if th...
[ "def", "single_gate_params", "(", "gate", ",", "params", "=", "None", ")", ":", "if", "gate", "in", "(", "'U'", ",", "'u3'", ")", ":", "return", "params", "[", "0", "]", ",", "params", "[", "1", "]", ",", "params", "[", "2", "]", "elif", "gate", ...
32.4
16.05
def _maybe_download_corpus(tmp_dir, vocab_type): """Download and unpack the corpus. Args: tmp_dir: directory containing dataset. vocab_type: which vocabulary are we using. Returns: The list of names of files. """ if vocab_type == text_problems.VocabType.CHARACTER: dataset_url = ("https://s3...
[ "def", "_maybe_download_corpus", "(", "tmp_dir", ",", "vocab_type", ")", ":", "if", "vocab_type", "==", "text_problems", ".", "VocabType", ".", "CHARACTER", ":", "dataset_url", "=", "(", "\"https://s3.amazonaws.com/research.metamind.io/wikitext\"", "\"/wikitext-103-raw-v1.z...
31.093023
18.093023
def generate(env): """Add Builders and construction variables for swig to an Environment.""" c_file, cxx_file = SCons.Tool.createCFileBuilders(env) c_file.suffix['.i'] = swigSuffixEmitter cxx_file.suffix['.i'] = swigSuffixEmitter c_file.add_action('.i', SwigAction) c_file.add_emitter('.i', _sw...
[ "def", "generate", "(", "env", ")", ":", "c_file", ",", "cxx_file", "=", "SCons", ".", "Tool", ".", "createCFileBuilders", "(", "env", ")", "c_file", ".", "suffix", "[", "'.i'", "]", "=", "swigSuffixEmitter", "cxx_file", ".", "suffix", "[", "'.i'", "]", ...
41.1875
18.59375
def search(self, project, text=''): """ Search in your Taiga.io instance :param project: the project id :param text: the query of your search """ result = self.raw_request.get( 'search', query={'project': project, 'text': text} ) result = resu...
[ "def", "search", "(", "self", ",", "project", ",", "text", "=", "''", ")", ":", "result", "=", "self", ".", "raw_request", ".", "get", "(", "'search'", ",", "query", "=", "{", "'project'", ":", "project", ",", "'text'", ":", "text", "}", ")", "resu...
34.857143
14.952381
def on_entry_click(self, event): """ function that gets called whenever entry is clicked """ if event.widget.config('fg') [4] == 'grey': event.widget.delete(0, "end" ) # delete all the text in the entry event.widget.insert(0, '') #Insert blank for user input event.widget.config(fg = 'black')
[ "def", "on_entry_click", "(", "self", ",", "event", ")", ":", "if", "event", ".", "widget", ".", "config", "(", "'fg'", ")", "[", "4", "]", "==", "'grey'", ":", "event", ".", "widget", ".", "delete", "(", "0", ",", "\"end\"", ")", "# delete all the t...
38.5
9.75
def impulse_response(self, impulse_length=30): """ Get the impulse response corresponding to our model. Returns ------- psi : array_like(float) psi[j] is the response at lag j of the impulse response. We take psi[0] as unity. """ from sci...
[ "def", "impulse_response", "(", "self", ",", "impulse_length", "=", "30", ")", ":", "from", "scipy", ".", "signal", "import", "dimpulse", "sys", "=", "self", ".", "ma_poly", ",", "self", ".", "ar_poly", ",", "1", "times", ",", "psi", "=", "dimpulse", "...
30.470588
18
def add_pv(self, device): """ Initializes a device as a physical volume and adds it to the volume group:: from lvm2py import * lvm = LVM() vg = lvm.get_vg("myvg", "w") vg.add_pv("/dev/sdbX") *Args:* * device (str): An existing d...
[ "def", "add_pv", "(", "self", ",", "device", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "device", ")", ":", "raise", "ValueError", "(", "\"%s does not exist.\"", "%", "device", ")", "self", ".", "open", "(", ")", "ext", "=", "lvm_v...
26.484848
21.757576
def async_or_fail(self, **options): """ Attempt to call self.apply_async, but if that fails with an exception, we fake the task completion using the exception as the result. This allows us to seamlessly handle errors on task creation the same way we handle errors when a task runs...
[ "def", "async_or_fail", "(", "self", ",", "*", "*", "options", ")", ":", "args", "=", "options", ".", "pop", "(", "\"args\"", ",", "None", ")", "kwargs", "=", "options", ".", "pop", "(", "\"kwargs\"", ",", "None", ")", "possible_broker_errors", "=", "s...
48.428571
17.285714
def dist(self, src, tar, probs=None): """Return the NCD between two strings using arithmetic coding. Parameters ---------- src : str Source string for comparison tar : str Target string for comparison probs : dict A dictionary trained ...
[ "def", "dist", "(", "self", ",", "src", ",", "tar", ",", "probs", "=", "None", ")", ":", "if", "src", "==", "tar", ":", "return", "0.0", "if", "probs", "is", "None", ":", "# lacking a reasonable dictionary, train on the strings themselves", "self", ".", "_co...
27.404255
18.276596
def to_btc(ccy, value, api_code=None): """Call the 'tobtc' method and convert x value in the provided currency to BTC. :param str ccy: currency code :param float value: value to convert :param str api_code: Blockchain.info API code :return: the value in BTC """ res = 'tobtc?currenc...
[ "def", "to_btc", "(", "ccy", ",", "value", ",", "api_code", "=", "None", ")", ":", "res", "=", "'tobtc?currency={0}&value={1}'", ".", "format", "(", "ccy", ",", "value", ")", "if", "api_code", "is", "not", "None", ":", "res", "+=", "'&api_code='", "+", ...
34.461538
10.615385
def satoshi_to_currency_cached(num, currency): """Converts a given number of satoshi to another currency as a formatted string rounded down to the proper number of decimal places. Results are cached using a decorator for 60 seconds by default. See :ref:`cache times`. :param num: The number of satoshi. ...
[ "def", "satoshi_to_currency_cached", "(", "num", ",", "currency", ")", ":", "return", "'{:f}'", ".", "format", "(", "Decimal", "(", "num", "/", "Decimal", "(", "currency_to_satoshi_cached", "(", "1", ",", "currency", ")", ")", ")", ".", "quantize", "(", "D...
36.578947
19.263158
def get_solarposition(self, times, pressure=None, temperature=12, **kwargs): """ Uses the :py:func:`solarposition.get_solarposition` function to calculate the solar zenith, azimuth, etc. at this location. Parameters ---------- times : DatetimeIn...
[ "def", "get_solarposition", "(", "self", ",", "times", ",", "pressure", "=", "None", ",", "temperature", "=", "12", ",", "*", "*", "kwargs", ")", ":", "if", "pressure", "is", "None", ":", "pressure", "=", "atmosphere", ".", "alt2pres", "(", "self", "."...
40.96875
22.40625
def p_InDecrement(p): ''' InDecrement : INDECREMENT Expression | Expression INDECREMENT ''' from .helper import isString if isString(p[1]): p[0] = InDecrement(p[1], p[2], False) else: p[0] = InDecrement(p[2], p[1], True)
[ "def", "p_InDecrement", "(", "p", ")", ":", "from", ".", "helper", "import", "isString", "if", "isString", "(", "p", "[", "1", "]", ")", ":", "p", "[", "0", "]", "=", "InDecrement", "(", "p", "[", "1", "]", ",", "p", "[", "2", "]", ",", "Fals...
26.7
15.1
def get_filedata(self, condition=None, page_size=1000): """Return a generator over all results matching the provided condition :param condition: An :class:`.Expression` which defines the condition which must be matched on the filedata that will be retrieved from file data store....
[ "def", "get_filedata", "(", "self", ",", "condition", "=", "None", ",", "page_size", "=", "1000", ")", ":", "condition", "=", "validate_type", "(", "condition", ",", "type", "(", "None", ")", ",", "Expression", ",", "*", "six", ".", "string_types", ")", ...
55.96
29.92
def iter_org_issues(self, name, filter='', state='', labels='', sort='', direction='', since=None, number=-1, etag=None): """Iterate over the organnization's issues if the authenticated user belongs to it. :param str name: (required), name of the organization :pa...
[ "def", "iter_org_issues", "(", "self", ",", "name", ",", "filter", "=", "''", ",", "state", "=", "''", ",", "labels", "=", "''", ",", "sort", "=", "''", ",", "direction", "=", "''", ",", "since", "=", "None", ",", "number", "=", "-", "1", ",", ...
51.612903
19.516129
def operations_contain_expected_statuses(operations, expected_statuses): """ Checks whether the operation list has an operation with the expected status, then returns true If it encounters operations in FAILED or ABORTED state throw :class:`airflow.exceptions.AirflowException`. ...
[ "def", "operations_contain_expected_statuses", "(", "operations", ",", "expected_statuses", ")", ":", "expected_statuses", "=", "(", "{", "expected_statuses", "}", "if", "isinstance", "(", "expected_statuses", ",", "six", ".", "string_types", ")", "else", "set", "("...
43.351351
24.864865
def count_quota_handler_factory(count_quota_field): """ Creates handler that will recalculate count_quota on creation/deletion """ def recalculate_count_quota(sender, instance, **kwargs): signal = kwargs['signal'] if signal == signals.post_save and kwargs.get('created'): count_quota...
[ "def", "count_quota_handler_factory", "(", "count_quota_field", ")", ":", "def", "recalculate_count_quota", "(", "sender", ",", "instance", ",", "*", "*", "kwargs", ")", ":", "signal", "=", "kwargs", "[", "'signal'", "]", "if", "signal", "==", "signals", ".", ...
45.909091
19
def get(code): """ Return an object that corresponds to the given EPSG code. Currently supported object types are: - :class:`GeodeticCRS` - :class:`ProjectedCRS` - :class:`CartesianCS` - :class:`UOM` For example:: >>> print(get(27700)) <ProjectedCRS: 27...
[ "def", "get", "(", "code", ")", ":", "instance", "=", "_cache", ".", "get", "(", "code", ")", "if", "instance", "is", "None", ":", "url", "=", "'{prefix}{code}.gml?download'", ".", "format", "(", "prefix", "=", "EPSG_IO_URL", ",", "code", "=", "code", ...
33.102564
16.74359
def supply_and_demand( lcm, choosers, alternatives, alt_segmenter, price_col, base_multiplier=None, clip_change_low=0.75, clip_change_high=1.25, iterations=5, multiplier_func=None): """ Adjust real estate prices to compensate for supply and demand effects. Parameters ---------- ...
[ "def", "supply_and_demand", "(", "lcm", ",", "choosers", ",", "alternatives", ",", "alt_segmenter", ",", "price_col", ",", "base_multiplier", "=", "None", ",", "clip_change_low", "=", "0.75", ",", "clip_change_high", "=", "1.25", ",", "iterations", "=", "5", "...
44.5
21.388889
def get_groups(self): """Get groups via provisioning API. If you get back an error 999, then the provisioning API is not enabled. :returns: list of groups :raises: HTTPResponseError in case an HTTP error status was returned """ res = self._make_ocs_request( ...
[ "def", "get_groups", "(", "self", ")", ":", "res", "=", "self", ".", "_make_ocs_request", "(", "'GET'", ",", "self", ".", "OCS_SERVICE_CLOUD", ",", "'groups'", ")", "if", "res", ".", "status_code", "==", "200", ":", "tree", "=", "ET", ".", "fromstring", ...
28.333333
21.285714
def quick_response(self, status_code): """ Quickly construct response using a status code """ translator = Translator(environ=self.environ) if status_code == 404: self.status(404) self.message(translator.trans('http_messages.404')) elif status_code == 401: ...
[ "def", "quick_response", "(", "self", ",", "status_code", ")", ":", "translator", "=", "Translator", "(", "environ", "=", "self", ".", "environ", ")", "if", "status_code", "==", "404", ":", "self", ".", "status", "(", "404", ")", "self", ".", "message", ...
43.8
12.266667
def get_kwargs_index(target) -> int: """ Returns the index of the "**kwargs" parameter if such a parameter exists in the function arguments or -1 otherwise. :param target: The target function for which the kwargs index should be determined :return: The keyword arguments index if it ...
[ "def", "get_kwargs_index", "(", "target", ")", "->", "int", ":", "code", "=", "target", ".", "__code__", "if", "not", "bool", "(", "code", ".", "co_flags", "&", "inspect", ".", "CO_VARKEYWORDS", ")", ":", "return", "-", "1", "return", "(", "code", ".",...
27.047619
22.190476
def get_topic_keyword_dictionary(): """ Opens the topic-keyword map resource file and returns the corresponding python dictionary. - Input: - file_path: The path pointing to the topic-keyword map resource file. - Output: - topic_set: A topic to keyword python dictionary. """ topic_keyword_dic...
[ "def", "get_topic_keyword_dictionary", "(", ")", ":", "topic_keyword_dictionary", "=", "dict", "(", ")", "file_row_gen", "=", "get_file_row_generator", "(", "get_package_path", "(", ")", "+", "\"/twitter/res/topics/topic_keyword_mapping\"", "+", "\".txt\"", ",", "\",\"", ...
43.625
25.25
def jpegrescan(ext_args): """Run the EXTERNAL program jpegrescan.""" args = copy.copy(_JPEGRESCAN_ARGS) if Settings.jpegrescan_multithread: args += ['-t'] if Settings.destroy_metadata: args += ['-s'] args += [ext_args.old_filename, ext_args.new_filename] extern.run_ext(args) ...
[ "def", "jpegrescan", "(", "ext_args", ")", ":", "args", "=", "copy", ".", "copy", "(", "_JPEGRESCAN_ARGS", ")", "if", "Settings", ".", "jpegrescan_multithread", ":", "args", "+=", "[", "'-t'", "]", "if", "Settings", ".", "destroy_metadata", ":", "args", "+...
33
11.2
def get_image(self, image_id_or_slug): """ Return a Image by its ID/Slug. """ return Image.get_object( api_token=self.token, image_id_or_slug=image_id_or_slug, )
[ "def", "get_image", "(", "self", ",", "image_id_or_slug", ")", ":", "return", "Image", ".", "get_object", "(", "api_token", "=", "self", ".", "token", ",", "image_id_or_slug", "=", "image_id_or_slug", ",", ")" ]
27.75
7
def _get_sentences_dict(self): """ Returns sentence objects :return: order dict of sentences :rtype: collections.OrderedDict """ if self._sentences_dict is None: sentences = [Sentence(element) for element in self._xml.xpath('/root/document/sentences/sentence...
[ "def", "_get_sentences_dict", "(", "self", ")", ":", "if", "self", ".", "_sentences_dict", "is", "None", ":", "sentences", "=", "[", "Sentence", "(", "element", ")", "for", "element", "in", "self", ".", "_xml", ".", "xpath", "(", "'/root/document/sentences/s...
35.583333
17.75
def delete_library_value(self, key: str) -> None: """Delete the library value for the given key. Please consult the developer documentation for a list of valid keys. .. versionadded:: 1.0 Scriptable: Yes """ desc = Metadata.session_key_map.get(key) if desc is n...
[ "def", "delete_library_value", "(", "self", ",", "key", ":", "str", ")", "->", "None", ":", "desc", "=", "Metadata", ".", "session_key_map", ".", "get", "(", "key", ")", "if", "desc", "is", "not", "None", ":", "field_id", "=", "desc", "[", "'path'", ...
32
19.533333
def _sample_item(self, **kwargs): """Sample an item from the pool according to the instrumental distribution """ t = self.t_ # Update instrumental distribution self._calc_inst_pmf() if self.record_inst_hist: inst_pmf = self._inst_pmf[:,t] els...
[ "def", "_sample_item", "(", "self", ",", "*", "*", "kwargs", ")", ":", "t", "=", "self", ".", "t_", "# Update instrumental distribution", "self", ".", "_calc_inst_pmf", "(", ")", "if", "self", ".", "record_inst_hist", ":", "inst_pmf", "=", "self", ".", "_i...
30.157895
17.105263
def control_loop(): '''Main loop, updating the capture agent state. ''' set_service_status(Service.AGENTSTATE, ServiceStatus.BUSY) notify.notify('READY=1') notify.notify('STATUS=Running') while not terminate(): notify.notify('WATCHDOG=1') update_agent_state() next_update...
[ "def", "control_loop", "(", ")", ":", "set_service_status", "(", "Service", ".", "AGENTSTATE", ",", "ServiceStatus", ".", "BUSY", ")", "notify", ".", "notify", "(", "'READY=1'", ")", "notify", ".", "notify", "(", "'STATUS=Running'", ")", "while", "not", "ter...
35.4375
19.8125
def round_up(self, num): """Determine the length to use for this waveform by rounding. Parameters ---------- num : int Proposed size of waveform in seconds Returns ------- size: int The rounded size to use for the waveform buffer in secon...
[ "def", "round_up", "(", "self", ",", "num", ")", ":", "inc", "=", "self", ".", "increment", "size", "=", "np", ".", "ceil", "(", "num", "/", "self", ".", "sample_rate", "/", "inc", ")", "*", "self", ".", "sample_rate", "*", "inc", "return", "size" ...
31.722222
21.611111
def render(self, name, value, attrs=None, multi=False, renderer=None): """ Django <= 1.10 variant. """ DJANGO_111_OR_UP = (VERSION[0] == 1 and VERSION[1] >= 11) or ( VERSION[0] >= 2 ) if DJANGO_111_OR_UP: return super(DynamicRawIDWidget, self).rend...
[ "def", "render", "(", "self", ",", "name", ",", "value", ",", "attrs", "=", "None", ",", "multi", "=", "False", ",", "renderer", "=", "None", ")", ":", "DJANGO_111_OR_UP", "=", "(", "VERSION", "[", "0", "]", "==", "1", "and", "VERSION", "[", "1", ...
30.777778
18.037037
def increment_extension_daily_stat(self, publisher_name, extension_name, version, stat_type): """IncrementExtensionDailyStat. [Preview API] Increments a daily statistic associated with the extension :param str publisher_name: Name of the publisher :param str extension_name: Name of the e...
[ "def", "increment_extension_daily_stat", "(", "self", ",", "publisher_name", ",", "extension_name", ",", "version", ",", "stat_type", ")", ":", "route_values", "=", "{", "}", "if", "publisher_name", "is", "not", "None", ":", "route_values", "[", "'publisherName'",...
55.304348
20.782609
def listdir(search_base, followlinks=False, filter='*', relpath=False, bestprefix=False, system=NIST): """This is a generator which recurses the directory tree `search_base`, yielding 2-tuples of: * The absolute/relative path to a discovered file * A bitmath instance representing the "apparent size" of...
[ "def", "listdir", "(", "search_base", ",", "followlinks", "=", "False", ",", "filter", "=", "'*'", ",", "relpath", "=", "False", ",", "bestprefix", "=", "False", ",", "system", "=", "NIST", ")", ":", "for", "root", ",", "dirs", ",", "files", "in", "o...
43
22.536585
def connect_async(self, connection_id, connection_string, callback, retries=4): """Connect to a device by its connection_string This function asynchronously connects to a device by its BLE address passed in the connection_string parameter and calls callback when finished. Callback is called ...
[ "def", "connect_async", "(", "self", ",", "connection_id", ",", "connection_string", ",", "callback", ",", "retries", "=", "4", ")", ":", "context", "=", "{", "}", "context", "[", "'connection_id'", "]", "=", "connection_id", "context", "[", "'callback'", "]...
50.794872
31.820513
def search_repositories(query, sort=None, order=None, per_page=None, text_match=False, number=-1, etag=None): """Find repositories via various criteria. .. warning:: You will only be able to make 5 calls with this or other search functions. To raise the rate-limit on th...
[ "def", "search_repositories", "(", "query", ",", "sort", "=", "None", ",", "order", "=", "None", ",", "per_page", "=", "None", ",", "text_match", "=", "False", ",", "number", "=", "-", "1", ",", "etag", "=", "None", ")", ":", "return", "gh", ".", "...
47.76
25.54
def SoS_exec(script: str, _dict: dict = None, return_result: bool = True) -> None: '''Execute a statement.''' if _dict is None: _dict = env.sos_dict.dict() if not return_result: exec( compile(script, filename=stmtHash.hash(script), mode='exec'), _dict) retur...
[ "def", "SoS_exec", "(", "script", ":", "str", ",", "_dict", ":", "dict", "=", "None", ",", "return_result", ":", "bool", "=", "True", ")", "->", "None", ":", "if", "_dict", "is", "None", ":", "_dict", "=", "env", ".", "sos_dict", ".", "dict", "(", ...
34.309524
18.357143