text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def api_version(profile=None, **connection_args): ''' Returns the API version derived from endpoint's response. CLI Example: .. code-block:: bash salt '*' keystone.api_version ''' kwargs = _get_kwargs(profile=profile, **connection_args) auth_url = kwargs.get('auth_url', kwargs.get...
[ "def", "api_version", "(", "profile", "=", "None", ",", "*", "*", "connection_args", ")", ":", "kwargs", "=", "_get_kwargs", "(", "profile", "=", "profile", ",", "*", "*", "connection_args", ")", "auth_url", "=", "kwargs", ".", "get", "(", "'auth_url'", ...
31.352941
26.882353
def trim_Ns(self): '''Removes any leading or trailing N or n characters from the sequence''' # get index of first base that is not an N i = 0 while i < len(self) and self.seq[i] in 'nN': i += 1 # strip off start of sequence and quality self.seq = self.seq[i:]...
[ "def", "trim_Ns", "(", "self", ")", ":", "# get index of first base that is not an N", "i", "=", "0", "while", "i", "<", "len", "(", "self", ")", "and", "self", ".", "seq", "[", "i", "]", "in", "'nN'", ":", "i", "+=", "1", "# strip off start of sequence an...
32.428571
18.571429
def copychildren(self, newdoc=None, idsuffix=""): """Generator creating a deep copy of the children of this element. If idsuffix is a string, if set to True, a random idsuffix will be generated including a random 32-bit hash""" if idsuffix is True: idsuffix = ".copy." + "%08x" % random.getrandbits(32) #...
[ "def", "copychildren", "(", "self", ",", "newdoc", "=", "None", ",", "idsuffix", "=", "\"\"", ")", ":", "if", "idsuffix", "is", "True", ":", "idsuffix", "=", "\".copy.\"", "+", "\"%08x\"", "%", "random", ".", "getrandbits", "(", "32", ")", "#random 32-bi...
70.375
23.75
def _observe_mode(self, change): """ If the mode changes. Refresh the items. """ block = self.block if block and self.is_initialized and change['type'] == 'update': if change['oldvalue'] == 'replace': raise NotImplementedError for c in sel...
[ "def", "_observe_mode", "(", "self", ",", "change", ")", ":", "block", "=", "self", ".", "block", "if", "block", "and", "self", ".", "is_initialized", "and", "change", "[", "'type'", "]", "==", "'update'", ":", "if", "change", "[", "'oldvalue'", "]", "...
35.75
9.416667
def _to_enos_roles(roles): """Transform the roles to use enoslib.host.Host hosts. Args: roles (dict): roles returned by :py:func:`enoslib.infra.provider.Provider.init` """ def to_host(h): extra = {} # create extra_vars for the nics # network_role = ethX ...
[ "def", "_to_enos_roles", "(", "roles", ")", ":", "def", "to_host", "(", "h", ")", ":", "extra", "=", "{", "}", "# create extra_vars for the nics", "# network_role = ethX", "for", "nic", ",", "roles", "in", "h", "[", "\"nics\"", "]", ":", "for", "role", "in...
26.869565
16.73913
def read_alignment(out_sam, loci, seqs, out_file): """read which seqs map to which loci and return a tab separated file""" hits = defaultdict(list) with open(out_file, "w") as out_handle: samfile = pysam.Samfile(out_sam, "r") for a in samfile.fetch(): if not a.is_unmapped: ...
[ "def", "read_alignment", "(", "out_sam", ",", "loci", ",", "seqs", ",", "out_file", ")", ":", "hits", "=", "defaultdict", "(", "list", ")", "with", "open", "(", "out_file", ",", "\"w\"", ")", "as", "out_handle", ":", "samfile", "=", "pysam", ".", "Samf...
41.85
14.95
def connect(self, protocolFactory): """Starts a process and connect a protocol to it. """ deferred = self._startProcess() deferred.addCallback(self._connectRelay, protocolFactory) deferred.addCallback(self._startRelay) return deferred
[ "def", "connect", "(", "self", ",", "protocolFactory", ")", ":", "deferred", "=", "self", ".", "_startProcess", "(", ")", "deferred", ".", "addCallback", "(", "self", ".", "_connectRelay", ",", "protocolFactory", ")", "deferred", ".", "addCallback", "(", "se...
39.428571
7.714286
def _match_mask(mask, ctype): """ Determine if a content type mask matches a given content type. :param mask: The content type mask, taken from the Accept header. :param ctype: The content type to match to the mask. """ # Handle the simple cases first if '*' not in mask: ...
[ "def", "_match_mask", "(", "mask", ",", "ctype", ")", ":", "# Handle the simple cases first", "if", "'*'", "not", "in", "mask", ":", "return", "ctype", "==", "mask", "elif", "mask", "==", "'*/*'", ":", "return", "True", "elif", "not", "mask", ".", "endswit...
26.65
16.35
def class_names(self, nodes): """return class names if needed in diagram""" names = [] for node in nodes: if isinstance(node, astroid.Instance): node = node._proxied if ( isinstance(node, astroid.ClassDef) and hasattr(node, ...
[ "def", "class_names", "(", "self", ",", "nodes", ")", ":", "names", "=", "[", "]", "for", "node", "in", "nodes", ":", "if", "isinstance", "(", "node", ",", "astroid", ".", "Instance", ")", ":", "node", "=", "node", ".", "_proxied", "if", "(", "isin...
34.8
10.066667
def match_nth(self, el, nth): """Match `nth` elements.""" matched = True for n in nth: matched = False if n.selectors and not self.match_selectors(el, n.selectors): break parent = self.get_parent(el) if parent is None: ...
[ "def", "match_nth", "(", "self", ",", "el", ",", "nth", ")", ":", "matched", "=", "True", "for", "n", "in", "nth", ":", "matched", "=", "False", "if", "n", ".", "selectors", "and", "not", "self", ".", "match_selectors", "(", "el", ",", "n", ".", ...
40.52
15.95
def get_encodings_from_content(content): """Returns encodings from given content string. :param content: bytestring to extract encodings from. """ charset_re = re.compile(r'<meta.*?charset=["\']*(.+?)["\'>]', flags=re.I) return charset_re.findall(content)
[ "def", "get_encodings_from_content", "(", "content", ")", ":", "charset_re", "=", "re", ".", "compile", "(", "r'<meta.*?charset=[\"\\']*(.+?)[\"\\'>]'", ",", "flags", "=", "re", ".", "I", ")", "return", "charset_re", ".", "findall", "(", "content", ")" ]
30
19.555556
def _flatten(l): """helper to flatten a list of lists """ res = [] for sublist in l: if isinstance(sublist, whaaaaat.Separator): res.append(sublist) else: for item in sublist: res.append(item) return res
[ "def", "_flatten", "(", "l", ")", ":", "res", "=", "[", "]", "for", "sublist", "in", "l", ":", "if", "isinstance", "(", "sublist", ",", "whaaaaat", ".", "Separator", ")", ":", "res", ".", "append", "(", "sublist", ")", "else", ":", "for", "item", ...
24.454545
14.545455
def intersects_segment(self, seg): """ Returns True if any segmentlist in self intersects the segment, otherwise returns False. """ return any(value.intersects_segment(seg) for value in self.itervalues())
[ "def", "intersects_segment", "(", "self", ",", "seg", ")", ":", "return", "any", "(", "value", ".", "intersects_segment", "(", "seg", ")", "for", "value", "in", "self", ".", "itervalues", "(", ")", ")" ]
34.833333
10.166667
def generic_model(cls, site_class, **kwds): """Use generic model parameters based on site class. Parameters ---------- site_class: str Site classification. Possible options are: * Geomatrix AB * Geomatrix CD * USGS AB * USG...
[ "def", "generic_model", "(", "cls", ",", "site_class", ",", "*", "*", "kwds", ")", ":", "p", "=", "dict", "(", "cls", ".", "PARAMS", "[", "site_class", "]", ")", "p", ".", "update", "(", "kwds", ")", "return", "cls", "(", "*", "*", "p", ")" ]
30.416667
17.055556
def distance(x0, x1, y0, y1): """ Function that calculates the square of the distance between two points. Parameters ----- x0: x - coordinate of point 0 x1: x - coordinate of point 1 y0: y - coordinate of point 0 y1: y - coordinate of point 1 Returns -----...
[ "def", "distance", "(", "x0", ",", "x1", ",", "y0", ",", "y1", ")", ":", "# Calculate square of the distance between two points (Pythagoras)", "distance", "=", "(", "x1", ".", "values", "-", "x0", ".", "values", ")", "*", "(", "x1", ".", "values", "-", "x0...
25.347826
20.695652
def _setup_root_filesystem(self, root_dir): """Setup the filesystem layout in the given root directory. Create a copy of the existing proc- and dev-mountpoints in the specified root directory. Afterwards we chroot into it. @param root_dir: The path of the root directory that is used to ...
[ "def", "_setup_root_filesystem", "(", "self", ",", "root_dir", ")", ":", "root_dir", "=", "root_dir", ".", "encode", "(", ")", "# Create an empty proc folder into the root dir. The grandchild still needs a view of", "# the old /proc, therefore we do not mount a fresh /proc here.", ...
46.375
24.541667
def _ParseInsserv(self, data): """/etc/insserv.conf* entries define system facilities. Full format details are in man 8 insserv, but the basic structure is: $variable facility1 facility2 $second_variable facility3 $variable Any init script that specifies Required-Start: $second_vari...
[ "def", "_ParseInsserv", "(", "self", ",", "data", ")", ":", "p", "=", "config_file", ".", "FieldParser", "(", ")", "entries", "=", "p", ".", "ParseEntries", "(", "data", ")", "raw", "=", "{", "e", "[", "0", "]", ":", "e", "[", "1", ":", "]", "f...
34.423077
15.192308
def temporary(self, path): """Establishes a temporary build root, restoring the prior build root on exit.""" if path is None: raise ValueError('Can only temporarily establish a build root given a path.') prior = self._root_dir self._root_dir = path try: yield finally: self._roo...
[ "def", "temporary", "(", "self", ",", "path", ")", ":", "if", "path", "is", "None", ":", "raise", "ValueError", "(", "'Can only temporarily establish a build root given a path.'", ")", "prior", "=", "self", ".", "_root_dir", "self", ".", "_root_dir", "=", "path"...
32.4
20.7
def list_active_gen(self, pattern=None): """Generator for the LIST ACTIVE command. Generates a list of active newsgroups that match the specified pattern. If no pattern is specfied then all active groups are generated. See <http://tools.ietf.org/html/rfc3977#section-7.6.3> Arg...
[ "def", "list_active_gen", "(", "self", ",", "pattern", "=", "None", ")", ":", "args", "=", "pattern", "if", "args", "is", "None", ":", "cmd", "=", "\"LIST\"", "else", ":", "cmd", "=", "\"LIST ACTIVE\"", "code", ",", "message", "=", "self", ".", "comman...
29.857143
21.642857
def pseudo_raw_input(self, prompt: str) -> str: """Began life as a copy of cmd's cmdloop; like raw_input but - accounts for changed stdin, stdout - if input is a pipe (instead of a tty), look at self.echo to decide whether to print the prompt and the input """ if self....
[ "def", "pseudo_raw_input", "(", "self", ",", "prompt", ":", "str", ")", "->", "str", ":", "if", "self", ".", "use_rawinput", ":", "try", ":", "if", "sys", ".", "stdin", ".", "isatty", "(", ")", ":", "# Wrap in try since terminal_lock may not be locked when thi...
42.54902
18.411765
def get_self_url(request_data): """ Returns the URL of the current host + current view + query. :param request_data: The request as a dict :type: dict :return: The url of current host + current view + query :rtype: string """ self_url_host = OneLogin_Sam...
[ "def", "get_self_url", "(", "request_data", ")", ":", "self_url_host", "=", "OneLogin_Saml2_Utils", ".", "get_self_url_host", "(", "request_data", ")", "request_uri", "=", "''", "if", "'request_uri'", "in", "request_data", ":", "request_uri", "=", "request_data", "[...
34.047619
18.428571
def assign_highest_value(exposure, hazard): """Assign the highest hazard value to an indivisible feature. For indivisible polygon exposure layers such as buildings, we need to assigned the greatest hazard that each polygon touches and use that as the effective hazard class. Issue https://github.co...
[ "def", "assign_highest_value", "(", "exposure", ",", "hazard", ")", ":", "output_layer_name", "=", "assign_highest_value_steps", "[", "'output_layer_name'", "]", "hazard_inasafe_fields", "=", "hazard", ".", "keywords", "[", "'inasafe_fields'", "]", "if", "not", "hazar...
36.481818
22.518182
def initialise_api( debug=False, host=None, key=None, proxy=None, user_agent=None, headers=None, rate_limit=True, rate_limit_callback=None, error_retry_max=None, error_retry_backoff=None, error_retry_codes=None, ): """Initialise the API.""" config = cloudsmith_api.Con...
[ "def", "initialise_api", "(", "debug", "=", "False", ",", "host", "=", "None", ",", "key", "=", "None", ",", "proxy", "=", "None", ",", "user_agent", "=", "None", ",", "headers", "=", "None", ",", "rate_limit", "=", "True", ",", "rate_limit_callback", ...
30.257143
16.514286
def _validate_snap_name(name, snap_name, strict=True, runas=None): ''' Validate snapshot name and convert to snapshot ID :param str name: Name/ID of VM whose snapshot name is being validated :param str snap_name: Name/ID of snapshot :param bool strict: Raise an exception i...
[ "def", "_validate_snap_name", "(", "name", ",", "snap_name", ",", "strict", "=", "True", ",", "runas", "=", "None", ")", ":", "snap_name", "=", "salt", ".", "utils", ".", "data", ".", "decode", "(", "snap_name", ")", "# Try to convert snapshot name to an ID wi...
30.043478
23.608696
def _detect_sse3(self): "Does this compiler support SSE3 intrinsics?" self._print_support_start('SSE3') result = self.hasfunction('__m128 v; _mm_hadd_ps(v,v)', include='<pmmintrin.h>', extra_postargs=['-msse3']) self._print_support_en...
[ "def", "_detect_sse3", "(", "self", ")", ":", "self", ".", "_print_support_start", "(", "'SSE3'", ")", "result", "=", "self", ".", "hasfunction", "(", "'__m128 v; _mm_hadd_ps(v,v)'", ",", "include", "=", "'<pmmintrin.h>'", ",", "extra_postargs", "=", "[", "'-mss...
44
13
def gather_command_line_options(filter_disabled=None): """Get a sorted list of all CommandLineOption subclasses.""" if filter_disabled is None: filter_disabled = not SETTINGS.COMMAND_LINE.SHOW_DISABLED_OPTIONS options = [opt for opt in get_inheritors(CommandLineOption) if not filter_d...
[ "def", "gather_command_line_options", "(", "filter_disabled", "=", "None", ")", ":", "if", "filter_disabled", "is", "None", ":", "filter_disabled", "=", "not", "SETTINGS", ".", "COMMAND_LINE", ".", "SHOW_DISABLED_OPTIONS", "options", "=", "[", "opt", "for", "opt",...
56.428571
15.571429
def _merge_configs(configs): """ Merge one or more ``KubeConfig`` objects. :param list[KubeConfig] configs: The configurations to merge. :return KubeConfig: A single configuration object with the merged configuration. """ result = { u"contexts": [], u"users": [], ...
[ "def", "_merge_configs", "(", "configs", ")", ":", "result", "=", "{", "u\"contexts\"", ":", "[", "]", ",", "u\"users\"", ":", "[", "]", ",", "u\"clusters\"", ":", "[", "]", ",", "u\"current-context\"", ":", "None", ",", "}", "for", "config", "in", "co...
26.354839
18.870968
def _rise_set_trig(t, target, location, prev_next, rise_set): """ Crude time at next rise/set of ``target`` using spherical trig. This method is ~15 times faster than `_calcriseset`, and inherently does *not* take the atmosphere into account. The time returned should not be used in calculations; t...
[ "def", "_rise_set_trig", "(", "t", ",", "target", ",", "location", ",", "prev_next", ",", "rise_set", ")", ":", "dec", "=", "target", ".", "transform_to", "(", "coord", ".", "ICRS", ")", ".", "dec", "with", "warnings", ".", "catch_warnings", "(", ")", ...
34.098039
19.745098
def stage_modified(self): """ Stages modified files only (no untracked) """ LOGGER.info('Staging modified files') self.repo.git.add(u=True)
[ "def", "stage_modified", "(", "self", ")", ":", "LOGGER", ".", "info", "(", "'Staging modified files'", ")", "self", ".", "repo", ".", "git", ".", "add", "(", "u", "=", "True", ")" ]
29
6
def unicode_iter(val): """Provides an iterator over the *code points* of the given Unicode sequence. Notes: Before PEP-393, Python has the potential to support Unicode as UTF-16 or UTF-32. This is reified in the property as ``sys.maxunicode``. As a result, naive iteration of Unicode se...
[ "def", "unicode_iter", "(", "val", ")", ":", "val_iter", "=", "iter", "(", "val", ")", "while", "True", ":", "try", ":", "code_point", "=", "next", "(", "_next_code_point", "(", "val", ",", "val_iter", ",", "to_int", "=", "ord", ")", ")", "except", "...
40.52381
27.857143
def get_token_settings(cls, token, default=None): """ Get the value for a specific token as a dictionary or replace with default :param token: str, token to query the nomenclate for :param default: object, substitution if the token is not found :return: (dict, object, None), token setti...
[ "def", "get_token_settings", "(", "cls", ",", "token", ",", "default", "=", "None", ")", ":", "setting_dict", "=", "{", "}", "for", "key", ",", "value", "in", "iteritems", "(", "cls", ".", "__dict__", ")", ":", "if", "'%s_'", "%", "token", "in", "key...
47.692308
23
def deploy_file(file_path, bucket): """ Uploads a file to an S3 bucket, as a public file. """ # Paths look like: # index.html # css/bootstrap.min.css logger.info("Deploying {0}".format(file_path)) # Upload the actual file to file_path k = Key(bucket) k.key = file_path try: ...
[ "def", "deploy_file", "(", "file_path", ",", "bucket", ")", ":", "# Paths look like:", "# index.html", "# css/bootstrap.min.css", "logger", ".", "info", "(", "\"Deploying {0}\"", ".", "format", "(", "file_path", ")", ")", "# Upload the actual file to file_path", "k", ...
31.666667
19.619048
def save(self, info): """ Handles saving the current model to the last file. """ save_file = self.save_file if not isfile(save_file): self.save_as(info) else: fd = None try: fd = open(save_file, "wb") dot_code =...
[ "def", "save", "(", "self", ",", "info", ")", ":", "save_file", "=", "self", ".", "save_file", "if", "not", "isfile", "(", "save_file", ")", ":", "self", ".", "save_as", "(", "info", ")", "else", ":", "fd", "=", "None", "try", ":", "fd", "=", "op...
27.6875
12.375
def as_point(row): '''Create a Point from a data block row''' return Point(row[COLS.X], row[COLS.Y], row[COLS.Z], row[COLS.R], int(row[COLS.TYPE]))
[ "def", "as_point", "(", "row", ")", ":", "return", "Point", "(", "row", "[", "COLS", ".", "X", "]", ",", "row", "[", "COLS", ".", "Y", "]", ",", "row", "[", "COLS", ".", "Z", "]", ",", "row", "[", "COLS", ".", "R", "]", ",", "int", "(", "...
42.25
13.25
def wrap(text, indent=' '): """Wrap text to terminal width with default indentation""" wrapper = textwrap.TextWrapper( width=int(os.environ.get('COLUMNS', 80)), initial_indent=indent, subsequent_indent=indent ) return '\n'.join(wrapper.wrap(text))
[ "def", "wrap", "(", "text", ",", "indent", "=", "' '", ")", ":", "wrapper", "=", "textwrap", ".", "TextWrapper", "(", "width", "=", "int", "(", "os", ".", "environ", ".", "get", "(", "'COLUMNS'", ",", "80", ")", ")", ",", "initial_indent", "=", ...
35.375
9.625
def strip_system_metadata(etree_obj): """In-place remove elements and attributes that are only valid in v2 types from v1 System Metadata. Args: etree_obj: ElementTree ElementTree holding a v1 SystemMetadata. """ for series_id_el in etree_obj.findall('seriesId'): etree_obj.remove(seri...
[ "def", "strip_system_metadata", "(", "etree_obj", ")", ":", "for", "series_id_el", "in", "etree_obj", ".", "findall", "(", "'seriesId'", ")", ":", "etree_obj", ".", "remove", "(", "series_id_el", ")", "for", "media_type_el", "in", "etree_obj", ".", "findall", ...
39.076923
14.692308
def parse_str(self, s): """ Parse entire file and return a :class:`Catchment` object. :param file_name: File path :type file_name: str :return: Parsed object :rtype: :class:`Catchment` """ root = ET.fromstring(s) return self._parse(root)
[ "def", "parse_str", "(", "self", ",", "s", ")", ":", "root", "=", "ET", ".", "fromstring", "(", "s", ")", "return", "self", ".", "_parse", "(", "root", ")" ]
27.272727
12
def empty(self, duration): '''Empty vector annotations. This returns an annotation with a single observation vector consisting of all-zeroes. Parameters ---------- duration : number >0 Length of the track Returns ------- ann : jams.A...
[ "def", "empty", "(", "self", ",", "duration", ")", ":", "ann", "=", "super", "(", "VectorTransformer", ",", "self", ")", ".", "empty", "(", "duration", ")", "ann", ".", "append", "(", "time", "=", "0", ",", "duration", "=", "duration", ",", "confiden...
26.857143
21.428571
def set_contrast(self, contrast): """ Adjusts the image contrast. Contrast refers to the rate of change of color with color level. At low contrast, color changes gradually over many intensity levels, while at high contrast it can change rapidly within a few levels ...
[ "def", "set_contrast", "(", "self", ",", "contrast", ")", ":", "self", ".", "_contrast", "=", "contrast", "self", ".", "x_spread", "=", "2", "*", "(", "1.0", "-", "contrast", ")", "self", ".", "y_spread", "=", "2.0", "-", "2", "*", "(", "1.0", "-",...
29.954545
21.227273
def request(self, url, json="", data="", username="", password="", headers=None, timout=30): """This is overridden on module initialization. This function will make an HTTP POST to a given url. Either json/da...
[ "def", "request", "(", "self", ",", "url", ",", "json", "=", "\"\"", ",", "data", "=", "\"\"", ",", "username", "=", "\"\"", ",", "password", "=", "\"\"", ",", "headers", "=", "None", ",", "timout", "=", "30", ")", ":", "raise", "NotImplementedError"...
49.571429
21
def delete(self, bundleId): """ Delete a device management extension package It accepts bundleId (string) as parameters In case of failure it throws APIException """ url = "api/v0002/mgmt/custom/bundle/%s" % (bundleId) r = self._apiClient.delete(url) if r...
[ "def", "delete", "(", "self", ",", "bundleId", ")", ":", "url", "=", "\"api/v0002/mgmt/custom/bundle/%s\"", "%", "(", "bundleId", ")", "r", "=", "self", ".", "_apiClient", ".", "delete", "(", "url", ")", "if", "r", ".", "status_code", "==", "204", ":", ...
30.769231
12.615385
def set_exclude_replies(self, exclude): """ Sets 'exclude_replies' parameter used to \ prevent replies from appearing in the returned timeline :param exclude: Boolean triggering the usage of the parameter :raises: TwitterSearchException """ if not isinstance(exclude, bo...
[ "def", "set_exclude_replies", "(", "self", ",", "exclude", ")", ":", "if", "not", "isinstance", "(", "exclude", ",", "bool", ")", ":", "raise", "TwitterSearchException", "(", "1008", ")", "self", ".", "arguments", ".", "update", "(", "{", "'exclude_replies'"...
41.692308
15.461538
def add_phrase(self, phrase: List[int]) -> None: """ Recursively adds a phrase to this trie node. :param phrase: A list of word IDs to add to this trie node. """ if len(phrase) == 1: self.final_ids.add(phrase[0]) else: next_word...
[ "def", "add_phrase", "(", "self", ",", "phrase", ":", "List", "[", "int", "]", ")", "->", "None", ":", "if", "len", "(", "phrase", ")", "==", "1", ":", "self", ".", "final_ids", ".", "add", "(", "phrase", "[", "0", "]", ")", "else", ":", "next_...
34.071429
13.357143
def computeNormals(self): """Compute cell and vertex normals for the actor's mesh. .. warning:: Mesh gets modified, can have a different nr. of vertices. """ poly = self.polydata(False) pnormals = poly.GetPointData().GetNormals() cnormals = poly.GetCellData().GetNormals(...
[ "def", "computeNormals", "(", "self", ")", ":", "poly", "=", "self", ".", "polydata", "(", "False", ")", "pnormals", "=", "poly", ".", "GetPointData", "(", ")", ".", "GetNormals", "(", ")", "cnormals", "=", "poly", ".", "GetCellData", "(", ")", ".", ...
34.368421
12.736842
def walk(self, root): """ Walks the path for a returning the folders and roots for the files found, similar to os.walk. :param path | <str> """ files = [] folders = [] for relpath in self.listdir(root): if self...
[ "def", "walk", "(", "self", ",", "root", ")", ":", "files", "=", "[", "]", "folders", "=", "[", "]", "for", "relpath", "in", "self", ".", "listdir", "(", "root", ")", ":", "if", "self", ".", "isfile", "(", "root", "+", "'/'", "+", "relpath", ")...
31.545455
14.727273
def open (filename, mode='r', **options): """Returns an instance of a :class:`PCapStream` class which contains the ``read()``, ``write()``, and ``close()`` methods. Binary mode is assumed for this module, so the "b" is not required when calling ``open()``. If the optiontal ``rollover`` parameter i...
[ "def", "open", "(", "filename", ",", "mode", "=", "'r'", ",", "*", "*", "options", ")", ":", "mode", "=", "mode", ".", "replace", "(", "'b'", ",", "''", ")", "+", "'b'", "if", "options", ".", "get", "(", "'rollover'", ",", "False", ")", ":", "s...
42.793103
22.413793
def setup_logging(default_path='logging.yaml', default_level=logging.INFO, env_key='LOG_CFG'): """Logging Setup""" path = default_path value = os.getenv(env_key, None) if value: path = value if os.path.exists(path): with open(path, 'rt') as f: try: config ...
[ "def", "setup_logging", "(", "default_path", "=", "'logging.yaml'", ",", "default_level", "=", "logging", ".", "INFO", ",", "env_key", "=", "'LOG_CFG'", ")", ":", "path", "=", "default_path", "value", "=", "os", ".", "getenv", "(", "env_key", ",", "None", ...
40.428571
16.952381
def unstuff(packet): """ Remove byte stuffing from a TSIP packet. :param packet: TSIP packet with byte stuffing. The packet must already have been stripped or `ValueError` will be raised. :type packet: Binary string. :return: Packet without byte stuffing. """ if is_framed(packet):...
[ "def", "unstuff", "(", "packet", ")", ":", "if", "is_framed", "(", "packet", ")", ":", "raise", "ValueError", "(", "'packet contains leading DLE and trailing DLE/ETX'", ")", "else", ":", "return", "packet", ".", "replace", "(", "CHR_DLE", "+", "CHR_DLE", ",", ...
30.066667
20.333333
def start_sctp_server(self, ip, port, name=None, timeout=None, protocol=None, family='ipv4'): """Starts a new STCP server to given `ip` and `port`. `family` can be either ipv4 (default) or ipv6. pysctp (https://github.com/philpraxis/pysctp) need to be installed your system. Server can ...
[ "def", "start_sctp_server", "(", "self", ",", "ip", ",", "port", ",", "name", "=", "None", ",", "timeout", "=", "None", ",", "protocol", "=", "None", ",", "family", "=", "'ipv4'", ")", ":", "self", ".", "_start_server", "(", "SCTPServer", ",", "ip", ...
48.470588
27.176471
def only_newer(copy_func): """ Wrap a copy function (like shutil.copy2) to return the dst if it's newer than the source. """ @functools.wraps(copy_func) def wrapper(src, dst, *args, **kwargs): is_newer_dst = ( dst.exists() and dst.getmtime() >= src.getmtime() ...
[ "def", "only_newer", "(", "copy_func", ")", ":", "@", "functools", ".", "wraps", "(", "copy_func", ")", "def", "wrapper", "(", "src", ",", "dst", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "is_newer_dst", "=", "(", "dst", ".", "exists", "...
28.666667
12
def pruned(name, user=None, env=None): ''' .. versionadded:: 2017.7.0 Cleans up local bower_components directory. Will execute 'bower prune' on the specified directory (param: name) user The user to run Bower with ''' ret = {'name': name, 'result': None, 'comment': '', 'changes':...
[ "def", "pruned", "(", "name", ",", "user", "=", "None", ",", "env", "=", "None", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'result'", ":", "None", ",", "'comment'", ":", "''", ",", "'changes'", ":", "{", "}", "}", "if", "__opts__", ...
28.714286
27.285714
def GET_AUTH(self, courseid): # pylint: disable=arguments-differ """ GET request """ course, __ = self.get_course_and_check_rights(courseid) if self.user_manager.session_username() in course.get_tutors(): raise web.seeother(self.app.get_homepath() + '/admin/{}/tasks'.format(courseid...
[ "def", "GET_AUTH", "(", "self", ",", "courseid", ")", ":", "# pylint: disable=arguments-differ", "course", ",", "__", "=", "self", ".", "get_course_and_check_rights", "(", "courseid", ")", "if", "self", ".", "user_manager", ".", "session_username", "(", ")", "in...
60.857143
30.428571
def do_unmute(self, sender, body, args): """Unmutes the chatroom for a user""" if sender.get('MUTED'): sender['MUTED'] = False self.broadcast('%s has unmuted this chatroom' % (sender['NICK'],)) for msg in sender.get('QUEUED_MESSAGES', []): self.send_me...
[ "def", "do_unmute", "(", "self", ",", "sender", ",", "body", ",", "args", ")", ":", "if", "sender", ".", "get", "(", "'MUTED'", ")", ":", "sender", "[", "'MUTED'", "]", "=", "False", "self", ".", "broadcast", "(", "'%s has unmuted this chatroom'", "%", ...
44.6
12.3
def start(self): """ Start animation thread. """ self.thread = threading.Thread(target=self._animate) self.thread.start() return
[ "def", "start", "(", "self", ")", ":", "self", ".", "thread", "=", "threading", ".", "Thread", "(", "target", "=", "self", ".", "_animate", ")", "self", ".", "thread", ".", "start", "(", ")", "return" ]
24.285714
13.142857
def _create_tmp_file(config): """Write temp file and for use with inline config and SCP.""" tmp_dir = tempfile.gettempdir() rand_fname = py23_compat.text_type(uuid.uuid4()) filename = os.path.join(tmp_dir, rand_fname) with open(filename, 'wt') as fobj: fobj.write(conf...
[ "def", "_create_tmp_file", "(", "config", ")", ":", "tmp_dir", "=", "tempfile", ".", "gettempdir", "(", ")", "rand_fname", "=", "py23_compat", ".", "text_type", "(", "uuid", ".", "uuid4", "(", ")", ")", "filename", "=", "os", ".", "path", ".", "join", ...
42.5
8.625
def download_setuptools(version=DEFAULT_VERSION, download_base=DEFAULT_URL, to_dir=os.curdir, delay=15, downloader_factory=get_best_downloader): """Download setuptools from a specified location and return its filename `version` should be a valid setuptools versio...
[ "def", "download_setuptools", "(", "version", "=", "DEFAULT_VERSION", ",", "download_base", "=", "DEFAULT_URL", ",", "to_dir", "=", "os", ".", "curdir", ",", "delay", "=", "15", ",", "downloader_factory", "=", "get_best_downloader", ")", ":", "# making sure we use...
46.708333
17.666667
def print_results(self, results, min_ratio=None, indent=False, pval=0.05, prt=sys.stdout): """Print GOEA results with some additional statistics calculated.""" results_adj = self.get_adj_records(results, min_ratio, pval) self.print_results_adj(results_adj, indent, prt)
[ "def", "print_results", "(", "self", ",", "results", ",", "min_ratio", "=", "None", ",", "indent", "=", "False", ",", "pval", "=", "0.05", ",", "prt", "=", "sys", ".", "stdout", ")", ":", "results_adj", "=", "self", ".", "get_adj_records", "(", "result...
72.5
23.5
def normalize_text(text, line_len=80, indent=""): """Wrap the text on the given line length.""" return "\n".join( textwrap.wrap( text, width=line_len, initial_indent=indent, subsequent_indent=indent ) )
[ "def", "normalize_text", "(", "text", ",", "line_len", "=", "80", ",", "indent", "=", "\"\"", ")", ":", "return", "\"\\n\"", ".", "join", "(", "textwrap", ".", "wrap", "(", "text", ",", "width", "=", "line_len", ",", "initial_indent", "=", "indent", ",...
33.714286
21.857143
def snapshot_report(result, config=None, html=True): """ Generate a snapshot report from a result set and configuration. Parameters ---------- result : memote.MemoteResult Nested dictionary structure as returned from the test suite. config : dict, optional The final test report ...
[ "def", "snapshot_report", "(", "result", ",", "config", "=", "None", ",", "html", "=", "True", ")", ":", "if", "config", "is", "None", ":", "config", "=", "ReportConfiguration", ".", "load", "(", ")", "report", "=", "SnapshotReport", "(", "result", "=", ...
31.666667
19.095238
def cmd_led(self, args): '''send LED pattern as override''' if len(args) < 3: print("Usage: led RED GREEN BLUE <RATE>") return pattern = [0] * 24 pattern[0] = int(args[0]) pattern[1] = int(args[1]) pattern[2] = int(args[2]) if len(...
[ "def", "cmd_led", "(", "self", ",", "args", ")", ":", "if", "len", "(", "args", ")", "<", "3", ":", "print", "(", "\"Usage: led RED GREEN BLUE <RATE>\"", ")", "return", "pattern", "=", "[", "0", "]", "*", "24", "pattern", "[", "0", "]", "=", "int", ...
32.894737
17.315789
def _uri(self, url): """Returns request absolute URI""" if url and not url.startswith('/'): # Then this must be a proxy request. return url uri = "{0}://{1}{2}{3}".format( self._protocol, self.real_connection.host, self._port_postfix(),...
[ "def", "_uri", "(", "self", ",", "url", ")", ":", "if", "url", "and", "not", "url", ".", "startswith", "(", "'/'", ")", ":", "# Then this must be a proxy request.", "return", "url", "uri", "=", "\"{0}://{1}{2}{3}\"", ".", "format", "(", "self", ".", "_prot...
29.583333
12.416667
def fit(self, train_set, test_set): """Fit the model to the given data. :param train_set: training data :param test_set: test data """ with tf.Graph().as_default(), tf.Session() as self.tf_session: self.build_model() tf.global_variables_initializer().run(...
[ "def", "fit", "(", "self", ",", "train_set", ",", "test_set", ")", ":", "with", "tf", ".", "Graph", "(", ")", ".", "as_default", "(", ")", ",", "tf", ".", "Session", "(", ")", "as", "self", ".", "tf_session", ":", "self", ".", "build_model", "(", ...
40.5
18.590909
def _remove_person_from_group(person, group): """ Call datastores after removing a person from a group. """ from karaage.datastores import remove_accounts_from_group from karaage.datastores import remove_accounts_from_project from karaage.datastores import remove_accounts_from_institute a_list = pe...
[ "def", "_remove_person_from_group", "(", "person", ",", "group", ")", ":", "from", "karaage", ".", "datastores", "import", "remove_accounts_from_group", "from", "karaage", ".", "datastores", "import", "remove_accounts_from_project", "from", "karaage", ".", "datastores",...
47.916667
14
def _create_segment(self, obj, segment, next_segment): """Create ``obj[segment]`` if missing. The default value for a missing segment is based on the *next* segment, unless a ``default`` is explicitly passed. If the next segment is an int, the default will be a list with the in...
[ "def", "_create_segment", "(", "self", ",", "obj", ",", "segment", ",", "next_segment", ")", ":", "if", "isinstance", "(", "next_segment", ",", "int", ")", ":", "value", "=", "[", "PLACEHOLDER", "]", "*", "(", "next_segment", "+", "1", ")", "else", ":"...
37.28
14.76
def prune(self, wordlist): """ Prune the current reach instance by removing items. Parameters ---------- wordlist : list of str A list of words to keep. Note that this wordlist need not include all words in the Reach instance. Any words which are in the ...
[ "def", "prune", "(", "self", ",", "wordlist", ")", ":", "# Remove duplicates", "wordlist", "=", "set", "(", "wordlist", ")", ".", "intersection", "(", "set", "(", "self", ".", "items", ".", "keys", "(", ")", ")", ")", "indices", "=", "[", "self", "."...
45.84
21.2
def filter_connection_params(queue_params): """ Filters the queue params to keep only the connection related params. """ CONNECTION_PARAMS = ('URL', 'DB', 'USE_REDIS_CACHE', 'UNIX_SOCKET_PATH', 'HOST', 'PORT', 'PASSWORD', 'SENTINELS', 'MASTER_NAME', 'SOC...
[ "def", "filter_connection_params", "(", "queue_params", ")", ":", "CONNECTION_PARAMS", "=", "(", "'URL'", ",", "'DB'", ",", "'USE_REDIS_CACHE'", ",", "'UNIX_SOCKET_PATH'", ",", "'HOST'", ",", "'PORT'", ",", "'PASSWORD'", ",", "'SENTINELS'", ",", "'MASTER_NAME'", "...
49
21.166667
def print_title(title): """Helper function to print titles to the console more nicely""" sprint('\n') sprint('=={}=='.format('=' * len(title))) sprint('= {} ='.format(title)) sprint('=={}=='.format('=' * len(title)))
[ "def", "print_title", "(", "title", ")", ":", "sprint", "(", "'\\n'", ")", "sprint", "(", "'=={}=='", ".", "format", "(", "'='", "*", "len", "(", "title", ")", ")", ")", "sprint", "(", "'= {} ='", ".", "format", "(", "title", ")", ")", "sprint", "(...
38.5
9.5
def rename(self, node): """ Translate a rename node into latex qtree node. :param node: a treebrd node :return: a qtree subtree rooted at the node """ child = self.translate(node.child) attributes = '' if node.attributes: attributes = '({})'.fo...
[ "def", "rename", "(", "self", ",", "node", ")", ":", "child", "=", "self", ".", "translate", "(", "node", ".", "child", ")", "attributes", "=", "''", "if", "node", ".", "attributes", ":", "attributes", "=", "'({})'", ".", "format", "(", "', '", ".", ...
39.357143
12.071429
def endian_swap_words(source): """ Endian-swap each word in 'source' bitstring """ assert len(source) % 4 == 0 words = "I" * (len(source) // 4) return struct.pack("<" + words, *struct.unpack(">" + words, source))
[ "def", "endian_swap_words", "(", "source", ")", ":", "assert", "len", "(", "source", ")", "%", "4", "==", "0", "words", "=", "\"I\"", "*", "(", "len", "(", "source", ")", "//", "4", ")", "return", "struct", ".", "pack", "(", "\"<\"", "+", "words", ...
44.8
11
def _parse_failures(gallery_conf): """Split the failures.""" failing_examples = set(gallery_conf['failing_examples'].keys()) expected_failing_examples = set( os.path.normpath(os.path.join(gallery_conf['src_dir'], path)) for path in gallery_conf['expected_failing_examples']) failing_as_ex...
[ "def", "_parse_failures", "(", "gallery_conf", ")", ":", "failing_examples", "=", "set", "(", "gallery_conf", "[", "'failing_examples'", "]", ".", "keys", "(", ")", ")", "expected_failing_examples", "=", "set", "(", "os", ".", "path", ".", "normpath", "(", "...
48.705882
15.235294
def _parse_supybot_msg(self, line): """Parse message section""" patterns = [(self.SUPYBOT_COMMENT_REGEX, self.TCOMMENT), (self.SUPYBOT_COMMENT_ACTION_REGEX, self.TCOMMENT), (self.SUPYBOT_SERVER_REGEX, self.TSERVER), (self.SUPYBOT_BOT_REGEX, se...
[ "def", "_parse_supybot_msg", "(", "self", ",", "line", ")", ":", "patterns", "=", "[", "(", "self", ".", "SUPYBOT_COMMENT_REGEX", ",", "self", ".", "TCOMMENT", ")", ",", "(", "self", ".", "SUPYBOT_COMMENT_ACTION_REGEX", ",", "self", ".", "TCOMMENT", ")", "...
37
20.6875
def apply_rule_changes(self): """ Makes the security group rules match what is defined in the Bang config file. """ # TODO: add error handling for rule in self.delete_these_rules: self.consul.delete_secgroup_rule(rule) log.info("Revoked: %s" % rul...
[ "def", "apply_rule_changes", "(", "self", ")", ":", "# TODO: add error handling", "for", "rule", "in", "self", ".", "delete_these_rules", ":", "self", ".", "consul", ".", "delete_secgroup_rule", "(", "rule", ")", "log", ".", "info", "(", "\"Revoked: %s\"", "%", ...
35.5
10.785714
def get_cache_mode(service, pool_name): """ Find the current caching mode of the pool_name given. :param service: six.string_types. The Ceph user name to run the command under :param pool_name: six.string_types :return: int or None """ validator(value=service, valid_type=six.string_types) ...
[ "def", "get_cache_mode", "(", "service", ",", "pool_name", ")", ":", "validator", "(", "value", "=", "service", ",", "valid_type", "=", "six", ".", "string_types", ")", "validator", "(", "value", "=", "pool_name", ",", "valid_type", "=", "six", ".", "strin...
35.333333
13.428571
def _get_remote_ontology(onto_url, time_difference=None): """Check if the online ontology is more recent than the local ontology. If yes, try to download and store it in Invenio's cache directory. Return a boolean describing the success of the operation. :return: path to the downloaded ontology. ...
[ "def", "_get_remote_ontology", "(", "onto_url", ",", "time_difference", "=", "None", ")", ":", "if", "onto_url", "is", "None", ":", "return", "False", "dl_dir", "=", "os", ".", "path", ".", "join", "(", "current_app", ".", "config", "[", "\"CLASSIFIER_WORKDI...
35.533333
23.355556
def getCheckedOption(self): """Returns what destination is selected""" if self.__silentRButton.isChecked(): return GCPluginConfigDialog.SILENT if self.__statusbarRButton.isChecked(): return GCPluginConfigDialog.STATUS_BAR return GCPluginConfigDialog.LOG
[ "def", "getCheckedOption", "(", "self", ")", ":", "if", "self", ".", "__silentRButton", ".", "isChecked", "(", ")", ":", "return", "GCPluginConfigDialog", ".", "SILENT", "if", "self", ".", "__statusbarRButton", ".", "isChecked", "(", ")", ":", "return", "GCP...
43.285714
5.857143
def check_next_match(self, match, new_relations, subject_graph, one_match): """Check if the (onset for a) match can be a valid (part of a) ring""" # avoid duplicate rings (order of traversal) if len(match) == 3: if match.forward[1] < match.forward[2]: #print "RingPatt...
[ "def", "check_next_match", "(", "self", ",", "match", ",", "new_relations", ",", "subject_graph", ",", "one_match", ")", ":", "# avoid duplicate rings (order of traversal)", "if", "len", "(", "match", ")", "==", "3", ":", "if", "match", ".", "forward", "[", "1...
52.045455
18.590909
def cmd_fw_manifest_purge(self): '''remove all downloaded manifests''' for filepath in self.find_manifests(): os.unlink(filepath) self.manifests_parse()
[ "def", "cmd_fw_manifest_purge", "(", "self", ")", ":", "for", "filepath", "in", "self", ".", "find_manifests", "(", ")", ":", "os", ".", "unlink", "(", "filepath", ")", "self", ".", "manifests_parse", "(", ")" ]
36.8
7.6
def lvremove(lvname, vgname): ''' Remove a given existing logical volume from a named existing volume group CLI Example: .. code-block:: bash salt '*' lvm.lvremove lvname vgname force=True ''' cmd = ['lvremove', '-f', '{0}/{1}'.format(vgname, lvname)] out = __salt__['cmd.run'](cmd...
[ "def", "lvremove", "(", "lvname", ",", "vgname", ")", ":", "cmd", "=", "[", "'lvremove'", ",", "'-f'", ",", "'{0}/{1}'", ".", "format", "(", "vgname", ",", "lvname", ")", "]", "out", "=", "__salt__", "[", "'cmd.run'", "]", "(", "cmd", ",", "python_sh...
27.076923
26.307692
def guess_mode(self, data): """ Guess what type of image the np.array is representing """ # TODO: do we want to support dimensions being at the beginning of the array? if data.ndim == 2: return "L" elif data.shape[-1] == 3: return "RGB" eli...
[ "def", "guess_mode", "(", "self", ",", "data", ")", ":", "# TODO: do we want to support dimensions being at the beginning of the array?", "if", "data", ".", "ndim", "==", "2", ":", "return", "\"L\"", "elif", "data", ".", "shape", "[", "-", "1", "]", "==", "3", ...
34.285714
16.714286
def accessibles(self, roles=None): """ Returns the list of *slugs* for which the accounts are accessibles by ``request.user`` filtered by ``roles`` if present. """ return [org['slug'] for org in self.get_accessibles(self.request, roles=roles)]
[ "def", "accessibles", "(", "self", ",", "roles", "=", "None", ")", ":", "return", "[", "org", "[", "'slug'", "]", "for", "org", "in", "self", ".", "get_accessibles", "(", "self", ".", "request", ",", "roles", "=", "roles", ")", "]" ]
41.857143
15.571429
def _get_compiled_ext(): """Official way to get the extension of compiled files (.pyc or .pyo)""" for ext, mode, typ in imp.get_suffixes(): if typ == imp.PY_COMPILED: return ext
[ "def", "_get_compiled_ext", "(", ")", ":", "for", "ext", ",", "mode", ",", "typ", "in", "imp", ".", "get_suffixes", "(", ")", ":", "if", "typ", "==", "imp", ".", "PY_COMPILED", ":", "return", "ext" ]
40.2
9
def is_time_variable(varname, var): """ Identifies if a variable is represents time """ satisfied = varname.lower() == 'time' satisfied |= getattr(var, 'standard_name', '') == 'time' satisfied |= getattr(var, 'axis', '') == 'T' satisfied |= units_convertible('seconds since 1900-01-01', getat...
[ "def", "is_time_variable", "(", "varname", ",", "var", ")", ":", "satisfied", "=", "varname", ".", "lower", "(", ")", "==", "'time'", "satisfied", "|=", "getattr", "(", "var", ",", "'standard_name'", ",", "''", ")", "==", "'time'", "satisfied", "|=", "ge...
39.333333
12.222222
async def send_cred_def(self, s_id: str, revocation: bool = True, rr_size: int = None) -> str: """ Create a credential definition as Issuer, store it in its wallet, and send it to the ledger. Raise CorruptWallet for wallet not pertaining to current ledger, BadLedgerTxn on failure to sen...
[ "async", "def", "send_cred_def", "(", "self", ",", "s_id", ":", "str", ",", "revocation", ":", "bool", "=", "True", ",", "rr_size", ":", "int", "=", "None", ")", "->", "str", ":", "LOGGER", ".", "debug", "(", "'Issuer.send_cred_def >>> s_id: %s, revocation: ...
51.546512
27.662791
def get_files_by_name(self, name, parent=None): """ Gets all the files references that have the given name, under the specified parent PBXGroup object or PBXGroup id. :param name: name of the file to be retrieved :param parent: PBXGroup that should be used to narrow the search or...
[ "def", "get_files_by_name", "(", "self", ",", "name", ",", "parent", "=", "None", ")", ":", "if", "parent", "is", "not", "None", ":", "parent", "=", "self", ".", "_get_parent_group", "(", "parent", ")", "files", "=", "[", "]", "for", "file_ref", "in", ...
46.647059
28.176471
def login(request): """View to check the persona assertion and remember the user""" email = verify_login(request) request.response.headers.extend(remember(request, email)) return {'redirect': request.POST.get('came_from', '/'), 'success': True}
[ "def", "login", "(", "request", ")", ":", "email", "=", "verify_login", "(", "request", ")", "request", ".", "response", ".", "headers", ".", "extend", "(", "remember", "(", "request", ",", "email", ")", ")", "return", "{", "'redirect'", ":", "request", ...
51.2
17
def ensure_views(): ''' This function makes sure that all the views that should exist in the design document do exist. ''' # Get the options so we have the URL and DB.. options = _get_options(ret=None) # Make a request to check if the design document exists. _response = _request("GET",...
[ "def", "ensure_views", "(", ")", ":", "# Get the options so we have the URL and DB..", "options", "=", "_get_options", "(", "ret", "=", "None", ")", "# Make a request to check if the design document exists.", "_response", "=", "_request", "(", "\"GET\"", ",", "options", "...
34
22.962963
def _transformBy(self, matrix, **kwargs): """ Subclasses may override this method. """ t = transform.Transform(*matrix) transformation = t.transform(self.transformation) self.transformation = tuple(transformation)
[ "def", "_transformBy", "(", "self", ",", "matrix", ",", "*", "*", "kwargs", ")", ":", "t", "=", "transform", ".", "Transform", "(", "*", "matrix", ")", "transformation", "=", "t", ".", "transform", "(", "self", ".", "transformation", ")", "self", ".", ...
36.428571
4.714286
def direct_age_standardization(e, b, s, n, alpha=0.05): """A utility function to compute rate through direct age standardization Parameters ---------- e : array (n*h, 1), event variable measured for each age group across n spatial units b : array ...
[ "def", "direct_age_standardization", "(", "e", ",", "b", ",", "s", ",", "n", ",", "alpha", "=", "0.05", ")", ":", "age_weight", "=", "(", "1.0", "/", "b", ")", "*", "(", "s", "*", "1.0", "/", "sum_by_n", "(", "s", ",", "1.0", ",", "n", ")", "...
37.795181
27.012048
def post_generate_identifier(request): """MNStorage.generateIdentifier(session, scheme[, fragment]) → Identifier.""" d1_gmn.app.views.assert_db.post_has_mime_parts(request, (('field', 'scheme'),)) if request.POST['scheme'] != 'UUID': raise d1_common.types.exceptions.InvalidRequest( 0, 'O...
[ "def", "post_generate_identifier", "(", "request", ")", ":", "d1_gmn", ".", "app", ".", "views", ".", "assert_db", ".", "post_has_mime_parts", "(", "request", ",", "(", "(", "'field'", ",", "'scheme'", ")", ",", ")", ")", "if", "request", ".", "POST", "[...
50.083333
19.333333
def check_params(num_rows, num_cols, padding): """Validation and typcasting""" num_rows = check_int(num_rows, 'num_rows', min_value=1) num_cols = check_int(num_cols, 'num_cols', min_value=1) padding = check_int(padding, 'padding', min_value=0) return num_rows, num_cols, padding
[ "def", "check_params", "(", "num_rows", ",", "num_cols", ",", "padding", ")", ":", "num_rows", "=", "check_int", "(", "num_rows", ",", "'num_rows'", ",", "min_value", "=", "1", ")", "num_cols", "=", "check_int", "(", "num_cols", ",", "'num_cols'", ",", "mi...
36.625
17.75
def import_process_element(process_elements_dict, process_element): """ Adds attributes of BPMN process element to appropriate field process_attributes. Diagram inner representation contains following process attributes: - id - assumed to be required in XML file, even thought BPMN 2.0 s...
[ "def", "import_process_element", "(", "process_elements_dict", ",", "process_element", ")", ":", "process_id", "=", "process_element", ".", "getAttribute", "(", "consts", ".", "Consts", ".", "id", ")", "process_element_attributes", "=", "{", "consts", ".", "Consts",...
74.37931
41.896552
def drag_by_coordinates(self,sx, sy, ex, ey, steps=10): """ Drag from (sx, sy) to (ex, ey) with steps See `Swipe By Coordinates` also. """ self.device.drag(sx, sy, ex, ey, steps)
[ "def", "drag_by_coordinates", "(", "self", ",", "sx", ",", "sy", ",", "ex", ",", "ey", ",", "steps", "=", "10", ")", ":", "self", ".", "device", ".", "drag", "(", "sx", ",", "sy", ",", "ex", ",", "ey", ",", "steps", ")" ]
30.428571
10.142857
def get_search_cache_key(prefix, *args): """ Generate suitable key to cache twitter tag context """ key = '%s_%s' % (prefix, '_'.join([str(arg) for arg in args if arg])) not_allowed = re.compile('[^%s]' % ''.join([chr(i) for i in range(33, 128)])) key = not_allowed.sub('', key) return key
[ "def", "get_search_cache_key", "(", "prefix", ",", "*", "args", ")", ":", "key", "=", "'%s_%s'", "%", "(", "prefix", ",", "'_'", ".", "join", "(", "[", "str", "(", "arg", ")", "for", "arg", "in", "args", "if", "arg", "]", ")", ")", "not_allowed", ...
43.857143
15.142857
def extract_features(self, dataset, missing_value_action='auto'): """ For each example in the dataset, extract the leaf indices of each tree as features. For multiclass classification, each leaf index contains #num_class numbers. The returned feature vectors can be used...
[ "def", "extract_features", "(", "self", ",", "dataset", ",", "missing_value_action", "=", "'auto'", ")", ":", "_raise_error_if_not_sframe", "(", "dataset", ",", "\"dataset\"", ")", "if", "missing_value_action", "==", "'auto'", ":", "missing_value_action", "=", "sele...
41
25.035714
def _state_changed(self, previous_state, new_state): """Callback called whenever the underlying Receiver undergoes a change of state. This function wraps the states as Enums to prepare for calling the public callback. :param previous_state: The previous Receiver state. :type pre...
[ "def", "_state_changed", "(", "self", ",", "previous_state", ",", "new_state", ")", ":", "try", ":", "try", ":", "_previous_state", "=", "constants", ".", "MessageReceiverState", "(", "previous_state", ")", "except", "ValueError", ":", "_previous_state", "=", "p...
50.066667
22.5
def calc_stream_lb(self, vo=None,ro=None, R0=None,Zsun=None,vsun=None): """ NAME: calc_stream_lb PURPOSE: convert the stream track to observational coordinates and store INPUT: Coordinate transformation i...
[ "def", "calc_stream_lb", "(", "self", ",", "vo", "=", "None", ",", "ro", "=", "None", ",", "R0", "=", "None", ",", "Zsun", "=", "None", ",", "vsun", "=", "None", ")", ":", "if", "vo", "is", "None", ":", "vo", "=", "self", ".", "_vo", "if", "r...
39.693069
20.861386
def _get_cron_info(): ''' Returns the proper group owner and path to the cron directory ''' owner = 'root' if __grains__['os'] == 'FreeBSD': group = 'wheel' crontab_dir = '/var/cron/tabs' elif __grains__['os'] == 'OpenBSD': group = 'crontab' crontab_dir = '/var/cr...
[ "def", "_get_cron_info", "(", ")", ":", "owner", "=", "'root'", "if", "__grains__", "[", "'os'", "]", "==", "'FreeBSD'", ":", "group", "=", "'wheel'", "crontab_dir", "=", "'/var/cron/tabs'", "elif", "__grains__", "[", "'os'", "]", "==", "'OpenBSD'", ":", "...
30.571429
13.333333
def abbreviate(s, maxlength=25): """Color-aware abbreviator""" assert maxlength >= 4 skip = False abbrv = None i = 0 for j, c in enumerate(s): if c == '\033': skip = True elif skip: if c == 'm': skip = False else: i += 1...
[ "def", "abbreviate", "(", "s", ",", "maxlength", "=", "25", ")", ":", "assert", "maxlength", ">=", "4", "skip", "=", "False", "abbrv", "=", "None", "i", "=", "0", "for", "j", ",", "c", "in", "enumerate", "(", "s", ")", ":", "if", "c", "==", "'\...
20.333333
19.375
def lemmas(self, lemma, pos = None): ''' Looks up lemmas in the GermaNet database. Arguments: - `lemma`: - `pos`: ''' if pos is not None: if pos not in SHORT_POS_TO_LONG: return None pos = SHORT_POS_TO_LONG[pos] ...
[ "def", "lemmas", "(", "self", ",", "lemma", ",", "pos", "=", "None", ")", ":", "if", "pos", "is", "not", "None", ":", "if", "pos", "not", "in", "SHORT_POS_TO_LONG", ":", "return", "None", "pos", "=", "SHORT_POS_TO_LONG", "[", "pos", "]", "lemma_dicts",...
36.352941
22.588235
def addHandler(name, basepath=None, baseurl=None, allowDownscale=False): """Add an event handler with given name.""" if basepath is None: basepath = '.' _handlers.append(_handler_classes[name](basepath, baseurl, allowDownscale))
[ "def", "addHandler", "(", "name", ",", "basepath", "=", "None", ",", "baseurl", "=", "None", ",", "allowDownscale", "=", "False", ")", ":", "if", "basepath", "is", "None", ":", "basepath", "=", "'.'", "_handlers", ".", "append", "(", "_handler_classes", ...
48.8
21