text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def register_user(self, user, allow_login=None, send_email=None, _force_login_without_confirmation=False): """ Service method to register a user. Sends signal `user_registered`. Returns True if the user has been logged in, False otherwise. """ shou...
[ "def", "register_user", "(", "self", ",", "user", ",", "allow_login", "=", "None", ",", "send_email", "=", "None", ",", "_force_login_without_confirmation", "=", "False", ")", ":", "should_login_user", "=", "(", "not", "self", ".", "security", ".", "confirmabl...
44.595238
22.880952
def save(self): """ :return: save this routing area on Ariane server (create or update) """ LOGGER.debug("RoutingArea.save") post_payload = {} consolidated_loc_id = [] if self.id is not None: post_payload['routingAreaID'] = self.id if self.na...
[ "def", "save", "(", "self", ")", ":", "LOGGER", ".", "debug", "(", "\"RoutingArea.save\"", ")", "post_payload", "=", "{", "}", "consolidated_loc_id", "=", "[", "]", "if", "self", ".", "id", "is", "not", "None", ":", "post_payload", "[", "'routingAreaID'", ...
37.716667
17.483333
def connect(self, obj, network): """Connect to the specified AP.""" network_summary = self._send_cmd_to_wpas( obj['name'], 'LIST_NETWORKS', True) network_summary = network_summary[:-1].split('\n') if len(network_summary) == 1: return netwo...
[ "def", "connect", "(", "self", ",", "obj", ",", "network", ")", ":", "network_summary", "=", "self", ".", "_send_cmd_to_wpas", "(", "obj", "[", "'name'", "]", ",", "'LIST_NETWORKS'", ",", "True", ")", "network_summary", "=", "network_summary", "[", ":", "-...
33.222222
13.888889
def apply(self, function): """ For each row or column in cuts, read a list of its colors, apply the function to that list of colors, then write it back to the layout. """ for cut in self.cuts: value = self.read(cut) function(value) self...
[ "def", "apply", "(", "self", ",", "function", ")", ":", "for", "cut", "in", "self", ".", "cuts", ":", "value", "=", "self", ".", "read", "(", "cut", ")", "function", "(", "value", ")", "self", ".", "write", "(", "cut", ",", "value", ")" ]
32.9
12.3
def post(self, path, args, wait=False): """POST an HTTP request to a daemon :param path: path to do the request :type path: str :param args: args to add in the request :type args: dict :param wait: True for a long timeout :type wait: bool :return: Content...
[ "def", "post", "(", "self", ",", "path", ",", "args", ",", "wait", "=", "False", ")", ":", "uri", "=", "self", ".", "make_uri", "(", "path", ")", "timeout", "=", "self", ".", "make_timeout", "(", "wait", ")", "for", "(", "key", ",", "value", ")",...
44.586207
16.931034
def _update_classmethod(self, oldcm, newcm): """Update a classmethod update.""" # While we can't modify the classmethod object itself (it has no # mutable attributes), we *can* extract the underlying function # (by calling __get__(), which returns a method object) and update # it...
[ "def", "_update_classmethod", "(", "self", ",", "oldcm", ",", "newcm", ")", ":", "# While we can't modify the classmethod object itself (it has no", "# mutable attributes), we *can* extract the underlying function", "# (by calling __get__(), which returns a method object) and update", "# i...
61.75
21.5
def check_uniqueness(self, *args): """For a unique index, check if the given args are not used twice For the parameters, seen BaseIndex.check_uniqueness """ self.get_unique_index().check_uniqueness(*self.prepare_args(args, transform=False))
[ "def", "check_uniqueness", "(", "self", ",", "*", "args", ")", ":", "self", ".", "get_unique_index", "(", ")", ".", "check_uniqueness", "(", "*", "self", ".", "prepare_args", "(", "args", ",", "transform", "=", "False", ")", ")" ]
38.285714
22.285714
def update(self, *args, **kwargs): ''' Updates multiple attributes in a model. If ``args`` are provided, this method will assign attributes in the order returned by ``list(self._columns)`` until one or both are exhausted. If ``kwargs`` are provided, this method will assign attri...
[ "def", "update", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "sa", "=", "setattr", "for", "a", ",", "v", "in", "zip", "(", "self", ".", "_columns", ",", "args", ")", ":", "sa", "(", "self", ",", "a", ",", "v", ")", "fo...
37.8
21.533333
def utime(self, *args, **kwargs): """ Set the access and modified times of the file specified by path. """ os.utime(self.extended_path, *args, **kwargs)
[ "def", "utime", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "os", ".", "utime", "(", "self", ".", "extended_path", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
55.333333
6.666667
def python_value(self, dtype, dvalue): """Convert a CLIPS type into Python.""" try: return CONVERTERS[dtype](dvalue) except KeyError: if dtype == clips.common.CLIPSType.MULTIFIELD: return self.multifield_to_list() if dtype == clips.common.CLIPS...
[ "def", "python_value", "(", "self", ",", "dtype", ",", "dvalue", ")", ":", "try", ":", "return", "CONVERTERS", "[", "dtype", "]", "(", "dvalue", ")", "except", "KeyError", ":", "if", "dtype", "==", "clips", ".", "common", ".", "CLIPSType", ".", "MULTIF...
44
19.923077
def _hyphens_to_dashes(self): """Transform hyphens to various kinds of dashes""" problematic_hyphens = [(r'-([.,!)])', r'---\1'), (r'(?<=\d)-(?=\d)', '--'), (r'(?<=\s)-(?=\s)', '---')] for problem_case in problematic_hyphens: self._...
[ "def", "_hyphens_to_dashes", "(", "self", ")", ":", "problematic_hyphens", "=", "[", "(", "r'-([.,!)])'", ",", "r'---\\1'", ")", ",", "(", "r'(?<=\\d)-(?=\\d)'", ",", "'--'", ")", ",", "(", "r'(?<=\\s)-(?=\\s)'", ",", "'---'", ")", "]", "for", "problem_case", ...
38.222222
16.666667
def unpublish_view(self, request, object_id): """ Instantiates a class-based view that redirects to Wagtail's 'unpublish' view for models that extend 'Page' (if the user has sufficient permissions). We do this via our own view so that we can reliably control redirection of the us...
[ "def", "unpublish_view", "(", "self", ",", "request", ",", "object_id", ")", ":", "kwargs", "=", "{", "'model_admin'", ":", "self", ",", "'object_id'", ":", "object_id", "}", "view_class", "=", "self", ".", "unpublish_view_class", "return", "view_class", ".", ...
53.583333
18.416667
def get_weights_of_nn_sites(self, structure, n): """ Get weight associated with each near neighbor of site with index n in structure. Args: structure (Structure): input structure. n (integer): index of site for which to determine the weights. Returns: ...
[ "def", "get_weights_of_nn_sites", "(", "self", ",", "structure", ",", "n", ")", ":", "return", "[", "e", "[", "'weight'", "]", "for", "e", "in", "self", ".", "get_nn_info", "(", "structure", ",", "n", ")", "]" ]
34.384615
20.692308
def distance_strength_of_connection(A, V, theta=2.0, relative_drop=True): """Distance based strength-of-connection. Parameters ---------- A : csr_matrix or bsr_matrix Square, sparse matrix in CSR or BSR format V : array Coordinates of the vertices of the graph of A relative_drop...
[ "def", "distance_strength_of_connection", "(", "A", ",", "V", ",", "theta", "=", "2.0", ",", "relative_drop", "=", "True", ")", ":", "# Amalgamate for the supernode case", "if", "sparse", ".", "isspmatrix_bsr", "(", "A", ")", ":", "sn", "=", "int", "(", "A",...
34.776471
22.494118
def render_dynamic_electrode_state_shapes(self): ''' Render **dynamic** states reported by the electrode controller. **Dynamic** electrode states are only applied while a protocol is running -- _not_ while in real-time programming mode. See also :meth:`render_electrode_shapes()...
[ "def", "render_dynamic_electrode_state_shapes", "(", "self", ")", ":", "df_shapes", "=", "self", ".", "canvas", ".", "df_canvas_shapes", ".", "copy", "(", ")", "# Only include shapes for electrodes reported as actuated.", "on_electrodes", "=", "self", ".", "_dynamic_elect...
42.791667
25.458333
def remove_lb_nodes(self, lb_id, node_ids): """ Remove one or more nodes :param string lb_id: Balancer id :param list node_ids: List of node ids """ log.info("Removing load balancer nodes %s" % node_ids) for node_id in node_ids: self._request('dele...
[ "def", "remove_lb_nodes", "(", "self", ",", "lb_id", ",", "node_ids", ")", ":", "log", ".", "info", "(", "\"Removing load balancer nodes %s\"", "%", "node_ids", ")", "for", "node_id", "in", "node_ids", ":", "self", ".", "_request", "(", "'delete'", ",", "'/l...
33
15.727273
def evaluate(condition): """ Evaluate simple condition. >>> Condition.evaluate(' 2 == 2 ') True >>> Condition.evaluate(' not 2 == 2 ') False >>> Condition.evaluate(' not "abc" == "xyz" ') True >>> Condition.evaluate('2 in [2, 4, 6, 8...
[ "def", "evaluate", "(", "condition", ")", ":", "success", "=", "False", "if", "len", "(", "condition", ")", ">", "0", ":", "try", ":", "rule_name", ",", "ast_tokens", ",", "evaluate_function", "=", "Condition", ".", "find_rule", "(", "condition", ")", "i...
32.605263
21.763158
def _TryPrintAsAnyMessage(self, message): """Serializes if message is a google.protobuf.Any field.""" packed_message = _BuildMessageFromTypeName(message.TypeName(), self.descriptor_pool) if packed_message: packed_message.MergeFromString(message.value) ...
[ "def", "_TryPrintAsAnyMessage", "(", "self", ",", "message", ")", ":", "packed_message", "=", "_BuildMessageFromTypeName", "(", "message", ".", "TypeName", "(", ")", ",", "self", ".", "descriptor_pool", ")", "if", "packed_message", ":", "packed_message", ".", "M...
44.166667
17.916667
def _vax_to_ieee_single_float(data): """Converts a float in Vax format to IEEE format. data should be a single string of chars that have been read in from a binary file. These will be processed 4 at a time into float values. Thus the total number of byte/chars in the string should be divisible by 4...
[ "def", "_vax_to_ieee_single_float", "(", "data", ")", ":", "f", "=", "[", "]", "nfloat", "=", "int", "(", "len", "(", "data", ")", "/", "4", ")", "for", "i", "in", "range", "(", "nfloat", ")", ":", "byte2", "=", "data", "[", "0", "+", "i", "*",...
32.16
23.2
def analytic(input_type, output_type): """Define an *analytic* user-defined function that takes N pandas Series or scalar values as inputs and produces N rows of output. Parameters ---------- input_type : List[ibis.expr.datatypes.DataType] A list of the types found i...
[ "def", "analytic", "(", "input_type", ",", "output_type", ")", ":", "return", "udf", ".", "_grouped", "(", "input_type", ",", "output_type", ",", "base_class", "=", "ops", ".", "AnalyticOp", ",", "output_type_method", "=", "operator", ".", "attrgetter", "(", ...
40.071429
19.392857
def _render_internal_label(self): ''' Render with a label inside the bar graph. ''' ncc = self._num_complete_chars bar = self._lbl.center(self.iwidth) cm_chars = self._comp_style(bar[:ncc]) em_chars = self._empt_style(bar[ncc:]) return f'{self._first}{cm_chars}{em_chars}{...
[ "def", "_render_internal_label", "(", "self", ")", ":", "ncc", "=", "self", ".", "_num_complete_chars", "bar", "=", "self", ".", "_lbl", ".", "center", "(", "self", ".", "iwidth", ")", "cm_chars", "=", "self", ".", "_comp_style", "(", "bar", "[", ":", ...
46.571429
9.142857
def _setHeaders(self, request): """ Those headers will allow you to call API methods from web browsers, they require CORS: https://en.wikipedia.org/wiki/Cross-origin_resource_sharing """ request.responseHeaders.addRawHeader(b'content-type', b'application/json') reques...
[ "def", "_setHeaders", "(", "self", ",", "request", ")", ":", "request", ".", "responseHeaders", ".", "addRawHeader", "(", "b'content-type'", ",", "b'application/json'", ")", "request", ".", "responseHeaders", ".", "addRawHeader", "(", "b'Access-Control-Allow-Origin'",...
63.909091
34.090909
def scan_for_valid_codon(codon_span, strand, seqid, genome, type='start'): """ Given a codon span, strand and reference seqid, scan upstream/downstream to find a valid in-frame start/stop codon """ s, e = codon_span[0], codon_span[1] while True: if (type == 'start' and strand == '+') or ...
[ "def", "scan_for_valid_codon", "(", "codon_span", ",", "strand", ",", "seqid", ",", "genome", ",", "type", "=", "'start'", ")", ":", "s", ",", "e", "=", "codon_span", "[", "0", "]", ",", "codon_span", "[", "1", "]", "while", "True", ":", "if", "(", ...
37.533333
16.8
def prune_unspecified_categories(modules, categories): """ Removes unspecified module categories. Mutates dictionary and returns it. """ res = {} for mod_name, mod_info in modules.items(): mod_categories = mod_info.get("categories", all_categories) for category in categories: ...
[ "def", "prune_unspecified_categories", "(", "modules", ",", "categories", ")", ":", "res", "=", "{", "}", "for", "mod_name", ",", "mod_info", "in", "modules", ".", "items", "(", ")", ":", "mod_categories", "=", "mod_info", ".", "get", "(", "\"categories\"", ...
34.518519
13.333333
def to_snake_case(text): """Convert to snake case. :param str text: :rtype: str :return: """ s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', text) return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower()
[ "def", "to_snake_case", "(", "text", ")", ":", "s1", "=", "re", ".", "sub", "(", "'(.)([A-Z][a-z]+)'", ",", "r'\\1_\\2'", ",", "text", ")", "return", "re", ".", "sub", "(", "'([a-z0-9])([A-Z])'", ",", "r'\\1_\\2'", ",", "s1", ")", ".", "lower", "(", ")...
24.222222
17.777778
def _build_ds_from_instruction(instruction, ds_from_file_fn): """Map an instruction to a real datasets for one particular shard. Args: instruction: A `dict` of `tf.Tensor` containing the instruction to load the particular shard (filename, mask,...) ds_from_file_fn: `fct`, function which returns the d...
[ "def", "_build_ds_from_instruction", "(", "instruction", ",", "ds_from_file_fn", ")", ":", "# Create the example and mask ds for this particular shard", "examples_ds", "=", "ds_from_file_fn", "(", "instruction", "[", "\"filepath\"", "]", ")", "mask_ds", "=", "_build_mask_ds",...
35.230769
19.576923
def add(self, name, attributes): """ Add the relation to the Schema. :param name: The name of a relation. :param attributes: A list of attributes for the relation. :raise RelationReferenceError: Raised if the name already exists. """ if name in self._data: ...
[ "def", "add", "(", "self", ",", "name", ",", "attributes", ")", ":", "if", "name", "in", "self", ".", "_data", ":", "raise", "RelationReferenceError", "(", "'Relation \\'{name}\\' already exists.'", ".", "format", "(", "name", "=", "name", ")", ")", "self", ...
41.636364
10.363636
def color_electrodes(self, config_nr, ax): """ Color the electrodes used in specific configuration. Voltage electrodes are yellow, Current electrodes are red ?! """ electrodes = np.loadtxt(options.config_file, skiprows=1) electrodes = self.configs[~np.isnan(self.configs)....
[ "def", "color_electrodes", "(", "self", ",", "config_nr", ",", "ax", ")", ":", "electrodes", "=", "np", ".", "loadtxt", "(", "options", ".", "config_file", ",", "skiprows", "=", "1", ")", "electrodes", "=", "self", ".", "configs", "[", "~", "np", ".", ...
40.238095
12.904762
def _get_attribute(self, attribute, name): """Device attribute getter""" try: if attribute is None: attribute = self._attribute_file_open( name ) else: attribute.seek(0) return attribute, attribute.read().strip().decode() except...
[ "def", "_get_attribute", "(", "self", ",", "attribute", ",", "name", ")", ":", "try", ":", "if", "attribute", "is", "None", ":", "attribute", "=", "self", ".", "_attribute_file_open", "(", "name", ")", "else", ":", "attribute", ".", "seek", "(", "0", "...
38.4
13.5
def as_cql_query(self, formatted=False): """ Returns a CQL query that can be used to recreate this type. If `formatted` is set to :const:`True`, extra whitespace will be added to make the query more readable. """ ret = "CREATE TYPE %s.%s (%s" % ( protect_name(...
[ "def", "as_cql_query", "(", "self", ",", "formatted", "=", "False", ")", ":", "ret", "=", "\"CREATE TYPE %s.%s (%s\"", "%", "(", "protect_name", "(", "self", ".", "keyspace", ")", ",", "protect_name", "(", "self", ".", "name", ")", ",", "\"\\n\"", "if", ...
34.24
17.68
def fetch(self, value_obj=None): ''' Fetch the next two values ''' val = None try: val = next(self.__iterable) except StopIteration: return None if value_obj is None: value_obj = Value(value=val) else: value_obj.value = val ...
[ "def", "fetch", "(", "self", ",", "value_obj", "=", "None", ")", ":", "val", "=", "None", "try", ":", "val", "=", "next", "(", "self", ".", "__iterable", ")", "except", "StopIteration", ":", "return", "None", "if", "value_obj", "is", "None", ":", "va...
27.75
12.416667
def _encode_auth(auth): """ A function compatible with Python 2.3-3.3 that will encode auth from a URL suitable for an HTTP header. >>> _encode_auth('username%3Apassword') u'dXNlcm5hbWU6cGFzc3dvcmQ=' """ auth_s = urllib2.unquote(auth) # convert to bytes auth_bytes = auth_s.encode() ...
[ "def", "_encode_auth", "(", "auth", ")", ":", "auth_s", "=", "urllib2", ".", "unquote", "(", "auth", ")", "# convert to bytes", "auth_bytes", "=", "auth_s", ".", "encode", "(", ")", "# use the legacy interface for Python 2.3 support", "encoded_bytes", "=", "base64",...
34.125
8.875
def direct_command(self, device_id, command, command2, extended_payload=None): """Wrapper to send posted direct command and get response. Level is 0-100. extended_payload is 14 bytes/28 chars..but last 2 chars is a generated checksum so leave off""" extended_payload = extended_payload or '' ...
[ "def", "direct_command", "(", "self", ",", "device_id", ",", "command", ",", "command2", ",", "extended_payload", "=", "None", ")", ":", "extended_payload", "=", "extended_payload", "or", "''", "if", "not", "extended_payload", ":", "msg_type", "=", "'0'", "msg...
47.133333
18.755556
def query_os_kernel_log(self, max_messages): """Tries to get the kernel log (dmesg) of the guest OS. in max_messages of type int Max number of messages to return, counting from the end of the log. If 0, there is no limit. return dmesg of type str The kernel...
[ "def", "query_os_kernel_log", "(", "self", ",", "max_messages", ")", ":", "if", "not", "isinstance", "(", "max_messages", ",", "baseinteger", ")", ":", "raise", "TypeError", "(", "\"max_messages can only be an instance of type baseinteger\"", ")", "dmesg", "=", "self"...
35.9375
17.0625
def collect_random_trajectory(env, timesteps=1000): """Run a random policy to collect trajectories. The rollout trajectory is saved to files in npz format. Modify the DataCollectionWrapper wrapper to add new fields or change data formats. """ obs = env.reset() dof = env.dof for t in range...
[ "def", "collect_random_trajectory", "(", "env", ",", "timesteps", "=", "1000", ")", ":", "obs", "=", "env", ".", "reset", "(", ")", "dof", "=", "env", ".", "dof", "for", "t", "in", "range", "(", "timesteps", ")", ":", "action", "=", "0.5", "*", "np...
29.9375
19.8125
def _generate_event_resources(self, lambda_function, execution_role, event_resources, lambda_alias=None): """Generates and returns the resources associated with this function's events. :param model.lambda_.LambdaFunction lambda_function: generated Lambda function :param iam.IAMRole execution_ro...
[ "def", "_generate_event_resources", "(", "self", ",", "lambda_function", ",", "execution_role", ",", "event_resources", ",", "lambda_alias", "=", "None", ")", ":", "resources", "=", "[", "]", "if", "self", ".", "Events", ":", "for", "logical_id", ",", "event_d...
53.235294
32.205882
def create_release_branch(self, branch_name): """ Create a new release branch. :param branch_name: The name of the release branch to create (a string). :raises: The following exceptions can be raised: - :exc:`~exceptions.TypeError` when :attr:`release_scheme` ...
[ "def", "create_release_branch", "(", "self", ",", "branch_name", ")", ":", "# Validate the release scheme.", "self", ".", "ensure_release_scheme", "(", "'branches'", ")", "# Validate the name of the release branch.", "if", "self", ".", "compiled_filter", ".", "match", "("...
46.941176
19.647059
def append_tz_time_only(self, tag, timestamp=None, precision=3, header=False): """Append a field with a TZTimeOnly value. :param tag: Integer or string FIX tag number. :param timestamp: Time value, see below. :param precision: Number of decimal places: 0, 3 (...
[ "def", "append_tz_time_only", "(", "self", ",", "tag", ",", "timestamp", "=", "None", ",", "precision", "=", "3", ",", "header", "=", "False", ")", ":", "if", "timestamp", "is", "None", ":", "t", "=", "datetime", ".", "datetime", ".", "now", "(", ")"...
40.191489
18.829787
def history_date(soup, date_type = None): """ Find a date in the history tag for the specific date_type typical date_type values: received, accepted """ if(date_type == None): return None history_date = raw_parser.history_date(soup, date_type) if history_date is None: return...
[ "def", "history_date", "(", "soup", ",", "date_type", "=", "None", ")", ":", "if", "(", "date_type", "==", "None", ")", ":", "return", "None", "history_date", "=", "raw_parser", ".", "history_date", "(", "soup", ",", "date_type", ")", "if", "history_date",...
30.538462
12.230769
def chk_date_arg(s): """Checks if the string `s` is a valid date string. Return True of False.""" if re_date.search(s) is None: return False comp = s.split('-') try: dt = datetime.date(int(comp[0]), int(comp[1]), int(comp[2])) return True except Exception as e: r...
[ "def", "chk_date_arg", "(", "s", ")", ":", "if", "re_date", ".", "search", "(", "s", ")", "is", "None", ":", "return", "False", "comp", "=", "s", ".", "split", "(", "'-'", ")", "try", ":", "dt", "=", "datetime", ".", "date", "(", "int", "(", "c...
26.666667
18.25
def compute(self, *args, **kwargs)->[Any, None]: """Compose and evaluate the function. """ return super().compute( self.compose, *args, **kwargs )
[ "def", "compute", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", "->", "[", "Any", ",", "None", "]", ":", "return", "super", "(", ")", ".", "compute", "(", "self", ".", "compose", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
30.833333
8.166667
def day_of_week(abbr=False): """Return a random (abbreviated if `abbr`) day of week name.""" if abbr: return random.choice(DAYS_ABBR) else: return random.choice(DAYS)
[ "def", "day_of_week", "(", "abbr", "=", "False", ")", ":", "if", "abbr", ":", "return", "random", ".", "choice", "(", "DAYS_ABBR", ")", "else", ":", "return", "random", ".", "choice", "(", "DAYS", ")" ]
31.5
13
def getstruct(self, msgid, as_json=False, stream=sys.stdout): """Get and print the whole message. as_json indicates whether to print the part list as JSON or not. """ parts = [part.get_content_type() for hdr, part in self._get(msgid)] if as_json: print(json.dumps(par...
[ "def", "getstruct", "(", "self", ",", "msgid", ",", "as_json", "=", "False", ",", "stream", "=", "sys", ".", "stdout", ")", ":", "parts", "=", "[", "part", ".", "get_content_type", "(", ")", "for", "hdr", ",", "part", "in", "self", ".", "_get", "("...
37
18.272727
def matplotlib_scraper(block, block_vars, gallery_conf, **kwargs): """Scrape Matplotlib images. Parameters ---------- block : tuple A tuple containing the (label, content, line_number) of the block. block_vars : dict Dict of block variables. gallery_conf : dict Contains ...
[ "def", "matplotlib_scraper", "(", "block", ",", "block_vars", ",", "gallery_conf", ",", "*", "*", "kwargs", ")", ":", "matplotlib", ",", "plt", "=", "_import_matplotlib", "(", ")", "image_path_iterator", "=", "block_vars", "[", "'image_path_iterator'", "]", "ima...
41.681818
19.068182
def add_username(user, apps): """When using broser login, username was not stored so look it up""" if not user: return None apps = [a for a in apps if a.instance == user.instance] if not apps: return None from toot.api import verify_credentials creds = verify_credentials(apps....
[ "def", "add_username", "(", "user", ",", "apps", ")", ":", "if", "not", "user", ":", "return", "None", "apps", "=", "[", "a", "for", "a", "in", "apps", "if", "a", ".", "instance", "==", "user", ".", "instance", "]", "if", "not", "apps", ":", "ret...
27.785714
22.785714
def handle_tick(self): """Internal callback every time 1 second has passed.""" self.uptime += 1 for name, interval in self.ticks.items(): if interval == 0: continue self.tick_counters[name] += 1 if self.tick_counters[name] == interval: ...
[ "def", "handle_tick", "(", "self", ")", ":", "self", ".", "uptime", "+=", "1", "for", "name", ",", "interval", "in", "self", ".", "ticks", ".", "items", "(", ")", ":", "if", "interval", "==", "0", ":", "continue", "self", ".", "tick_counters", "[", ...
32.153846
18.230769
def readline(self, echo=None, prompt='', use_history=True): """Return a line of text, including the terminating LF If echo is true always echo, if echo is false never echo If echo is None follow the negotiated setting. prompt is the current prompt to write (and rewrite if needed...
[ "def", "readline", "(", "self", ",", "echo", "=", "None", ",", "prompt", "=", "''", ",", "use_history", "=", "True", ")", ":", "line", "=", "[", "]", "insptr", "=", "0", "ansi", "=", "0", "histptr", "=", "len", "(", "self", ".", "history", ")", ...
39.495575
14.265487
def _wkt(eivals, timescales, normalization, normalized_laplacian): """ Computes wave kernel trace from given eigenvalues, timescales, and normalization. For precise definition, please refer to "NetLSD: Hearing the Shape of a Graph" by A. Tsitsulin, D. Mottin, P. Karras, A. Bronstein, E. Müller. Published a...
[ "def", "_wkt", "(", "eivals", ",", "timescales", ",", "normalization", ",", "normalized_laplacian", ")", ":", "nv", "=", "eivals", ".", "shape", "[", "0", "]", "wkt", "=", "np", ".", "zeros", "(", "timescales", ".", "shape", ")", "for", "idx", ",", "...
39.425
23.675
def files_walker(directory, filters_in=None, filters_out=None, flags=0): """ Defines a generator used to walk files using given filters. Usage:: >>> for file in files_walker("./foundations/tests/tests_foundations/resources/standard/level_0"): ... print(file) ... ./found...
[ "def", "files_walker", "(", "directory", ",", "filters_in", "=", "None", ",", "filters_out", "=", "None", ",", "flags", "=", "0", ")", ":", "if", "filters_in", ":", "LOGGER", ".", "debug", "(", "\"> Current filters in: '{0}'.\"", ".", "format", "(", "filters...
42.744681
30.319149
def add_job_to_db(self, key, job): """Add job info to the database.""" job_msg = self.registry.deep_encode(job) prov = prov_key(job_msg) def set_link(duplicate_id): self.cur.execute( 'update "jobs" set "link" = ?, "status" = ? where "id" = ?', ...
[ "def", "add_job_to_db", "(", "self", ",", "key", ",", "job", ")", ":", "job_msg", "=", "self", ".", "registry", ".", "deep_encode", "(", "job", ")", "prov", "=", "prov_key", "(", "job_msg", ")", "def", "set_link", "(", "duplicate_id", ")", ":", "self",...
40.285714
16.746032
def addStepListener(listener): """addStepListener(traci.StepListener) -> bool Append the step listener (its step function is called at the end of every call to traci.simulationStep()) Returns True if the listener was added successfully, False otherwise. """ if issubclass(type(listener), StepListene...
[ "def", "addStepListener", "(", "listener", ")", ":", "if", "issubclass", "(", "type", "(", "listener", ")", ",", "StepListener", ")", ":", "_stepListeners", ".", "append", "(", "listener", ")", "return", "True", "warnings", ".", "warn", "(", "\"Proposed list...
44.166667
25.75
def get_config(variable, default=None): """ Get configuration variable for strudel.* packages Args: variable (str): name of the config variable default: value to use of config variable not set Returns: variable value Order of search: 1. stutils.CONFIG 2. settin...
[ "def", "get_config", "(", "variable", ",", "default", "=", "None", ")", ":", "if", "variable", "in", "CONFIG", ":", "return", "CONFIG", "[", "variable", "]", "if", "hasattr", "(", "settings", ",", "variable", ")", ":", "return", "getattr", "(", "settings...
27.815789
20.236842
def forward_message(chat_id, from_chat_id, message_id, **kwargs): """ Use this method to forward messages of any kind. :param chat_id: Unique identifier for the message recipient — User or GroupChat id :param from_chat_id: Unique identifier for the chat where the original message wa...
[ "def", "forward_message", "(", "chat_id", ",", "from_chat_id", ",", "message_id", ",", "*", "*", "kwargs", ")", ":", "# required args", "params", "=", "dict", "(", "chat_id", "=", "chat_id", ",", "from_chat_id", "=", "from_chat_id", ",", "message_id", "=", "...
32.851852
24.259259
def on_connect(self, ws): """ Todo """ self.logger.info("onconnect") msg = {'op': self.IDENTIFY, 'd': {'token': self.token, 'properties': {'$os': 'lnx', '$browser': 'discord_simple', '$device': 'discord_simple', ...
[ "def", "on_connect", "(", "self", ",", "ws", ")", ":", "self", ".", "logger", ".", "info", "(", "\"onconnect\"", ")", "msg", "=", "{", "'op'", ":", "self", ".", "IDENTIFY", ",", "'d'", ":", "{", "'token'", ":", "self", ".", "token", ",", "'properti...
38.714286
9.714286
def _ProcessFileEntry(self, mediator, file_entry): """Processes a file entry. Args: mediator (ParserMediator): mediates the interactions between parsers and other components, such as storage and abort signals. file_entry (dfvfs.FileEntry): file entry. """ display_name = mediator.G...
[ "def", "_ProcessFileEntry", "(", "self", ",", "mediator", ",", "file_entry", ")", ":", "display_name", "=", "mediator", ".", "GetDisplayName", "(", ")", "logger", ".", "debug", "(", "'[ProcessFileEntry] processing file entry: {0:s}'", ".", "format", "(", "display_na...
35.363636
22.545455
def eeg_microstates_relabel(method, results, microstates_labels, reverse_microstates=None): """ Relabel the microstates. """ microstates = list(method['microstates']) for index, microstate in enumerate(method['microstates']): if microstate in list(reverse_microstates.keys()): ...
[ "def", "eeg_microstates_relabel", "(", "method", ",", "results", ",", "microstates_labels", ",", "reverse_microstates", "=", "None", ")", ":", "microstates", "=", "list", "(", "method", "[", "'microstates'", "]", ")", "for", "index", ",", "microstate", "in", "...
32.526316
23.894737
def start_logging(gconfig, logpath): '''Turn on logging and set up the global config. This expects the :mod:`yakonfig` global configuration to be unset, and establishes it. It starts the log system via the :mod:`dblogger` setup. In addition to :mod:`dblogger`'s defaults, if `logpath` is provided,...
[ "def", "start_logging", "(", "gconfig", ",", "logpath", ")", ":", "yakonfig", ".", "set_default_config", "(", "[", "rejester", ",", "dblogger", "]", ",", "config", "=", "gconfig", ")", "if", "logpath", ":", "formatter", "=", "dblogger", ".", "FixedWidthForma...
43.72
24.12
def expand_branch_name(self, name): """ Expand branch names to their unambiguous form. :param name: The name of a local or remote branch (a string). :returns: The unambiguous form of the branch name (a string). This internal method is used by methods like :func:`find_revision_i...
[ "def", "expand_branch_name", "(", "self", ",", "name", ")", ":", "# If no name is given we pick the default revision.", "if", "not", "name", ":", "return", "self", ".", "default_revision", "# Run `git for-each-ref' once and remember the results.", "branches", "=", "list", "...
54.075
22.825
def log_view(func): """ Helpful while debugging Selenium unittests. e.g.: server response an error in AJAX requests """ @functools.wraps(func) def view_logger(*args, **kwargs): log.debug("call view %r", func.__name__) try: response = func(*args, **kwargs) exc...
[ "def", "log_view", "(", "func", ")", ":", "@", "functools", ".", "wraps", "(", "func", ")", "def", "view_logger", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "log", ".", "debug", "(", "\"call view %r\"", ",", "func", ".", "__name__", ")", ...
26.55
15.05
def siblings(self, **kwargs): # type: (Any) -> Any """Retrieve the siblings of this `Part` as `Partset`. Siblings are other Parts sharing the same parent of this `Part`, including the part itself. :param kwargs: Additional search arguments to search for, check :class:`pykechain.Client....
[ "def", "siblings", "(", "self", ",", "*", "*", "kwargs", ")", ":", "# type: (Any) -> Any", "if", "self", ".", "parent_id", ":", "return", "self", ".", "_client", ".", "parts", "(", "parent", "=", "self", ".", "parent_id", ",", "category", "=", "self", ...
44.529412
24.058824
def find_first_match(basedir, string): """ return the first file that matches string starting from basedir """ matches = find(basedir, string) return matches[0] if matches else matches
[ "def", "find_first_match", "(", "basedir", ",", "string", ")", ":", "matches", "=", "find", "(", "basedir", ",", "string", ")", "return", "matches", "[", "0", "]", "if", "matches", "else", "matches" ]
33.166667
6.5
def launch(self): """Launches pantsd in a subprocess. N.B. This should always be called under care of the `lifecycle_lock`. :returns: A Handle for the pantsd instance. :rtype: PantsDaemon.Handle """ self.terminate(include_watchman=False) self.watchman_launcher.maybe_launch() self._logg...
[ "def", "launch", "(", "self", ")", ":", "self", ".", "terminate", "(", "include_watchman", "=", "False", ")", "self", ".", "watchman_launcher", ".", "maybe_launch", "(", ")", "self", ".", "_logger", ".", "debug", "(", "'launching pantsd'", ")", "self", "."...
40.555556
17.444444
def diff_medians_abs(array_one, array_two): """ Computes the absolute (symmetric) difference in medians between two arrays of values. Given arrays will be flattened (to 1D array) regardless of dimension, and any non-finite/NaN values will be ignored. Parameters ---------- array_one, ar...
[ "def", "diff_medians_abs", "(", "array_one", ",", "array_two", ")", ":", "abs_diff_medians", "=", "np", ".", "abs", "(", "diff_medians", "(", "array_one", ",", "array_two", ")", ")", "return", "abs_diff_medians" ]
25.851852
26.074074
def get_ngrok_public_url(): """Get the ngrok public HTTP URL from the local client API.""" try: response = requests.get(url=NGROK_CLIENT_API_BASE_URL + "/tunnels", headers={'content-type': 'application/json'}) response.raise_for_status() except request...
[ "def", "get_ngrok_public_url", "(", ")", ":", "try", ":", "response", "=", "requests", ".", "get", "(", "url", "=", "NGROK_CLIENT_API_BASE_URL", "+", "\"/tunnels\"", ",", "headers", "=", "{", "'content-type'", ":", "'application/json'", "}", ")", "response", "...
41.764706
20.882353
def _get_result(self) -> float: """Return current measurement result in lx.""" try: data = self._bus.read_word_data(self._i2c_add, self._mode) self._ok = True except OSError as exc: self.log_error("Bad reading in bus: %s", exc) self._ok = False ...
[ "def", "_get_result", "(", "self", ")", "->", "float", ":", "try", ":", "data", "=", "self", ".", "_bus", ".", "read_word_data", "(", "self", ".", "_i2c_add", ",", "self", ".", "_mode", ")", "self", ".", "_ok", "=", "True", "except", "OSError", "as",...
36.571429
16
def eqdate(y): """ Like eq but compares datetime with y,m,d tuple. Also accepts magic string 'TODAY'. """ y = datetime.date.today() if y == 'TODAY' else datetime.date(*y) return lambda x: x == y
[ "def", "eqdate", "(", "y", ")", ":", "y", "=", "datetime", ".", "date", ".", "today", "(", ")", "if", "y", "==", "'TODAY'", "else", "datetime", ".", "date", "(", "*", "y", ")", "return", "lambda", "x", ":", "x", "==", "y" ]
30.285714
11.428571
async def set_bucket(self, *, chat: typing.Union[str, int, None] = None, user: typing.Union[str, int, None] = None, bucket: typing.Dict = None): """ Set bucket for user in chat Chat or user is always required. If one of ...
[ "async", "def", "set_bucket", "(", "self", ",", "*", ",", "chat", ":", "typing", ".", "Union", "[", "str", ",", "int", ",", "None", "]", "=", "None", ",", "user", ":", "typing", ".", "Union", "[", "str", ",", "int", ",", "None", "]", "=", "None...
33.6
18.933333
def _add_has_where(self, has_query, relation, operator, count, boolean): """ Add the "has" condition where clause to the query. :param has_query: The has query :type has_query: Builder :param relation: The relation to count :type relation: orator.orm.relations.Relation ...
[ "def", "_add_has_where", "(", "self", ",", "has_query", ",", "relation", ",", "operator", ",", "count", ",", "boolean", ")", ":", "self", ".", "_merge_model_defined_relation_wheres_to_has_query", "(", "has_query", ",", "relation", ")", "if", "isinstance", "(", "...
28.758621
21.517241
def _errstr(value): """Returns the value str, truncated to MAX_ERROR_STR_LEN characters. If it's truncated, the returned value will have '...' on the end. """ value = str(value) # We won't make the caller convert value to a string each time. if len(value) > MAX_ERROR_STR_LEN: return value[:...
[ "def", "_errstr", "(", "value", ")", ":", "value", "=", "str", "(", "value", ")", "# We won't make the caller convert value to a string each time.", "if", "len", "(", "value", ")", ">", "MAX_ERROR_STR_LEN", ":", "return", "value", "[", ":", "MAX_ERROR_STR_LEN", "]...
36.8
19.4
def _get_model_fitting(self, mf_id): """ Retreive model fitting with identifier 'mf_id' from the list of model fitting objects stored in self.model_fitting """ for model_fitting in self.model_fittings: if model_fitting.activity.id == mf_id: return mode...
[ "def", "_get_model_fitting", "(", "self", ",", "mf_id", ")", ":", "for", "model_fitting", "in", "self", ".", "model_fittings", ":", "if", "model_fitting", ".", "activity", ".", "id", "==", "mf_id", ":", "return", "model_fitting", "raise", "Exception", "(", "...
39.363636
13.727273
def get_models(self): """ Get a list of content models the object subscribes to. """ try: rels = self.rels_ext.content except RequestFailed: # if rels-ext can't be retrieved, confirm this object does not have a RELS-EXT # (in which case, it doe...
[ "def", "get_models", "(", "self", ")", ":", "try", ":", "rels", "=", "self", ".", "rels_ext", ".", "content", "except", "RequestFailed", ":", "# if rels-ext can't be retrieved, confirm this object does not have a RELS-EXT", "# (in which case, it does not have any content models...
34.8
19.333333
def add(self): """ Add the currently tested element into the database. """ if self._authorization(): # We are authorized to work. if self.epoch < int(PyFunceble.time()): state = "past" else: state = "future" ...
[ "def", "add", "(", "self", ")", ":", "if", "self", ".", "_authorization", "(", ")", ":", "# We are authorized to work.", "if", "self", ".", "epoch", "<", "int", "(", "PyFunceble", ".", "time", "(", ")", ")", ":", "state", "=", "\"past\"", "else", ":", ...
38.408602
20.27957
def is_same_filename (filename1, filename2): """Check if filename1 and filename2 are the same filename.""" return os.path.realpath(filename1) == os.path.realpath(filename2)
[ "def", "is_same_filename", "(", "filename1", ",", "filename2", ")", ":", "return", "os", ".", "path", ".", "realpath", "(", "filename1", ")", "==", "os", ".", "path", ".", "realpath", "(", "filename2", ")" ]
59.333333
11
def _load_w2v(model_file=_f_model, binary=True): ''' load word2vec model ''' if not os.path.exists(model_file): print("os.path : ", os.path) raise Exception("Model file [%s] does not exist." % model_file) return KeyedVectors.load_word2vec_format( model_file, binary=binary, un...
[ "def", "_load_w2v", "(", "model_file", "=", "_f_model", ",", "binary", "=", "True", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "model_file", ")", ":", "print", "(", "\"os.path : \"", ",", "os", ".", "path", ")", "raise", "Exception",...
37.111111
16.888889
def send(self): """ Send the message. First, a message is constructed, then a session with the email servers is created, finally the message is sent and the session is stopped. """ self._generate_email() if self.verbose: print( ...
[ "def", "send", "(", "self", ")", ":", "self", ".", "_generate_email", "(", ")", "if", "self", ".", "verbose", ":", "print", "(", "\"Debugging info\"", "\"\\n--------------\"", "\"\\n{} Message created.\"", ".", "format", "(", "timestamp", "(", ")", ")", ")", ...
27.404762
18.97619
def _count_tasks(self): """Count the number of tasks, both in the json and directory. Returns ------- num_tasks : int The total number of all tasks included in the `tasks.json` file. """ self.log.warning("Tasks:") tasks, task_names = self.catalog._lo...
[ "def", "_count_tasks", "(", "self", ")", ":", "self", ".", "log", ".", "warning", "(", "\"Tasks:\"", ")", "tasks", ",", "task_names", "=", "self", ".", "catalog", ".", "_load_task_list_from_file", "(", ")", "# Total number of all tasks", "num_tasks", "=", "len...
40.045455
18.772727
def create_threadpool_executed_func(original_func): """ Returns a function wrapper that defers function calls execute inside gevent's threadpool but keeps any exception or backtrace in the caller's context. :param original_func: function to wrap :returns: wrapper function """ def wrapped_fun...
[ "def", "create_threadpool_executed_func", "(", "original_func", ")", ":", "def", "wrapped_func", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "result", "=", "original_func", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "T...
37.956522
19.347826
def _fill_table_entry(self, row, col): """"" Fill an entry of the observation table. Args: row (str): The row of the observation table col (str): The column of the observation table Returns: None """ self.observation_table[row, col] = s...
[ "def", "_fill_table_entry", "(", "self", ",", "row", ",", "col", ")", ":", "self", ".", "observation_table", "[", "row", ",", "col", "]", "=", "self", ".", "_membership_query", "(", "row", "+", "col", ")" ]
34.3
15.3
def _adjust_boundaries(self, boundary_indices, text_file, real_wave_mfcc, sync_root, force_aba_auto=False, leaf_level=False): """ Adjust boundaries as requested by the user. Return the computed time map, that is, a list of pairs ``[start_time, end_time]``, of length equal to num...
[ "def", "_adjust_boundaries", "(", "self", ",", "boundary_indices", ",", "text_file", ",", "real_wave_mfcc", ",", "sync_root", ",", "force_aba_auto", "=", "False", ",", "leaf_level", "=", "False", ")", ":", "# boundary_indices contains the boundary indices in the all_mfcc ...
49.107143
19.321429
def public_ip_addresses_list_all(**kwargs): ''' .. versionadded:: 2019.2.0 List all public IP addresses within a subscription. CLI Example: .. code-block:: bash salt-call azurearm_network.public_ip_addresses_list_all ''' result = {} netconn = __utils__['azurearm.get_client']...
[ "def", "public_ip_addresses_list_all", "(", "*", "*", "kwargs", ")", ":", "result", "=", "{", "}", "netconn", "=", "__utils__", "[", "'azurearm.get_client'", "]", "(", "'network'", ",", "*", "*", "kwargs", ")", "try", ":", "pub_ips", "=", "__utils__", "[",...
26.16
26.96
def drop_continuous_query(self, name, database=None): """Drop an existing continuous query for a database. :param name: the name of continuous query to drop :type name: str :param database: the database for which the continuous query is dropped. Defaults to current client's ...
[ "def", "drop_continuous_query", "(", "self", ",", "name", ",", "database", "=", "None", ")", ":", "query_string", "=", "(", "\"DROP CONTINUOUS QUERY {0} ON {1}\"", ")", ".", "format", "(", "quote_ident", "(", "name", ")", ",", "quote_ident", "(", "database", "...
41.384615
16.538462
def remove_docstrings(tokens): """ Removes docstrings from *tokens* which is expected to be a list equivalent of `tokenize.generate_tokens()` (so we can update in-place). """ prev_tok_type = None for index, tok in enumerate(tokens): token_type = tok[0] if token_type == tokenize.S...
[ "def", "remove_docstrings", "(", "tokens", ")", ":", "prev_tok_type", "=", "None", "for", "index", ",", "tok", "in", "enumerate", "(", "tokens", ")", ":", "token_type", "=", "tok", "[", "0", "]", "if", "token_type", "==", "tokenize", ".", "STRING", ":", ...
41.954545
9.227273
def evalsha(self, sha, numkeys, *keys_and_args): """Emulates evalsha""" if not self.script_exists(sha)[0]: raise RedisError("Sha not registered") script_callable = Script(self, self.shas[sha], self.load_lua_dependencies) numkeys = max(numkeys, 0) keys = keys_and_args[...
[ "def", "evalsha", "(", "self", ",", "sha", ",", "numkeys", ",", "*", "keys_and_args", ")", ":", "if", "not", "self", ".", "script_exists", "(", "sha", ")", "[", "0", "]", ":", "raise", "RedisError", "(", "\"Sha not registered\"", ")", "script_callable", ...
44.777778
8.333333
def get_files_types(self): """ Return the files inside the APK with their associated types (by using python-magic) At the same time, the CRC32 are calculated for the files. :rtype: a dictionnary """ if self._files == {}: # Generate File Types / CRC List ...
[ "def", "get_files_types", "(", "self", ")", ":", "if", "self", ".", "_files", "==", "{", "}", ":", "# Generate File Types / CRC List", "for", "i", "in", "self", ".", "get_files", "(", ")", ":", "buffer", "=", "self", ".", "_get_crc32", "(", "i", ")", "...
31.933333
18.733333
def extracturls(mesg): """Given a text message, extract all the URLs found in the message, along with their surrounding context. The output is a list of sequences of Chunk objects, corresponding to the contextual regions extracted from the string. """ lines = NLRE.split(mesg) # The number of ...
[ "def", "extracturls", "(", "mesg", ")", ":", "lines", "=", "NLRE", ".", "split", "(", "mesg", ")", "# The number of lines of context above to provide.", "# above_context = 1", "# The number of lines of context below to provide.", "# below_context = 1", "# Plan here is to first tr...
39.72
20.92
def get_form_success_data(self, form): """ Allows customization of the JSON data returned when a valid form submission occurs. """ data = { "html": render_to_string( "pinax/teams/_invite_form.html", { "invite_form": self.get...
[ "def", "get_form_success_data", "(", "self", ",", "form", ")", ":", "data", "=", "{", "\"html\"", ":", "render_to_string", "(", "\"pinax/teams/_invite_form.html\"", ",", "{", "\"invite_form\"", ":", "self", ".", "get_unbound_form", "(", ")", ",", "\"team\"", ":"...
37.1
15.4
def fix_style(style='basic', ax=None, **kwargs): ''' Add an extra formatting layer to an axe, that couldn't be changed directly in matplotlib.rcParams or with styles. Apply this function to every axe you created. Parameters ---------- ax: a matplotlib axe. If None, the last ...
[ "def", "fix_style", "(", "style", "=", "'basic'", ",", "ax", "=", "None", ",", "*", "*", "kwargs", ")", ":", "style", "=", "_read_style", "(", "style", ")", "# Apply all styles", "for", "s", "in", "style", ":", "if", "not", "s", "in", "style_params", ...
30.521739
23.913043
def insert_level(df, label, level=0, copy=0, axis=0, level_name=None): """Add a new level to the index with the specified label. The newly created index will be a MultiIndex. :param df: DataFrame :param label: label to insert :param copy: If True, copy the DataFrame before assigning new index ...
[ "def", "insert_level", "(", "df", ",", "label", ",", "level", "=", "0", ",", "copy", "=", "0", ",", "axis", "=", "0", ",", "level_name", "=", "None", ")", ":", "df", "=", "df", "if", "not", "copy", "else", "df", ".", "copy", "(", ")", "src", ...
39.2
17.4
def request_many(self, queries, source='Datastream', fields=None, options=None, symbol_set=None, tag=None): """General function to retrieve one record in raw format. query - list of query strings for DWE system. source - The name of datasource (default: "Datastream") ...
[ "def", "request_many", "(", "self", ",", "queries", ",", "source", "=", "'Datastream'", ",", "fields", "=", "None", ",", "options", "=", "None", ",", "symbol_set", "=", "None", ",", "tag", "=", "None", ")", ":", "if", "self", ".", "show_request", ":", ...
46.214286
21.166667
def document_url(self): """ Constructs and returns the document URL. :returns: Document URL """ if '_id' not in self or self['_id'] is None: return None # handle design document url if self['_id'].startswith('_design/'): return '/'.join((...
[ "def", "document_url", "(", "self", ")", ":", "if", "'_id'", "not", "in", "self", "or", "self", "[", "'_id'", "]", "is", "None", ":", "return", "None", "# handle design document url", "if", "self", "[", "'_id'", "]", ".", "startswith", "(", "'_design/'", ...
28.125
14.458333
def do_setmode(self, arg): ''' shift from ASM to DISASM ''' op_modes = config.get_op_modes() if arg in op_modes: op_mode = op_modes[arg] op_mode.cmdloop() else: print("Error: unknown operational mode, please use 'help setmode'.")
[ "def", "do_setmode", "(", "self", ",", "arg", ")", ":", "op_modes", "=", "config", ".", "get_op_modes", "(", ")", "if", "arg", "in", "op_modes", ":", "op_mode", "=", "op_modes", "[", "arg", "]", "op_mode", ".", "cmdloop", "(", ")", "else", ":", "prin...
36.25
13.75
def email_on_invoice_change(cls, invoice, old_status, new_status): ''' Sends out all of the necessary notifications that the status of the invoice has changed to: - Invoice is now paid - Invoice is now refunded ''' # The statuses that we don't care about. silen...
[ "def", "email_on_invoice_change", "(", "cls", ",", "invoice", ",", "old_status", ",", "new_status", ")", ":", "# The statuses that we don't care about.", "silent_status", "=", "[", "commerce", ".", "Invoice", ".", "STATUS_VOID", ",", "commerce", ".", "Invoice", ".",...
27.571429
21.095238
def copy(self, src_fs, src_path, dst_fs, dst_path): # type: (FS, Text, FS, Text) -> None """Copy a file from one fs to another.""" if self.queue is None: # This should be the most performant for a single-thread copy_file_internal(src_fs, src_path, dst_fs, dst_path) ...
[ "def", "copy", "(", "self", ",", "src_fs", ",", "src_path", ",", "dst_fs", ",", "dst_path", ")", ":", "# type: (FS, Text, FS, Text) -> None", "if", "self", ".", "queue", "is", "None", ":", "# This should be the most performant for a single-thread", "copy_file_internal",...
40.466667
14.133333
def add_paginated_grid_widget(self, part_model, delete=False, edit=True, export=True, clone=True, new_instance=False, parent_part_instance=None, max_height=None, custom_title=False, emphasize_edit=False, emphasize_clone=False, emphasize_new_instance=Tr...
[ "def", "add_paginated_grid_widget", "(", "self", ",", "part_model", ",", "delete", "=", "False", ",", "edit", "=", "True", ",", "export", "=", "True", ",", "clone", "=", "True", ",", "new_instance", "=", "False", ",", "parent_part_instance", "=", "None", "...
50.892655
23.367232
def inflect(self): """Return instance of inflect.""" if self._inflect is None: import inflect self._inflect = inflect.engine() return self._inflect
[ "def", "inflect", "(", "self", ")", ":", "if", "self", ".", "_inflect", "is", "None", ":", "import", "inflect", "self", ".", "_inflect", "=", "inflect", ".", "engine", "(", ")", "return", "self", ".", "_inflect" ]
27.142857
14.142857
def isMasterReqLatencyTooHigh(self): """ Return whether the request latency of the master instance is greater than the acceptable threshold """ # TODO for now, view_change procedure can take more that 15 minutes # (5 minutes for catchup and 10 minutes for primary's answer...
[ "def", "isMasterReqLatencyTooHigh", "(", "self", ")", ":", "# TODO for now, view_change procedure can take more that 15 minutes", "# (5 minutes for catchup and 10 minutes for primary's answer).", "# Therefore, view_change triggering by max latency is not indicative now.", "r", "=", "self", "...
48.789474
25
def find_1wf_files(self): """ Abinit adds the idir-ipert index at the end of the 1WF file and this breaks the extension e.g. out_1WF4. This method scans the files in the directories and returns a list of namedtuple Each named tuple gives the `path` of the 1FK file and the `pertcase` inde...
[ "def", "find_1wf_files", "(", "self", ")", ":", "regex", "=", "re", ".", "compile", "(", "r\"out_1WF(\\d+)(\\.nc)?$\"", ")", "wf_paths", "=", "[", "f", "for", "f", "in", "self", ".", "list_filepaths", "(", ")", "if", "regex", ".", "match", "(", "os", "...
43.590909
23.318182
def render(self): """ Render the menu into a sorted by order multi dict """ menu_list = [] menu_index = 0 for _, menu in copy.deepcopy(self.MENU).items(): subnav = [] menu["kwargs"]["_id"] = str(menu_index) menu["kwargs"]["active"] = False ...
[ "def", "render", "(", "self", ")", ":", "menu_list", "=", "[", "]", "menu_index", "=", "0", "for", "_", ",", "menu", "in", "copy", ".", "deepcopy", "(", "self", ".", "MENU", ")", ".", "items", "(", ")", ":", "subnav", "=", "[", "]", "menu", "["...
34.105263
16.552632
def extract(query, choices, processor=default_processor, scorer=default_scorer, limit=5): """Select the best match in a list or dictionary of choices. Find best matches in a list or dictionary of choices, return a list of tuples containing the match and its score. If a dictionary is used, also returns ...
[ "def", "extract", "(", "query", ",", "choices", ",", "processor", "=", "default_processor", ",", "scorer", "=", "default_scorer", ",", "limit", "=", "5", ")", ":", "sl", "=", "extractWithoutOrder", "(", "query", ",", "choices", ",", "processor", ",", "scor...
41.479167
27
def sendMessage(self,chat_id,text,parse_mode=None,disable_web=None,reply_msg_id=None,markup=None): ''' On failure returns False On success returns Message Object ''' payload={'chat_id' : chat_id, 'text' : text, 'parse_mode': parse_mode , 'disable_web_page_preview' : disable_web , 'reply_to_message_id' : reply_msg...
[ "def", "sendMessage", "(", "self", ",", "chat_id", ",", "text", ",", "parse_mode", "=", "None", ",", "disable_web", "=", "None", ",", "reply_msg_id", "=", "None", ",", "markup", "=", "None", ")", ":", "payload", "=", "{", "'chat_id'", ":", "chat_id", "...
45.272727
32.727273