text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def get_program_args(self): """Get the program args to run this JVM with. These are the arguments passed to main() and are program-specific. """ ret = [] for arg in self.get_options().program_args: ret.extend(safe_shlex_split(arg)) return ret
[ "def", "get_program_args", "(", "self", ")", ":", "ret", "=", "[", "]", "for", "arg", "in", "self", ".", "get_options", "(", ")", ".", "program_args", ":", "ret", ".", "extend", "(", "safe_shlex_split", "(", "arg", ")", ")", "return", "ret" ]
29.444444
16.111111
def p_cardinality_1(self, p): '''cardinality : NUMBER''' if p[1] != '1': raise ParsingException("illegal cardinality (%s) at %s:%d" % (p[1], p.lexer.filename, p.lineno(1))) p[0] = p[1]
[ "def", "p_cardinality_1", "(", "self", ",", "p", ")", ":", "if", "p", "[", "1", "]", "!=", "'1'", ":", "raise", "ParsingException", "(", "\"illegal cardinality (%s) at %s:%d\"", "%", "(", "p", "[", "1", "]", ",", "p", ".", "lexer", ".", "filename", ","...
41.666667
20
def fromfd(cls, fd, mode='rb', bufsize=-1): """create a cooperating greenhouse file from an existing descriptor :param fd: the file descriptor to wrap in a new file object :type fd: int :param mode: the file mode :type mode: str :param bufsize: the size of re...
[ "def", "fromfd", "(", "cls", ",", "fd", ",", "mode", "=", "'rb'", ",", "bufsize", "=", "-", "1", ")", ":", "fp", "=", "object", ".", "__new__", "(", "cls", ")", "# bypass __init__", "fp", ".", "_rbuf", "=", "StringIO", "(", ")", "fp", ".", "encod...
32.25
19.333333
def delete_task(self, courseid, taskid): """ :param courseid: the course id of the course :param taskid: the task id of the task :raise InvalidNameException or CourseNotFoundException Erase the content of the task folder """ if not id_checker(courseid): ...
[ "def", "delete_task", "(", "self", ",", "courseid", ",", "taskid", ")", ":", "if", "not", "id_checker", "(", "courseid", ")", ":", "raise", "InvalidNameException", "(", "\"Course with invalid name: \"", "+", "courseid", ")", "if", "not", "id_checker", "(", "ta...
40.352941
17.176471
def _get_users_from_groups(self, project_id, roles, project_users): """Update with users which have role on project through a group. :param project_id: ID of the project :param roles: list of roles from keystone :param project_users: list to be updated with the users found """ ...
[ "def", "_get_users_from_groups", "(", "self", ",", "project_id", ",", "roles", ",", "project_users", ")", ":", "# For keystone.group_list project_id is not passed as argument because", "# it is ignored when using admin credentials", "# Get all groups (to be able to find group name)", "...
43.307692
19.641026
def calc_finite_diff_terms_for_abc(model_obj, mle_params, init_vals, epsilon, **fit_kwargs): """ Calculates the terms needed for the finite difference approximations of ...
[ "def", "calc_finite_diff_terms_for_abc", "(", "model_obj", ",", "mle_params", ",", "init_vals", ",", "epsilon", ",", "*", "*", "fit_kwargs", ")", ":", "# Determine the number of observations in this dataset.", "num_obs", "=", "model_obj", ".", "data", "[", "model_obj", ...
49.99
23.11
def is_watertight(edges, edges_sorted=None): """ Parameters --------- edges : (n, 2) int List of vertex indices edges_sorted : (n, 2) int Pass vertex indices sorted on axis 1 as a speedup Returns --------- watertight : boolean Whether every edge is shared by an even ...
[ "def", "is_watertight", "(", "edges", ",", "edges_sorted", "=", "None", ")", ":", "# passing edges_sorted is a speedup only", "if", "edges_sorted", "is", "None", ":", "edges_sorted", "=", "np", ".", "sort", "(", "edges", ",", "axis", "=", "1", ")", "# group so...
27.387097
16.483871
def keepOriginalText(s,startLoc,t): """DEPRECATED - use new helper method C{L{originalTextFor}}. Helper parse action to preserve original parsed text, overriding any nested parse actions.""" try: endloc = getTokensEndLoc() except ParseException: raise ParseFatalException...
[ "def", "keepOriginalText", "(", "s", ",", "startLoc", ",", "t", ")", ":", "try", ":", "endloc", "=", "getTokensEndLoc", "(", ")", "except", "ParseException", ":", "raise", "ParseFatalException", "(", "\"incorrect usage of keepOriginalText - may only be called as a parse...
41.727273
18.454545
def make_segwit_info(privkey=None): """ Create a bundle of information that can be used to generate a p2sh-p2wpkh transaction """ if privkey is None: privkey = BitcoinPrivateKey(compressed=True).to_wif() return make_multisig_segwit_info(1, [privkey])
[ "def", "make_segwit_info", "(", "privkey", "=", "None", ")", ":", "if", "privkey", "is", "None", ":", "privkey", "=", "BitcoinPrivateKey", "(", "compressed", "=", "True", ")", ".", "to_wif", "(", ")", "return", "make_multisig_segwit_info", "(", "1", ",", "...
25.272727
14.363636
def get(dict_, keys=(), default=None): """Extensions of standard :meth:`dict.get`. Retrieves an item from given dictionary, trying given keys in order. :param dict_: Dictionary to perform the lookup(s) in :param keys: Iterable of keys :param default: Default value to return if no key is found ...
[ "def", "get", "(", "dict_", ",", "keys", "=", "(", ")", ",", "default", "=", "None", ")", ":", "ensure_mapping", "(", "dict_", ")", "ensure_iterable", "(", "keys", ")", "for", "key", "in", "keys", ":", "try", ":", "return", "dict_", "[", "key", "]"...
27.2
20.5
def clear_mpi_env_vars(): """ from mpi4py import MPI will call MPI_Init by default. If the child process has MPI environment variables, MPI will think that the child process is an MPI process just like the parent and do bad things such as hang. This context manager is a hacky way to clear those environment...
[ "def", "clear_mpi_env_vars", "(", ")", ":", "removed_environment", "=", "{", "}", "for", "k", ",", "v", "in", "list", "(", "os", ".", "environ", ".", "items", "(", ")", ")", ":", "for", "prefix", "in", "[", "'OMPI_'", ",", "'PMI_'", "]", ":", "if",...
44
27
def _get_version_info(): """ Returns the currently-installed awslimitchecker version, and a best-effort attempt at finding the origin URL and commit/tag if installed from an editable git clone. :returns: awslimitchecker version :rtype: str """ if os.environ.get('VERSIONCHECK_DEBUG', '')...
[ "def", "_get_version_info", "(", ")", ":", "if", "os", ".", "environ", ".", "get", "(", "'VERSIONCHECK_DEBUG'", ",", "''", ")", "!=", "'true'", ":", "for", "lname", "in", "[", "'versionfinder'", ",", "'pip'", ",", "'git'", "]", ":", "l", "=", "logging"...
33.868421
16.5
def get_output_nodes(G: nx.DiGraph) -> List[str]: """ Get all output nodes from a network. """ return [n for n, d in G.out_degree() if d == 0]
[ "def", "get_output_nodes", "(", "G", ":", "nx", ".", "DiGraph", ")", "->", "List", "[", "str", "]", ":", "return", "[", "n", "for", "n", ",", "d", "in", "G", ".", "out_degree", "(", ")", "if", "d", "==", "0", "]" ]
49.333333
6.666667
def sanity_check_ir_blocks_from_frontend(ir_blocks, query_metadata_table): """Assert that IR blocks originating from the frontend do not have nonsensical structure. Args: ir_blocks: list of BasicBlocks representing the IR to sanity-check Raises: AssertionError, if the IR has unexpected str...
[ "def", "sanity_check_ir_blocks_from_frontend", "(", "ir_blocks", ",", "query_metadata_table", ")", ":", "if", "not", "ir_blocks", ":", "raise", "AssertionError", "(", "u'Received no ir_blocks: {}'", ".", "format", "(", "ir_blocks", ")", ")", "_sanity_check_fold_scope_loca...
50.541667
26.291667
def project_top_dir(self, *args) -> str: """ Project top-level directory """ return os.path.join(self.project_dir, *args)
[ "def", "project_top_dir", "(", "self", ",", "*", "args", ")", "->", "str", ":", "return", "os", ".", "path", ".", "join", "(", "self", ".", "project_dir", ",", "*", "args", ")" ]
45
4
def validate_response(public_key_server, status_code, body_bytes, headers): """ :type public_key_server: RSA.RsaKey :type status_code: int :type body_bytes: bytes :type headers: dict[str, str] :rtype: None """ head_bytes = _generate_response_head_bytes(status_code, headers) bytes_s...
[ "def", "validate_response", "(", "public_key_server", ",", "status_code", ",", "body_bytes", ",", "headers", ")", ":", "head_bytes", "=", "_generate_response_head_bytes", "(", "status_code", ",", "headers", ")", "bytes_signed", "=", "head_bytes", "+", "body_bytes", ...
33.0625
17.5625
def _nanstd(array, axis=None, ddof=0): """Bottleneck nanstd function that handle tuple axis.""" if isinstance(axis, tuple): array = _move_tuple_axes_first(array, axis=axis) axis = 0 return bottleneck.nanstd(array, axis=axis, ddof=ddof)
[ "def", "_nanstd", "(", "array", ",", "axis", "=", "None", ",", "ddof", "=", "0", ")", ":", "if", "isinstance", "(", "axis", ",", "tuple", ")", ":", "array", "=", "_move_tuple_axes_first", "(", "array", ",", "axis", "=", "axis", ")", "axis", "=", "0...
36.857143
15.428571
def pop(self, key, default=_sentinel): """ Removes the specified key and returns the corresponding value. If key is not found, the default is returned if given, otherwise KeyError is raised. :param key: The key :param default: The default value :return: The value ...
[ "def", "pop", "(", "self", ",", "key", ",", "default", "=", "_sentinel", ")", ":", "if", "default", "is", "not", "_sentinel", ":", "tup", "=", "self", ".", "_data", ".", "pop", "(", "key", ".", "lower", "(", ")", ",", "default", ")", "else", ":",...
32.823529
15.764706
def autodiscover(): """ TODO: document """ from django.contrib.admin import autodiscover as django_autodiscover django_autodiscover() from copy import copy from django.contrib.admin import site as django_site registry = copy(django_site._registry) registry.update(site._registry) ...
[ "def", "autodiscover", "(", ")", ":", "from", "django", ".", "contrib", ".", "admin", "import", "autodiscover", "as", "django_autodiscover", "django_autodiscover", "(", ")", "from", "copy", "import", "copy", "from", "django", ".", "contrib", ".", "admin", "imp...
27.916667
14.916667
def convert_dot(node, **kwargs): """Map MXNet's dot operator attributes to onnx's MatMul and Transpose operators based on the values set for transpose_a, transpose_b attributes.""" name, input_nodes, attrs = get_inputs(node, kwargs) input_node_a = input_nodes[0] input_node_b = input_nodes[1] ...
[ "def", "convert_dot", "(", "node", ",", "*", "*", "kwargs", ")", ":", "name", ",", "input_nodes", ",", "attrs", "=", "get_inputs", "(", "node", ",", "kwargs", ")", "input_node_a", "=", "input_nodes", "[", "0", "]", "input_node_b", "=", "input_nodes", "["...
31.736842
18.5
def export(target_folder, source_folders = None, class_type ='all', raise_errors = False): """ exports the existing scripts/instruments (future: probes) into folder as .b26 files Args: target_folder: target location of created .b26 script files source_folder: singel path or list of paths tha...
[ "def", "export", "(", "target_folder", ",", "source_folders", "=", "None", ",", "class_type", "=", "'all'", ",", "raise_errors", "=", "False", ")", ":", "if", "class_type", "not", "in", "(", "'all'", ",", "'scripts'", ",", "'instruments'", ",", "'probes'", ...
45.232558
23.232558
def queryset_from_filter_dict(filter_dict=None, model=None, app=None): """TODO: add fuzzy app, model and field (filter key) matching""" model = model or DEFAULT_MODEL app = app or DEFAULT_APP model = get_model(model, app) if filter_dict: return model.objects.filter(**filter_dict) re...
[ "def", "queryset_from_filter_dict", "(", "filter_dict", "=", "None", ",", "model", "=", "None", ",", "app", "=", "None", ")", ":", "model", "=", "model", "or", "DEFAULT_MODEL", "app", "=", "app", "or", "DEFAULT_APP", "model", "=", "get_model", "(", "model"...
36.666667
15.333333
def parse_headers(self, http_code): """ Parse http-code (like 'Header-X: foo\r\nHeader-Y: bar\r\n') and retrieve (save) HTTP-headers :param http_code: code to parse :return: None """ if self.__ro_flag: raise RuntimeError('Read-only object changing attempt') self.__headers = WHTTPHeaders.import_headers(h...
[ "def", "parse_headers", "(", "self", ",", "http_code", ")", ":", "if", "self", ".", "__ro_flag", ":", "raise", "RuntimeError", "(", "'Read-only object changing attempt'", ")", "self", ".", "__headers", "=", "WHTTPHeaders", ".", "import_headers", "(", "http_code", ...
35.666667
14.666667
def collect_touched_accounts(computation: BaseComputation) -> Iterable[bytes]: """ Collect all of the accounts that *may* need to be deleted based on `EIP-161 <https://eips.ethereum.org/EIPS/eip-161>`_. Checking whether they *do* need to be deleted happens in the caller. See also: https://github.c...
[ "def", "collect_touched_accounts", "(", "computation", ":", "BaseComputation", ")", "->", "Iterable", "[", "bytes", "]", ":", "# collect the coinbase account if it was touched via zero-fee transfer", "if", "computation", ".", "is_origin_computation", "and", "computation", "."...
43.184211
21.131579
def add(self, username, courseid, taskid, consumer_key, service_url, result_id): """ Add a job in the queue :param username: :param courseid: :param taskid: :param consumer_key: :param service_url: :param result_id: """ search = {"username": userna...
[ "def", "add", "(", "self", ",", "username", ",", "courseid", ",", "taskid", ",", "consumer_key", ",", "service_url", ",", "result_id", ")", ":", "search", "=", "{", "\"username\"", ":", "username", ",", "\"courseid\"", ":", "courseid", ",", "\"taskid\"", "...
48.294118
25.647059
def sitecol(self): """ Read the site collection from .filename and cache it """ if 'sitecol' in vars(self): return self.__dict__['sitecol'] if self.filename is None or not os.path.exists(self.filename): # case of nofilter/None sitecol return ...
[ "def", "sitecol", "(", "self", ")", ":", "if", "'sitecol'", "in", "vars", "(", "self", ")", ":", "return", "self", ".", "__dict__", "[", "'sitecol'", "]", "if", "self", ".", "filename", "is", "None", "or", "not", "os", ".", "path", ".", "exists", "...
36.333333
13.166667
def checksum(self, chunk_size=None, progress_callback=None, **kwargs): """Compute checksum of file.""" fp = self.open(mode='rb') try: value = self._compute_checksum( fp, size=self._size, chunk_size=None, progress_callback=progress_callback) exc...
[ "def", "checksum", "(", "self", ",", "chunk_size", "=", "None", ",", "progress_callback", "=", "None", ",", "*", "*", "kwargs", ")", ":", "fp", "=", "self", ".", "open", "(", "mode", "=", "'rb'", ")", "try", ":", "value", "=", "self", ".", "_comput...
33.75
15.833333
def raise_invalid_type_exception(self): """Raise invalid type.""" message = 'Expecting element type of %s' % ( self._parameter.element_type.__name__) err = ValueError(message) return err
[ "def", "raise_invalid_type_exception", "(", "self", ")", ":", "message", "=", "'Expecting element type of %s'", "%", "(", "self", ".", "_parameter", ".", "element_type", ".", "__name__", ")", "err", "=", "ValueError", "(", "message", ")", "return", "err" ]
37.5
8.666667
def _sorted_actions(self): """ Generate the sorted list of actions based on the "last" attribute. """ for a in filter(lambda _: not _.last and \ not self.is_action(_, 'parsers'), self._actions): yield a for a in filter(lambda _: _.last and \ ...
[ "def", "_sorted_actions", "(", "self", ")", ":", "for", "a", "in", "filter", "(", "lambda", "_", ":", "not", "_", ".", "last", "and", "not", "self", ".", "is_action", "(", "_", ",", "'parsers'", ")", ",", "self", ".", "_actions", ")", ":", "yield",...
40.230769
16.692308
def add_relationship( self, entity1_ilx: str, relationship_ilx: str, entity2_ilx: str) -> dict: """ Adds relationship connection in Interlex A relationship exists as 3 different parts: 1. entity with type term, cde, fde, or pde 2. entity with type...
[ "def", "add_relationship", "(", "self", ",", "entity1_ilx", ":", "str", ",", "relationship_ilx", ":", "str", ",", "entity2_ilx", ":", "str", ")", "->", "dict", ":", "url", "=", "self", ".", "base_url", "+", "'term/add-relationship'", "entity1_data", "=", "se...
39.825397
21.777778
def get_string_relative(strings: Sequence[str], prefix1: str, delta: int, prefix2: str, ignoreleadingcolon: bool = False, stripwhitespace: bool = True) -> Optional[str]: """ Finds a line (stri...
[ "def", "get_string_relative", "(", "strings", ":", "Sequence", "[", "str", "]", ",", "prefix1", ":", "str", ",", "delta", ":", "int", ",", "prefix2", ":", "str", ",", "ignoreleadingcolon", ":", "bool", "=", "False", ",", "stripwhitespace", ":", "bool", "...
36.357143
14.97619
def _connect(self,server=None,port=None): """Same as `ComponentStream.connect` but assume `self.lock` is acquired.""" if self.me.node or self.me.resource: raise Value("Component JID may have only domain defined") if not server: server=self.server if not port: ...
[ "def", "_connect", "(", "self", ",", "server", "=", "None", ",", "port", "=", "None", ")", ":", "if", "self", ".", "me", ".", "node", "or", "self", ".", "me", ".", "resource", ":", "raise", "Value", "(", "\"Component JID may have only domain defined\"", ...
43.545455
12
def headers_to_include_from_request(curr_request): ''' Define headers that needs to be included from the current request. ''' return { h: v for h, v in curr_request.META.items() if h in _settings.HEADERS_TO_INCLUDE}
[ "def", "headers_to_include_from_request", "(", "curr_request", ")", ":", "return", "{", "h", ":", "v", "for", "h", ",", "v", "in", "curr_request", ".", "META", ".", "items", "(", ")", "if", "h", "in", "_settings", ".", "HEADERS_TO_INCLUDE", "}" ]
39.666667
31
def event_update( self, event_id, name=None, season=None, start_time=None, event_group_id=None, status=None, account=None, **kwargs ): """ Update an event. This needs to be **proposed**. :param str event_id: Id of the event...
[ "def", "event_update", "(", "self", ",", "event_id", ",", "name", "=", "None", ",", "season", "=", "None", ",", "start_time", "=", "None", ",", "event_group_id", "=", "None", ",", "status", "=", "None", ",", "account", "=", "None", ",", "*", "*", "kw...
36.362319
17.144928
def installed(name, env=None, saltenv='base', user=None): """ Installs a single package, list of packages (comma separated) or packages in a requirements.txt Checks if the package is already in the environment. Check ocurres here so is only needed to `conda list` and `pip freeze` once name ...
[ "def", "installed", "(", "name", ",", "env", "=", "None", ",", "saltenv", "=", "'base'", ",", "user", "=", "None", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'changes'", ":", "{", "}", ",", "'comment'", ":", "''", ",", "'result'", ":...
38.141026
21.987179
def project(self, node): """ Translate a project node into SQLQuery. :param node: a treebrd node :return: a SQLQuery object for the tree rooted at node """ child_object = self.translate(node.child) child_object.select_block = str(node.attributes) return ch...
[ "def", "project", "(", "self", ",", "node", ")", ":", "child_object", "=", "self", ".", "translate", "(", "node", ".", "child", ")", "child_object", ".", "select_block", "=", "str", "(", "node", ".", "attributes", ")", "return", "child_object" ]
35.777778
9.777778
def get_user_profiles(self, prefix): """Get the user profil from the cache to the given prefix.""" filepath = "{}{}".format(self.base_path, prefix) return UserProfiles(filepath, prefix)
[ "def", "get_user_profiles", "(", "self", ",", "prefix", ")", ":", "filepath", "=", "\"{}{}\"", ".", "format", "(", "self", ".", "base_path", ",", "prefix", ")", "return", "UserProfiles", "(", "filepath", ",", "prefix", ")" ]
51.5
6.25
def get_account_entitlements_batch(self, user_ids): """GetAccountEntitlementsBatch. [Preview API] Returns AccountEntitlements that are currently assigned to the given list of users in the account :param [str] user_ids: List of user Ids. :rtype: [AccountEntitlement] """ ro...
[ "def", "get_account_entitlements_batch", "(", "self", ",", "user_ids", ")", ":", "route_values", "=", "{", "}", "route_values", "[", "'action'", "]", "=", "'GetUsersEntitlements'", "content", "=", "self", ".", "_serialize", ".", "body", "(", "user_ids", ",", "...
54.533333
19.066667
async def join_rtm(self, filters=None): """Join the real-time messaging service. Arguments: filters (:py:class:`dict`, optional): Dictionary mapping message filters to the functions they should dispatch to. Use a :py:class:`collections.OrderedDict` if precedence is ...
[ "async", "def", "join_rtm", "(", "self", ",", "filters", "=", "None", ")", ":", "if", "filters", "is", "None", ":", "filters", "=", "[", "cls", "(", "self", ")", "for", "cls", "in", "self", ".", "MESSAGE_FILTERS", "]", "url", "=", "await", "self", ...
42.357143
13.464286
def version(self): """RPM vesion string.""" stdout = Cmd.sh_e_out('{0} --version'.format(self.rpm_path)) rpm_version = stdout.split()[2] return rpm_version
[ "def", "version", "(", "self", ")", ":", "stdout", "=", "Cmd", ".", "sh_e_out", "(", "'{0} --version'", ".", "format", "(", "self", ".", "rpm_path", ")", ")", "rpm_version", "=", "stdout", ".", "split", "(", ")", "[", "2", "]", "return", "rpm_version" ...
36.6
13
def polygons_obb(polygons): """ Find the OBBs for a list of shapely.geometry.Polygons """ rectangles = [None] * len(polygons) transforms = [None] * len(polygons) for i, p in enumerate(polygons): transforms[i], rectangles[i] = polygon_obb(p) return np.array(transforms), np.array(recta...
[ "def", "polygons_obb", "(", "polygons", ")", ":", "rectangles", "=", "[", "None", "]", "*", "len", "(", "polygons", ")", "transforms", "=", "[", "None", "]", "*", "len", "(", "polygons", ")", "for", "i", ",", "p", "in", "enumerate", "(", "polygons", ...
35.333333
6.888889
def filter_by_labels(self, all_issues, kind): """ Filter issues for include/exclude labels. :param list(dict) all_issues: All issues. :param str kind: Either "issues" or "pull requests". :rtype: list(dict) :return: Filtered issues. """ filtered_issues = ...
[ "def", "filter_by_labels", "(", "self", ",", "all_issues", ",", "kind", ")", ":", "filtered_issues", "=", "self", ".", "include_issues_by_labels", "(", "all_issues", ")", "filtered", "=", "self", ".", "exclude_issues_by_labels", "(", "filtered_issues", ")", "if", ...
36.133333
16.266667
def generate(self, overwrite=False): """Generate a config file for an upstart service. """ super(Upstart, self).generate(overwrite=overwrite) svc_file_template = self.template_prefix + '.conf' self.svc_file_path = self.generate_into_prefix + '.conf' self.generate_file_f...
[ "def", "generate", "(", "self", ",", "overwrite", "=", "False", ")", ":", "super", "(", "Upstart", ",", "self", ")", ".", "generate", "(", "overwrite", "=", "overwrite", ")", "svc_file_template", "=", "self", ".", "template_prefix", "+", "'.conf'", "self",...
38.8
19.8
def write_translated(self, name, value, event=None): """Send a translated write request to the VI. """ data = {'name': name} if value is not None: data['value'] = self._massage_write_value(value) if event is not None: data['event'] = self._massage_write_va...
[ "def", "write_translated", "(", "self", ",", "name", ",", "value", ",", "event", "=", "None", ")", ":", "data", "=", "{", "'name'", ":", "name", "}", "if", "value", "is", "not", "None", ":", "data", "[", "'value'", "]", "=", "self", ".", "_massage_...
41.916667
10.75
def build_shapes(pfeed): """ Given a ProtoFeed, return DataFrame representing ``shapes.txt``. Only use shape IDs that occur in both ``pfeed.shapes`` and ``pfeed.frequencies``. Create reversed shapes where routes traverse shapes in both directions. """ rows = [] for shape, geom in pfe...
[ "def", "build_shapes", "(", "pfeed", ")", ":", "rows", "=", "[", "]", "for", "shape", ",", "geom", "in", "pfeed", ".", "shapes", "[", "[", "'shape_id'", ",", "'geometry'", "]", "]", ".", "itertuples", "(", "index", "=", "False", ")", ":", "if", "sh...
37.96875
14.28125
def upload_to_s3(file_path, config): """ Upload html file to S3 """ logging.info("Uploading file to S3 bucket: %s", config['s3_bucket_name']) s3 = boto3.resource('s3') s3_filename = config['s3_bucket_path'] + config['rendered_filename'] s3.Bucket(config['s3_bucket_name']).upload_file( fi...
[ "def", "upload_to_s3", "(", "file_path", ",", "config", ")", ":", "logging", ".", "info", "(", "\"Uploading file to S3 bucket: %s\"", ",", "config", "[", "'s3_bucket_name'", "]", ")", "s3", "=", "boto3", ".", "resource", "(", "'s3'", ")", "s3_filename", "=", ...
45.333333
13.444444
def _init_file(self): """Initialise the file header. This will erase any data previously in the file.""" header_length = 2*SECTOR_LENGTH if self.size > header_length: self.file.truncate(header_length) self.file.seek(0) self.file.write(header_length*b'\x00') se...
[ "def", "_init_file", "(", "self", ")", ":", "header_length", "=", "2", "*", "SECTOR_LENGTH", "if", "self", ".", "size", ">", "header_length", ":", "self", ".", "file", ".", "truncate", "(", "header_length", ")", "self", ".", "file", ".", "seek", "(", "...
42
7
def make_context(self, docker_file=None): """Determine the docker lines for this image""" kwargs = {"silent_build": self.harpoon.silent_build, "extra_context": self.commands.extra_context} if docker_file is None: docker_file = self.docker_file with ContextBuilder().make_conte...
[ "def", "make_context", "(", "self", ",", "docker_file", "=", "None", ")", ":", "kwargs", "=", "{", "\"silent_build\"", ":", "self", ".", "harpoon", ".", "silent_build", ",", "\"extra_context\"", ":", "self", ".", "commands", ".", "extra_context", "}", "if", ...
54.5
19.375
def union(self, *args): """ Produce an array that contains the union: each distinct element from all of the passed-in arrays. """ # setobj = set(self.obj) # for i, v in enumerate(args): # setobj = setobj + set(args[i]) # return self._wrap(self._clean._...
[ "def", "union", "(", "self", ",", "*", "args", ")", ":", "# setobj = set(self.obj)", "# for i, v in enumerate(args):", "# setobj = setobj + set(args[i])", "# return self._wrap(self._clean._toOriginal(setobj))", "args", "=", "list", "(", "args", ")", "args", ".", "insert...
37.666667
10.833333
def delete(self, force=False, volumes=False, **kwargs): """ remove this container; kwargs indicate that some container runtimes might accept more parameters :param force: bool, if container engine supports this, force the functionality :param volumes: bool, remove also associate...
[ "def", "delete", "(", "self", ",", "force", "=", "False", ",", "volumes", "=", "False", ",", "*", "*", "kwargs", ")", ":", "self", ".", "d", ".", "remove_container", "(", "self", ".", "get_id", "(", ")", ",", "v", "=", "volumes", ",", "force", "=...
42.5
20.9
def cli(ctx, group, user): """Remove a user from a group Output: an empty dictionary """ return ctx.gi.users.remove_from_group(group, user)
[ "def", "cli", "(", "ctx", ",", "group", ",", "user", ")", ":", "return", "ctx", ".", "gi", ".", "users", ".", "remove_from_group", "(", "group", ",", "user", ")" ]
18.75
19.75
def get_out_streamids(self): """Returns a set of output stream ids registered for this component""" if self.outputs is None: return set() if not isinstance(self.outputs, (list, tuple)): raise TypeError("Argument to outputs must be either list or tuple, given: %s" % str(typ...
[ "def", "get_out_streamids", "(", "self", ")", ":", "if", "self", ".", "outputs", "is", "None", ":", "return", "set", "(", ")", "if", "not", "isinstance", "(", "self", ".", "outputs", ",", "(", "list", ",", "tuple", ")", ")", ":", "raise", "TypeError"...
45.571429
22.571429
def block_ranges(start_block, last_block, step=5): """Returns 2-tuple ranges describing ranges of block from start_block to last_block Ranges do not overlap to facilitate use as ``toBlock``, ``fromBlock`` json-rpc arguments, which are both inclusive. """ if last_block is not None and start_b...
[ "def", "block_ranges", "(", "start_block", ",", "last_block", ",", "step", "=", "5", ")", ":", "if", "last_block", "is", "not", "None", "and", "start_block", ">", "last_block", ":", "raise", "TypeError", "(", "\"Incompatible start and stop arguments.\"", ",", "\...
35.647059
19.882353
def validateLogicalInterfaceConfiguration(self, logicalInterfaceId): """ Validate the logical interface configuration. Parameters: - logicalInterfaceId (string) Throws APIException on failure. """ req = ApiClient.oneLogicalInterfaceUrl % (self.host, "/draft", ...
[ "def", "validateLogicalInterfaceConfiguration", "(", "self", ",", "logicalInterfaceId", ")", ":", "req", "=", "ApiClient", ".", "oneLogicalInterfaceUrl", "%", "(", "self", ".", "host", ",", "\"/draft\"", ",", "logicalInterfaceId", ")", "body", "=", "{", "\"operati...
51.75
24.625
def _create_session(self, username, password): """Create HTTP session. Args: username (str): Timesketch username password (str): Timesketch password Returns: requests.Session: Session object. """ session = requests.Session() session.verify = False # Depending on SSL cert is ...
[ "def", "_create_session", "(", "self", ",", "username", ",", "password", ")", ":", "session", "=", "requests", ".", "Session", "(", ")", "session", ".", "verify", "=", "False", "# Depending on SSL cert is verifiable", "try", ":", "response", "=", "session", "....
32.769231
16.384615
def add_result(self, source, found, runtime): """ Adds a new record to the statistics 'database'. This function is intended to be called after a website has been scraped. The arguments indicate the function that was called, the time taken to scrap the website and a boolean indica...
[ "def", "add_result", "(", "self", ",", "source", ",", "found", ",", "runtime", ")", ":", "self", ".", "source_stats", "[", "source", ".", "__name__", "]", ".", "add_runtime", "(", "runtime", ")", "if", "found", ":", "self", ".", "source_stats", "[", "s...
47.833333
21
def detect_mode(term_hint="xterm-256color"): """Poor-mans color mode detection.""" if "ANSICON" in os.environ: return 16 elif os.environ.get("ConEmuANSI", "OFF") == "ON": return 256 else: term = os.environ.get("TERM", term_hint) if term.endswith("-256color") or term in ("...
[ "def", "detect_mode", "(", "term_hint", "=", "\"xterm-256color\"", ")", ":", "if", "\"ANSICON\"", "in", "os", ".", "environ", ":", "return", "16", "elif", "os", ".", "environ", ".", "get", "(", "\"ConEmuANSI\"", ",", "\"OFF\"", ")", "==", "\"ON\"", ":", ...
33.285714
17.071429
def write_loom(self, filename: PathLike, write_obsm_varm: bool = False): """Write ``.loom``-formatted hdf5 file. Parameters ---------- filename The filename. """ from .readwrite.write import write_loom write_loom(filename, self, write_obsm_varm = writ...
[ "def", "write_loom", "(", "self", ",", "filename", ":", "PathLike", ",", "write_obsm_varm", ":", "bool", "=", "False", ")", ":", "from", ".", "readwrite", ".", "write", "import", "write_loom", "write_loom", "(", "filename", ",", "self", ",", "write_obsm_varm...
32.3
19.1
def bbox(coordinates, crs, outname=None, format='ESRI Shapefile', overwrite=True): """ create a bounding box vector object or shapefile from coordinates and coordinate reference system. The CRS can be in either WKT, EPSG or PROJ4 format Parameters ---------- coordinates: dict a dict...
[ "def", "bbox", "(", "coordinates", ",", "crs", ",", "outname", "=", "None", ",", "format", "=", "'ESRI Shapefile'", ",", "overwrite", "=", "True", ")", ":", "srs", "=", "crsConvert", "(", "crs", ",", "'osr'", ")", "ring", "=", "ogr", ".", "Geometry", ...
33.808511
22.957447
def connect_widget(self, wid, getter=None, setter=None, signal=None, arg=None, update=True, flavour=None): """ Finish set-up by connecting the widget. The model was already specified in the constructor. *wid* is a wid...
[ "def", "connect_widget", "(", "self", ",", "wid", ",", "getter", "=", "None", ",", "setter", "=", "None", ",", "signal", "=", "None", ",", "arg", "=", "None", ",", "update", "=", "True", ",", "flavour", "=", "None", ")", ":", "if", "wid", "in", "...
32.685714
22
def analyse(file, length=None): """Analyse application layer packets. Keyword arguments: * file -- bytes or file-like object, packet to be analysed * length -- int, length of the analysing packet Returns: * Analysis -- an Analysis object from `pcapkit.analyser` """ if isin...
[ "def", "analyse", "(", "file", ",", "length", "=", "None", ")", ":", "if", "isinstance", "(", "file", ",", "bytes", ")", ":", "file", "=", "io", ".", "BytesIO", "(", "file", ")", "io_check", "(", "file", ")", "int_check", "(", "length", "or", "sys"...
24.833333
20.611111
def get_legend_text(obj): """Check if line is in legend. """ leg = obj.axes.get_legend() if leg is None: return None keys = [l.get_label() for l in leg.legendHandles if l is not None] values = [l.get_text() for l in leg.texts] label = obj.get_label() d = dict(zip(keys, values))...
[ "def", "get_legend_text", "(", "obj", ")", ":", "leg", "=", "obj", ".", "axes", ".", "get_legend", "(", ")", "if", "leg", "is", "None", ":", "return", "None", "keys", "=", "[", "l", ".", "get_label", "(", ")", "for", "l", "in", "leg", ".", "legen...
22.8125
19.25
def check_version(server, version, filename, timeout=SHORT_TIMEOUT): """Check for the latest version of OK and update accordingly.""" address = VERSION_ENDPOINT.format(server=server) print('Checking for software updates...') log.info('Existing OK version: %s', version) log.info('Checking latest ve...
[ "def", "check_version", "(", "server", ",", "version", ",", "filename", ",", "timeout", "=", "SHORT_TIMEOUT", ")", ":", "address", "=", "VERSION_ENDPOINT", ".", "format", "(", "server", "=", "server", ")", "print", "(", "'Checking for software updates...'", ")",...
38.454545
23.545455
def p_paramlist_paramlist(p): """ paramlist : paramlist COMMA ID """ p[0] = p[1] + [ID(p[3], value='', args=None, lineno=p.lineno(1), fname=CURRENT_FILE[-1])]
[ "def", "p_paramlist_paramlist", "(", "p", ")", ":", "p", "[", "0", "]", "=", "p", "[", "1", "]", "+", "[", "ID", "(", "p", "[", "3", "]", ",", "value", "=", "''", ",", "args", "=", "None", ",", "lineno", "=", "p", ".", "lineno", "(", "1", ...
37.6
9
def keyPressEvent(self, event): """ Handle key press event using the defined input handler. """ if self._process.state() != self._process.Running: return tc = self.textCursor() sel_start = tc.selectionStart() sel_end = tc.selectionEnd() tc.setP...
[ "def", "keyPressEvent", "(", "self", ",", "event", ")", ":", "if", "self", ".", "_process", ".", "state", "(", ")", "!=", "self", ".", "_process", ".", "Running", ":", "return", "tc", "=", "self", ".", "textCursor", "(", ")", "sel_start", "=", "tc", ...
40.294118
11.470588
def write_conf(conf_file, conf): ''' Write out an LXC configuration file This is normally only used internally. The format of the data structure must match that which is returned from ``lxc.read_conf()``, with ``out_format`` set to ``commented``. An example might look like: .. code-block:...
[ "def", "write_conf", "(", "conf_file", ",", "conf", ")", ":", "if", "not", "isinstance", "(", "conf", ",", "list", ")", ":", "raise", "SaltInvocationError", "(", "'Configuration must be passed as a list'", ")", "# construct the content prior to write to the file", "# to...
35.419355
19.258065
def mkclick(freq, sr=22050, duration=0.1): '''Generate a click sample. This replicates functionality from mir_eval.sonify.clicks, but exposes the target frequency and duration. ''' times = np.arange(int(sr * duration)) click = np.sin(2 * np.pi * times * freq / float(sr)) click *= np.exp(- ...
[ "def", "mkclick", "(", "freq", ",", "sr", "=", "22050", ",", "duration", "=", "0.1", ")", ":", "times", "=", "np", ".", "arange", "(", "int", "(", "sr", "*", "duration", ")", ")", "click", "=", "np", ".", "sin", "(", "2", "*", "np", ".", "pi"...
28.916667
19.916667
def delete_role(resource_root, service_name, name, cluster_name="default"): """ Delete a role by name @param resource_root: The root Resource object. @param service_name: Service name @param name: Role name @param cluster_name: Cluster name @return: The deleted ApiRole object """ return call(resource_...
[ "def", "delete_role", "(", "resource_root", ",", "service_name", ",", "name", ",", "cluster_name", "=", "\"default\"", ")", ":", "return", "call", "(", "resource_root", ".", "delete", ",", "_get_role_path", "(", "cluster_name", ",", "service_name", ",", "name", ...
35.181818
10.818182
def add_protocols(session, verbose): """Adds protocols""" # 1. DEFINITIONS enroll_session = [1] client_probe_session = [2] impostor_probe_session = [3] protocols = ['A'] # 2. ADDITIONS TO THE SQL DATABASE protocolPurpose_list = [('eval', 'enrol'), ('eval', 'probe')] for proto in protocols: p = P...
[ "def", "add_protocols", "(", "session", ",", "verbose", ")", ":", "# 1. DEFINITIONS", "enroll_session", "=", "[", "1", "]", "client_probe_session", "=", "[", "2", "]", "impostor_probe_session", "=", "[", "3", "]", "protocols", "=", "[", "'A'", "]", "# 2. ADD...
37.711111
24.2
def make_parser(parser_creator=None, **kwargs): """Returns a base argument parser for the ray.tune tool. Args: parser_creator: A constructor for the parser class. kwargs: Non-positional args to be passed into the parser class constructor. """ if parser_creator: pars...
[ "def", "make_parser", "(", "parser_creator", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "parser_creator", ":", "parser", "=", "parser_creator", "(", "*", "*", "kwargs", ")", "else", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "...
36.455224
20.014925
def configured_class(cls): # type: () -> type """Returns the currently configured class.""" base = cls.configurable_base() # Manually mangle the private name to see whether this base # has been configured (and not another base higher in the # hierarchy). if base._...
[ "def", "configured_class", "(", "cls", ")", ":", "# type: () -> type", "base", "=", "cls", ".", "configurable_base", "(", ")", "# Manually mangle the private name to see whether this base", "# has been configured (and not another base higher in the", "# hierarchy).", "if", "base"...
45.2
15.3
def getExpiresIn(self, now=None): """ This returns the number of seconds this association is still valid for, or C{0} if the association is no longer valid. @return: The number of seconds this association is still valid for, or C{0} if the association is no longer valid. ...
[ "def", "getExpiresIn", "(", "self", ",", "now", "=", "None", ")", ":", "if", "now", "is", "None", ":", "now", "=", "int", "(", "time", ".", "time", "(", ")", ")", "return", "max", "(", "0", ",", "self", ".", "issued", "+", "self", ".", "lifetim...
30.4
22
def authenticate(url, username, password): ''' Queries an asset behind CMU's WebISO wall. It uses Shibboleth authentication (see: http://dev.e-taxonomy.eu/trac/wiki/ShibbolethProtocol) Note that you can use this to authenticate stuff beyond just grades! (any CMU service) Sample usage: s = authen...
[ "def", "authenticate", "(", "url", ",", "username", ",", "password", ")", ":", "# We're using a Requests (http://www.python-requests.org/en/latest/) session", "s", "=", "requests", ".", "Session", "(", ")", "# 1. Initiate sequence by querying the protected asset", "data", "="...
39.107692
23.723077
def add_file(self, src, dest=None): """Add the file at ``src`` to the archive. If ``dest`` is ``None`` then it is added under just the original filename. So ``add_file('foo/bar.txt')`` ends up at ``bar.txt`` in the archive, while ``add_file('bar.txt', 'foo/bar.txt')`` ends up at ...
[ "def", "add_file", "(", "self", ",", "src", ",", "dest", "=", "None", ")", ":", "dest", "=", "dest", "or", "os", ".", "path", ".", "basename", "(", "src", ")", "with", "open", "(", "src", ",", "'rb'", ")", "as", "fp", ":", "contents", "=", "fp"...
38
17
def logger(self): """ Instantiates and returns a ServiceLogger instance """ if not hasattr(self, '_logger') or not self._logger: self._logger = ServiceLogger() return self._logger
[ "def", "logger", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'_logger'", ")", "or", "not", "self", ".", "_logger", ":", "self", ".", "_logger", "=", "ServiceLogger", "(", ")", "return", "self", ".", "_logger" ]
32.142857
10.714286
def setup_environ(self): """ Setup the environ dictionary and add the `'ws4py.socket'` key. Its associated value is the real socket underlying socket. """ SimpleHandler.setup_environ(self) self.environ['ws4py.socket'] = get_connection(self.environ['wsgi.input']) ...
[ "def", "setup_environ", "(", "self", ")", ":", "SimpleHandler", ".", "setup_environ", "(", "self", ")", "self", ".", "environ", "[", "'ws4py.socket'", "]", "=", "get_connection", "(", "self", ".", "environ", "[", "'wsgi.input'", "]", ")", "self", ".", "htt...
42.888889
12.888889
def __lock_density_if_defined(self, stack: dict): """lock (True) the density lock if the density has been been defined during initialization Store the resulting dictionary into density_lock Parameters: =========== stack: dictionary (optional) if not provided, the entir...
[ "def", "__lock_density_if_defined", "(", "self", ",", "stack", ":", "dict", ")", ":", "if", "self", ".", "stack", "==", "{", "}", ":", "density_lock", "=", "{", "}", "else", ":", "density_lock", "=", "self", ".", "density_lock", "for", "_compound", "in",...
33.590909
14.727273
def sanitize_resources(resource): """Cleans up incoming scene data :param resource: The dict with scene data to be sanitized. :returns: Cleaned up dict. """ try: resource[ATTR_HUB_NAME_UNICODE] = base64_to_unicode(resource[ATTR_HUB_NAME]) return resource ...
[ "def", "sanitize_resources", "(", "resource", ")", ":", "try", ":", "resource", "[", "ATTR_HUB_NAME_UNICODE", "]", "=", "base64_to_unicode", "(", "resource", "[", "ATTR_HUB_NAME", "]", ")", "return", "resource", "except", "(", "KeyError", ",", "TypeError", ")", ...
34.666667
16.083333
def find_one_app(zero_ok=False, more_ok=True, **kwargs): """ :param zero_ok: If False (default), :class:`~dxpy.exceptions.DXSearchError` is raised if the search has 0 results; if True, returns None if the search has 0 results :type zero_ok: bool :param more_ok: If False, ...
[ "def", "find_one_app", "(", "zero_ok", "=", "False", ",", "more_ok", "=", "True", ",", "*", "*", "kwargs", ")", ":", "return", "_find_one", "(", "find_apps", ",", "zero_ok", "=", "zero_ok", ",", "more_ok", "=", "more_ok", ",", "*", "*", "kwargs", ")" ]
39
21.333333
def get_latex_maybe_optional_arg(s, pos, **parse_flags): """ Attempts to parse an optional argument. Returns a tuple `(groupnode, pos, len)` if success, otherwise returns None. .. deprecated:: 1.0 Please use :py:meth:`LatexWalker.get_latex_maybe_optional_arg()` instead. """ return Latex...
[ "def", "get_latex_maybe_optional_arg", "(", "s", ",", "pos", ",", "*", "*", "parse_flags", ")", ":", "return", "LatexWalker", "(", "s", ",", "*", "*", "parse_flags", ")", ".", "get_latex_maybe_optional_arg", "(", "pos", "=", "pos", ")" ]
37.3
24.1
def write(self, fptr): """Write an Image Header box to file. """ fptr.write(struct.pack('>I4s', 22, b'ihdr')) # signedness and bps are stored together in a single byte bit_depth_signedness = 0x80 if self.signed else 0x00 bit_depth_signedness |= self.bits_per_component - ...
[ "def", "write", "(", "self", ",", "fptr", ")", ":", "fptr", ".", "write", "(", "struct", ".", "pack", "(", "'>I4s'", ",", "22", ",", "b'ihdr'", ")", ")", "# signedness and bps are stored together in a single byte", "bit_depth_signedness", "=", "0x80", "if", "s...
45.529412
14.823529
def sync(self): """Overwrite local customer profile data with remote data""" output = get_profile(self.profile_id) output['response'].raise_if_error() for payment_profile in output['payment_profiles']: instance, created = CustomerPaymentProfile.objects.get_or_create( ...
[ "def", "sync", "(", "self", ")", ":", "output", "=", "get_profile", "(", "self", ".", "profile_id", ")", "output", "[", "'response'", "]", ".", "raise_if_error", "(", ")", "for", "payment_profile", "in", "output", "[", "'payment_profiles'", "]", ":", "inst...
47.1
15.1
def filter_by_IDs(self, ids, ID=None): """ Keep only Measurements with given IDs. """ fil = lambda x: x in ids return self.filter_by_attr('ID', fil, ID)
[ "def", "filter_by_IDs", "(", "self", ",", "ids", ",", "ID", "=", "None", ")", ":", "fil", "=", "lambda", "x", ":", "x", "in", "ids", "return", "self", ".", "filter_by_attr", "(", "'ID'", ",", "fil", ",", "ID", ")" ]
31.166667
4.166667
def column_state(num_lev=30, num_lat=1, lev=None, lat=None, water_depth=1.0): """Sets up a state variable dictionary consisting of temperatures for atmospheric column (``Tatm``) and surface mixed layer (``Ts``). Surface temperature is alwa...
[ "def", "column_state", "(", "num_lev", "=", "30", ",", "num_lat", "=", "1", ",", "lev", "=", "None", ",", "lat", "=", "None", ",", "water_depth", "=", "1.0", ")", ":", "if", "lat", "is", "not", "None", ":", "num_lat", "=", "np", ".", "array", "("...
42.534247
22.534247
def _decrypt_data_key(self, encrypted_data_key, algorithm, encryption_context): """Decrypts an encrypted data key and returns the plaintext. :param data_key: Encrypted data key :type data_key: aws_encryption_sdk.structures.EncryptedDataKey :param algorithm: Algorithm object which direct...
[ "def", "_decrypt_data_key", "(", "self", ",", "encrypted_data_key", ",", "algorithm", ",", "encryption_context", ")", ":", "# Wrapped EncryptedDataKey to deserialized EncryptedData", "encrypted_wrapped_key", "=", "aws_encryption_sdk", ".", "internal", ".", "formatting", ".", ...
53.357143
24.464286
def get_mode(self, gpio): """ Returns the gpio mode. gpio:= 0-53. Returns a value as follows . . 0 = INPUT 1 = OUTPUT 2 = ALT5 3 = ALT4 4 = ALT0 5 = ALT1 6 = ALT2 7 = ALT3 . . ... print(pi...
[ "def", "get_mode", "(", "self", ",", "gpio", ")", ":", "res", "=", "yield", "from", "self", ".", "_pigpio_aio_command", "(", "_PI_CMD_MODEG", ",", "gpio", ",", "0", ")", "return", "_u2i", "(", "res", ")" ]
16.961538
23.346154
def from_code_array(self): """Replaces everything in pys_file from code_array""" for key in self._section2writer: self.pys_file.write(key) self._section2writer[key]() try: if self.pys_file.aborted: break except Attribu...
[ "def", "from_code_array", "(", "self", ")", ":", "for", "key", "in", "self", ".", "_section2writer", ":", "self", ".", "pys_file", ".", "write", "(", "key", ")", "self", ".", "_section2writer", "[", "key", "]", "(", ")", "try", ":", "if", "self", "."...
29.764706
13.823529
def plot_resp_diff(signal, rect_signal, sample_rate): """ Function design to generate a Bokeh figure containing the evolution of RIP signal, when respiration was suspended for a long period, the rectangular signal that defines the stages of inhalation and exhalation and the first derivative of the RIP s...
[ "def", "plot_resp_diff", "(", "signal", ",", "rect_signal", ",", "sample_rate", ")", ":", "signal", "=", "numpy", ".", "array", "(", "signal", ")", "-", "numpy", ".", "average", "(", "signal", ")", "rect_signal", "=", "numpy", ".", "array", "(", "rect_si...
39.745098
25.941176
def get_content_models(cls): """ Return all subclasses of the concrete model. """ concrete_model = base_concrete_model(ContentTyped, cls) return [m for m in apps.get_models() if m is not concrete_model and issubclass(m, concrete_model)]
[ "def", "get_content_models", "(", "cls", ")", ":", "concrete_model", "=", "base_concrete_model", "(", "ContentTyped", ",", "cls", ")", "return", "[", "m", "for", "m", "in", "apps", ".", "get_models", "(", ")", "if", "m", "is", "not", "concrete_model", "and...
54.6
15.2
def add_choice(self, text, inline_region, name='', identifier=None): """stub""" choice_display_text = self._choice_text_metadata['default_string_values'][0] choice_display_text['text'] = text if identifier is None: identifier = str(ObjectId()) choice = { '...
[ "def", "add_choice", "(", "self", ",", "text", ",", "inline_region", ",", "name", "=", "''", ",", "identifier", "=", "None", ")", ":", "choice_display_text", "=", "self", ".", "_choice_text_metadata", "[", "'default_string_values'", "]", "[", "0", "]", "choi...
40.3125
20.5625
def delete(self, refobj): """Delete the content of the given refobj :param refobj: the refobj that represents the content that should be deleted :type refobj: refobj :returns: None :rtype: None :raises: None """ refobjinter = self.get_refobjinter() ...
[ "def", "delete", "(", "self", ",", "refobj", ")", ":", "refobjinter", "=", "self", ".", "get_refobjinter", "(", ")", "reference", "=", "refobjinter", ".", "get_reference", "(", "refobj", ")", "if", "reference", ":", "fullns", "=", "cmds", ".", "referenceQu...
40.789474
19.736842
def active(self): """ Return the currently active :class:`~opentracing.Scope` which can be used to access the currently active :attr:`Scope.span`. :return: the :class:`~opentracing.Scope` that is active, or ``None`` if not available. """ context = se...
[ "def", "active", "(", "self", ")", ":", "context", "=", "self", ".", "_get_context", "(", ")", "if", "not", "context", ":", "return", "super", "(", "TornadoScopeManager", ",", "self", ")", ".", "active", "return", "context", ".", "active" ]
29.133333
17.933333
def calculate_gamma_matrix(magnetic_states, Omega=1): r"""Calculate the matrix of decay between states. This function calculates the matrix $\gamma_{ij}$ of decay rates between states |i> and |j> (in the units specified by the Omega argument). >>> g=State("Rb",87,5,0,1/Integer(2)) >>> e=State("Rb"...
[ "def", "calculate_gamma_matrix", "(", "magnetic_states", ",", "Omega", "=", "1", ")", ":", "Ne", "=", "len", "(", "magnetic_states", ")", "II", "=", "magnetic_states", "[", "0", "]", ".", "i", "gamma", "=", "[", "[", "0.0", "for", "j", "in", "range", ...
156.380282
150.830986
def _get_name(self, name): """ Find a team's name and abbreviation. Given the team's HTML name tag, determine their name, abbreviation, and whether or not they compete in Division-I. Parameters ---------- name : PyQuery object A PyQuery object of a t...
[ "def", "_get_name", "(", "self", ",", "name", ")", ":", "team_name", "=", "name", ".", "text", "(", ")", "abbr", "=", "self", ".", "_parse_abbreviation", "(", "name", ")", "non_di", "=", "False", "if", "not", "abbr", ":", "abbr", "=", "team_name", "n...
33.444444
20.925926
def set_assessments(self, assessment_ids): """Sets the assessments. arg: assessment_ids (osid.id.Id[]): the assessment ``Ids`` raise: InvalidArgument - ``assessment_ids`` is invalid raise: NullArgument - ``assessment_ids`` is ``null`` raise: NoAccess - ``Metadata.isReadOnl...
[ "def", "set_assessments", "(", "self", ",", "assessment_ids", ")", ":", "# Implemented from template for osid.learning.ActivityForm.set_assets_template", "if", "not", "isinstance", "(", "assessment_ids", ",", "list", ")", ":", "raise", "errors", ".", "InvalidArgument", "(...
44.285714
15.761905
def add_resource(self, handler, uri, methods=frozenset({'GET'}), host=None, strict_slashes=None, version=None, name=None, **kwargs): """ Create a blueprint resource route from a function. :param uri: endpoint at which the route will be accessible. ...
[ "def", "add_resource", "(", "self", ",", "handler", ",", "uri", ",", "methods", "=", "frozenset", "(", "{", "'GET'", "}", ")", ",", "host", "=", "None", ",", "strict_slashes", "=", "None", ",", "version", "=", "None", ",", "name", "=", "None", ",", ...
42.210526
19.578947
def choose_tag(self: object, tokens: List[str], index: int, history: List[str]): """ Looks up token in ``lemmas`` dict and returns the corresponding value as lemma. :rtype: str :type tokens: list :param tokens: List of tokens to be lemmatized :type index: int ...
[ "def", "choose_tag", "(", "self", ":", "object", ",", "tokens", ":", "List", "[", "str", "]", ",", "index", ":", "int", ",", "history", ":", "List", "[", "str", "]", ")", ":", "keys", "=", "self", ".", "lemmas", ".", "keys", "(", ")", "if", "to...
39
15.533333
def _make_valid_bounds(self, test_bounds): """ Private method: process input bounds into a form acceptable by scipy.optimize, and check the validity of said bounds. :param test_bounds: minimum and maximum weight of an asset :type test_bounds: tuple :raises ValueError: if...
[ "def", "_make_valid_bounds", "(", "self", ",", "test_bounds", ")", ":", "if", "len", "(", "test_bounds", ")", "!=", "2", "or", "not", "isinstance", "(", "test_bounds", ",", "tuple", ")", ":", "raise", "ValueError", "(", "\"test_bounds must be a tuple of (lower b...
45.35
17.95
def itemData(self, treeItem, column, role=Qt.DisplayRole): """ Returns the data stored under the given role for the item. O """ if role == Qt.DisplayRole: if column == self.COL_NODE_NAME: return treeItem.nodeName elif column == self.COL_NODE_PATH: ...
[ "def", "itemData", "(", "self", ",", "treeItem", ",", "column", ",", "role", "=", "Qt", ".", "DisplayRole", ")", ":", "if", "role", "==", "Qt", ".", "DisplayRole", ":", "if", "column", "==", "self", ".", "COL_NODE_NAME", ":", "return", "treeItem", ".",...
46.704918
14.52459
def __assert_true(returned): ''' Test if an boolean is True ''' result = "Pass" try: assert (returned is True), "{0} not True".format(returned) except AssertionError as err: result = "Fail: " + six.text_type(err) return result
[ "def", "__assert_true", "(", "returned", ")", ":", "result", "=", "\"Pass\"", "try", ":", "assert", "(", "returned", "is", "True", ")", ",", "\"{0} not True\"", ".", "format", "(", "returned", ")", "except", "AssertionError", "as", "err", ":", "result", "=...
29.7
18.3