text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def on_step_end(self, step, logs={}): """ Save weights at interval steps during training """ self.total_steps += 1 if self.total_steps % self.interval != 0: # Nothing to do. return filepath = self.filepath.format(step=self.total_steps, **logs) if self.ver...
[ "def", "on_step_end", "(", "self", ",", "step", ",", "logs", "=", "{", "}", ")", ":", "self", ".", "total_steps", "+=", "1", "if", "self", ".", "total_steps", "%", "self", ".", "interval", "!=", "0", ":", "# Nothing to do.", "return", "filepath", "=", ...
41.909091
18.090909
def _package_to_staging(staging_package_url): """Repackage this package from local installed location and copy it to GCS. Args: staging_package_url: GCS path. """ import google.datalab.ml as ml # Find the package root. __file__ is under [package_root]/mltoolbox/_structured_data/this_file ...
[ "def", "_package_to_staging", "(", "staging_package_url", ")", ":", "import", "google", ".", "datalab", ".", "ml", "as", "ml", "# Find the package root. __file__ is under [package_root]/mltoolbox/_structured_data/this_file", "package_root", "=", "os", ".", "path", ".", "abs...
38.315789
22.315789
def remove_highdepth_regions(in_file, items): """Remove high depth regions from a BED file for analyzing a set of calls. Tries to avoid spurious errors and slow run times in collapsed repeat regions. Also adds ENCODE blacklist regions which capture additional collapsed repeats around centromeres. ...
[ "def", "remove_highdepth_regions", "(", "in_file", ",", "items", ")", ":", "encode_bed", "=", "tz", ".", "get_in", "(", "[", "\"genome_resources\"", ",", "\"variation\"", ",", "\"encode_blacklist\"", "]", ",", "items", "[", "0", "]", ")", "if", "encode_bed", ...
43.076923
25.153846
def dfs_grid_recursive(grid, i, j, mark='X', free='.'): """DFS on a grid, mark connected component, iterative version :param grid: matrix, 4-neighborhood :param i,j: cell in this matrix, start of DFS exploration :param free: symbol for walkable cells :param mark: symbol to overwrite visited vertice...
[ "def", "dfs_grid_recursive", "(", "grid", ",", "i", ",", "j", ",", "mark", "=", "'X'", ",", "free", "=", "'.'", ")", ":", "height", "=", "len", "(", "grid", ")", "width", "=", "len", "(", "grid", "[", "0", "]", ")", "grid", "[", "i", "]", "["...
37.882353
9.882353
def get_units(username): """ Return all units of user 'username' """ connection, ldap_base = _get_LDAP_connection() # Search the user dn connection.search( search_base=ldap_base, search_filter='(uid={}@*)'.format(username), ) # For each user dn give me the unit dn_l...
[ "def", "get_units", "(", "username", ")", ":", "connection", ",", "ldap_base", "=", "_get_LDAP_connection", "(", ")", "# Search the user dn", "connection", ".", "search", "(", "search_base", "=", "ldap_base", ",", "search_filter", "=", "'(uid={}@*)'", ".", "format...
32.173913
23.826087
def _set_dst_vtep_ip(self, v, load=False): """ Setter method for dst_vtep_ip, mapped from YANG variable /overlay/access_list/type/vxlan/standard/seq/dst_vtep_ip (inet:ipv4-address) If this variable is read-only (config: false) in the source YANG file, then _set_dst_vtep_ip is considered as a private ...
[ "def", "_set_dst_vtep_ip", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", "v", ",", "ba...
105.863636
50.727273
def _get_stmt_by_group(self, stmt_type, stmts_this_type, eh): """Group Statements of `stmt_type` by their hierarchical relations.""" # Dict of stmt group key tuples, indexed by their first Agent stmt_by_first = collections.defaultdict(lambda: []) # Dict of stmt group key tuples, indexed ...
[ "def", "_get_stmt_by_group", "(", "self", ",", "stmt_type", ",", "stmts_this_type", ",", "eh", ")", ":", "# Dict of stmt group key tuples, indexed by their first Agent", "stmt_by_first", "=", "collections", ".", "defaultdict", "(", "lambda", ":", "[", "]", ")", "# Dic...
53.261682
18.028037
def request_file_upload(owner, repo, filepath, md5_checksum=None): """Request a new package file upload (for creating packages).""" client = get_files_api() md5_checksum = md5_checksum or calculate_file_md5(filepath) with catch_raise_api_exception(): data, _, headers = client.files_create_with_...
[ "def", "request_file_upload", "(", "owner", ",", "repo", ",", "filepath", ",", "md5_checksum", "=", "None", ")", ":", "client", "=", "get_files_api", "(", ")", "md5_checksum", "=", "md5_checksum", "or", "calculate_file_md5", "(", "filepath", ")", "with", "catc...
41.1875
20.5625
def noisepickle(d, data, u, v, w, chunk=200): """ Calculates noise properties and saves values to pickle. chunk defines window for measurement. at least one measurement always made. """ if d['savenoise']: noisefile = getnoisefile(d) if os.path.exists(noisefile): logger.warn...
[ "def", "noisepickle", "(", "d", ",", "data", ",", "u", ",", "v", ",", "w", ",", "chunk", "=", "200", ")", ":", "if", "d", "[", "'savenoise'", "]", ":", "noisefile", "=", "getnoisefile", "(", "d", ")", "if", "os", ".", "path", ".", "exists", "("...
45.518519
23.888889
def find_templates(): """ Load python modules from templates directory and get templates list :return: list of tuples (pairs): [(compiled regex, lambda regex_match: return message_data)] """ templates = [] templates_directory = (inspect.getsourcefile(lambda: 0).rstrip('__init__.py'...
[ "def", "find_templates", "(", ")", ":", "templates", "=", "[", "]", "templates_directory", "=", "(", "inspect", ".", "getsourcefile", "(", "lambda", ":", "0", ")", ".", "rstrip", "(", "'__init__.py'", ")", "+", "'templates'", ")", "template_files", "=", "o...
42.064516
18.322581
def check_void(result, func, cargs): "Error checking for void* returns" if not bool(result): s = rt.Error_GetLastErrorMsg().decode() msg = 'Error in "%s": %s' % (func.__name__, s) rt.Error_Reset() raise RTreeError(msg) return result
[ "def", "check_void", "(", "result", ",", "func", ",", "cargs", ")", ":", "if", "not", "bool", "(", "result", ")", ":", "s", "=", "rt", ".", "Error_GetLastErrorMsg", "(", ")", ".", "decode", "(", ")", "msg", "=", "'Error in \"%s\": %s'", "%", "(", "fu...
33.625
11.625
def run(self, proc: Callable[[Optional[str], Optional[str], argparse.Namespace], Optional[bool]], file_filter: Optional[Callable[[str], bool]]=None, file_filter_2: Optional[Callable[[Optional[str], str, argparse.Namespace], bool]]=None) \ -> Tuple[int, int]: """ R...
[ "def", "run", "(", "self", ",", "proc", ":", "Callable", "[", "[", "Optional", "[", "str", "]", ",", "Optional", "[", "str", "]", ",", "argparse", ".", "Namespace", "]", ",", "Optional", "[", "bool", "]", "]", ",", "file_filter", ":", "Optional", "...
50.87234
25
def iter_items(self, depth: int = 1): ''' get items from directory. ''' if depth is not None and not isinstance(depth, int): raise TypeError def itor(root, d): if d is not None: d -= 1 if d < 0: return ...
[ "def", "iter_items", "(", "self", ",", "depth", ":", "int", "=", "1", ")", ":", "if", "depth", "is", "not", "None", "and", "not", "isinstance", "(", "depth", ",", "int", ")", ":", "raise", "TypeError", "def", "itor", "(", "root", ",", "d", ")", "...
33.611111
12.166667
def log_deprecated(name="", text="", eos=""): """ Log deprecation warning. Args: name (str): name of the deprecated item. text (str, optional): information about the deprecation. eos (str, optional): end of service date such as "YYYY-MM-DD". """ assert name or text if eo...
[ "def", "log_deprecated", "(", "name", "=", "\"\"", ",", "text", "=", "\"\"", ",", "eos", "=", "\"\"", ")", ":", "assert", "name", "or", "text", "if", "eos", ":", "eos", "=", "\"after \"", "+", "datetime", "(", "*", "map", "(", "int", ",", "eos", ...
32.181818
20.818182
def delete(self): """ Destructor. """ if self.minisat: pysolvers.minisatgh_del(self.minisat) self.minisat = None
[ "def", "delete", "(", "self", ")", ":", "if", "self", ".", "minisat", ":", "pysolvers", ".", "minisatgh_del", "(", "self", ".", "minisat", ")", "self", ".", "minisat", "=", "None" ]
20.75
14.25
def send_document(chat_id, document, reply_to_message_id=None, reply_markup=None, **kwargs): """ Use this method to send general files. :param chat_id: Unique identifier for the message recipient — User or GroupChat id :param document: File to send. You can either pa...
[ "def", "send_document", "(", "chat_id", ",", "document", ",", "reply_to_message_id", "=", "None", ",", "reply_markup", "=", "None", ",", "*", "*", "kwargs", ")", ":", "files", "=", "None", "if", "isinstance", "(", "document", ",", "InputFile", ")", ":", ...
38.068182
26.25
def create(cls, function, *args, **kwargs): """ Capture the given callable and arguments as an instance of this class. :param callable function: The deferred action to take in the form of a function :param tuple args: Non-keyword arguments to the function :param dict kwargs: Key...
[ "def", "create", "(", "cls", ",", "function", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# The general principle is to deserialize as late as possible, i.e. when the function is", "# to be invoked, as that will avoid redundantly deserializing deferred functions for", "# ...
59.4375
30.5625
def get_trace_id(request): """Gets the trace id based on a request. If not present with the request, create a custom (depending on config: `zipkin.trace_id_generator`) or a completely random trace id. :param: current active pyramid request :returns: a 64-bit hex string """ if 'X-B3-TraceId'...
[ "def", "get_trace_id", "(", "request", ")", ":", "if", "'X-B3-TraceId'", "in", "request", ".", "headers", ":", "trace_id", "=", "_convert_signed_hex", "(", "request", ".", "headers", "[", "'X-B3-TraceId'", "]", ")", "# Tolerates 128 bit X-B3-TraceId by reading the rig...
42.35
19.05
def _visit_body(self, node): """ Traverse the body of the node manually. If the first node is an expression which contains a string or bytes it marks that as a docstring. """ if (node.body and isinstance(node.body[0], ast.Expr) and self.is_base_string(nod...
[ "def", "_visit_body", "(", "self", ",", "node", ")", ":", "if", "(", "node", ".", "body", "and", "isinstance", "(", "node", ".", "body", "[", "0", "]", ",", "ast", ".", "Expr", ")", "and", "self", ".", "is_base_string", "(", "node", ".", "body", ...
34.857143
15
def get_transaction(self, clear=False): """ Get the transaction registered for the current thread. :return: :rtype: Transaction """ transaction = getattr(self.thread_local, "transaction", None) if clear: self.thread_local.transaction = None re...
[ "def", "get_transaction", "(", "self", ",", "clear", "=", "False", ")", ":", "transaction", "=", "getattr", "(", "self", ".", "thread_local", ",", "\"transaction\"", ",", "None", ")", "if", "clear", ":", "self", ".", "thread_local", ".", "transaction", "="...
29.636364
15.818182
def get(self, endpoint): """ Todo """ r = self.http.request('GET', self._api_base.format(endpoint), headers={'Authorization': 'Bot '+self.token}) if r.status == 200: return json.loads(r.data.decode('utf-8')) else: return {}
[ "def", "get", "(", "self", ",", "endpoint", ")", ":", "r", "=", "self", ".", "http", ".", "request", "(", "'GET'", ",", "self", ".", "_api_base", ".", "format", "(", "endpoint", ")", ",", "headers", "=", "{", "'Authorization'", ":", "'Bot '", "+", ...
32.777778
17
async def disconnect(self): """Disconnect this interface.""" self._data = await self._handler.disconnect( system_id=self.node.system_id, id=self.id)
[ "async", "def", "disconnect", "(", "self", ")", ":", "self", ".", "_data", "=", "await", "self", ".", "_handler", ".", "disconnect", "(", "system_id", "=", "self", ".", "node", ".", "system_id", ",", "id", "=", "self", ".", "id", ")" ]
43.25
9.75
def stop_cont(self, cont=True): """Send SIGSTOP/SIGCONT to processes called <name> """ for proc in psutil.process_iter(): if proc.name() == self.process_name: sig = psutil.signal.SIGCONT if cont else psutil.signal.SIGSTOP proc.send_signal(sig) ...
[ "def", "stop_cont", "(", "self", ",", "cont", "=", "True", ")", ":", "for", "proc", "in", "psutil", ".", "process_iter", "(", ")", ":", "if", "proc", ".", "name", "(", ")", "==", "self", ".", "process_name", ":", "sig", "=", "psutil", ".", "signal"...
45.8
11.3
def _download_sdss_image( self): """*download sdss image* """ self.log.info('starting the ``_download_sdss_image`` method') opt = "" if self.grid: opt += "G" if self.label: opt += "L" if self.photocat: opt += "P" ...
[ "def", "_download_sdss_image", "(", "self", ")", ":", "self", ".", "log", ".", "info", "(", "'starting the ``_download_sdss_image`` method'", ")", "opt", "=", "\"\"", "if", "self", ".", "grid", ":", "opt", "+=", "\"G\"", "if", "self", ".", "label", ":", "o...
26.237288
21
def readlink(link): """ readlink(link) -> target Return a string representing the path to which the symbolic link points. """ handle = api.CreateFile( link, 0, 0, None, api.OPEN_EXISTING, api.FILE_FLAG_OPEN_REPARSE_POINT | api.FILE_FLAG_BACKUP_SEMANTICS, None, ) if handle == api.INVALID_HANDLE_VAL...
[ "def", "readlink", "(", "link", ")", ":", "handle", "=", "api", ".", "CreateFile", "(", "link", ",", "0", ",", "0", ",", "None", ",", "api", ".", "OPEN_EXISTING", ",", "api", ".", "FILE_FLAG_OPEN_REPARSE_POINT", "|", "api", ".", "FILE_FLAG_BACKUP_SEMANTICS...
25
21.965517
def _html(self, text): '''Parse a Tweet and generate HTML.''' html = URL_REGEX.sub(self._parse_urls, text) html = USERNAME_REGEX.sub(self._parse_users, html) html = LIST_REGEX.sub(self._parse_lists, html) return HASHTAG_REGEX.sub(self._parse_tags, html)
[ "def", "_html", "(", "self", ",", "text", ")", ":", "html", "=", "URL_REGEX", ".", "sub", "(", "self", ".", "_parse_urls", ",", "text", ")", "html", "=", "USERNAME_REGEX", ".", "sub", "(", "self", ".", "_parse_users", ",", "html", ")", "html", "=", ...
48
14
def closed_issue(issue, after=None): """Returns True iff this issue was closed after given date. If after not given, only checks if issue is closed.""" if issue['state'] == 'closed': if after is None or parse_timestamp(issue['closed_at']) > after: return True return False
[ "def", "closed_issue", "(", "issue", ",", "after", "=", "None", ")", ":", "if", "issue", "[", "'state'", "]", "==", "'closed'", ":", "if", "after", "is", "None", "or", "parse_timestamp", "(", "issue", "[", "'closed_at'", "]", ")", ">", "after", ":", ...
49.833333
13.833333
def predict(self, X): """Rank samples according to survival times Lower ranks indicate shorter survival, higher ranks longer survival. Parameters ---------- X : array-like, shape = (n_samples, n_features) The input samples. Returns ------- y...
[ "def", "predict", "(", "self", ",", "X", ")", ":", "val", "=", "numpy", ".", "dot", "(", "X", ",", "self", ".", "coef_", ")", "if", "hasattr", "(", "self", ",", "\"intercept_\"", ")", ":", "val", "+=", "self", ".", "intercept_", "# Order by increasin...
27.777778
20.148148
def _process_health_pill_event(self, node_name_set, mapping, target_step, file_path): """Creates health pills out of data in an event. Creates health pills out of the event and adds them to the mapping. Args: node_name_set: A set of node names that are relevant. ...
[ "def", "_process_health_pill_event", "(", "self", ",", "node_name_set", ",", "mapping", ",", "target_step", ",", "file_path", ")", ":", "events_loader", "=", "event_file_loader", ".", "EventFileLoader", "(", "file_path", ")", "for", "event", "in", "events_loader", ...
36.938272
20.08642
def update(self, attributes=values.unset, assignment_status=values.unset, reason=values.unset, priority=values.unset, task_channel=values.unset): """ Update the TaskInstance :param unicode attributes: The user-defined JSON data describing the custom attributes of t...
[ "def", "update", "(", "self", ",", "attributes", "=", "values", ".", "unset", ",", "assignment_status", "=", "values", ".", "unset", ",", "reason", "=", "values", ".", "unset", ",", "priority", "=", "values", ".", "unset", ",", "task_channel", "=", "valu...
45.772727
22.954545
def available_formats(): """ Get a list of all available loaders Returns ----------- loaders : list Extensions of available loaders i.e. 'stl', 'ply', 'dxf', etc. """ loaders = mesh_formats() loaders.extend(path_formats()) loaders.extend(compressed_loaders.keys()) ...
[ "def", "available_formats", "(", ")", ":", "loaders", "=", "mesh_formats", "(", ")", "loaders", ".", "extend", "(", "path_formats", "(", ")", ")", "loaders", ".", "extend", "(", "compressed_loaders", ".", "keys", "(", ")", ")", "return", "loaders" ]
21.533333
14.733333
def to_dict(self, db_obj): """Create a Json-like dictionary for objects managed by this object store. Parameters ---------- db_obj : (Sub-class of)ObjectHandle Returns ------- (JSON) Json-like object, i.e., dictionary. """ # B...
[ "def", "to_dict", "(", "self", ",", "db_obj", ")", ":", "# Base Json serialization for database objects", "return", "{", "'_id'", ":", "db_obj", ".", "identifier", ",", "'timestamp'", ":", "str", "(", "db_obj", ".", "timestamp", ".", "isoformat", "(", ")", ")"...
28.277778
17.5
def _zforce(self,R,z,phi=0.,t=0.): """ NAME: _zforce PURPOSE: evaluate the vertical force for this potential INPUT: R - Galactocentric cylindrical radius z - vertical height phi - azimuth t - time OUTPUT: ...
[ "def", "_zforce", "(", "self", ",", "R", ",", "z", ",", "phi", "=", "0.", ",", "t", "=", "0.", ")", ":", "sqrtbz", "=", "nu", ".", "sqrt", "(", "self", ".", "_b2", "+", "z", "**", "2.", ")", "asqrtbz", "=", "self", ".", "_a", "+", "sqrtbz",...
31.166667
15.916667
def load(file): """ This function expects a path to a file containing a **Detailed billing report with resources and tags** report from AWS. It returns a ``Costs`` object containing all of the lineitems from that detailed billing report """ fp = open(file) reader = csv.reader(fp) ...
[ "def", "load", "(", "file", ")", ":", "fp", "=", "open", "(", "file", ")", "reader", "=", "csv", ".", "reader", "(", "fp", ")", "headers", "=", "next", "(", "reader", ")", "costs", "=", "Costs", "(", "headers", ")", "for", "line", "in", "reader",...
30.272727
16.818182
def list_color_tag(self, pkg): """Tag with color installed packages """ name = GetFromInstalled(pkg).name() find = name + self.meta.sp if pkg.endswith(".txz") or pkg.endswith(".tgz"): find = pkg[:-4] if find_package(find, self.meta.pkg_path): pkg =...
[ "def", "list_color_tag", "(", "self", ",", "pkg", ")", ":", "name", "=", "GetFromInstalled", "(", "pkg", ")", ".", "name", "(", ")", "find", "=", "name", "+", "self", ".", "meta", ".", "sp", "if", "pkg", ".", "endswith", "(", "\".txz\"", ")", "or",...
40.090909
11.636364
def get_mini_reviews(recid, ln=CFG_SITE_LANG): """ Returns the web controls to add reviews to a record from the detailed record pages mini-panel. :param recid: the id of the displayed record :param ln: the user's language """ if CFG_WEBCOMMENT_ALLOW_SHORT_REVIEWS: action = 'SUBMIT' ...
[ "def", "get_mini_reviews", "(", "recid", ",", "ln", "=", "CFG_SITE_LANG", ")", ":", "if", "CFG_WEBCOMMENT_ALLOW_SHORT_REVIEWS", ":", "action", "=", "'SUBMIT'", "else", ":", "action", "=", "'DISPLAY'", "reviews", "=", "query_retrieve_comments_or_remarks", "(", "recid...
28.238095
16.428571
def metadefs_namespace_list(request, filters=None, sort_dir='asc', sort_key='namespace', marker=None, paginate=False): """Retrieve a listing of Namespaces :param paginate:...
[ "def", "metadefs_namespace_list", "(", "request", ",", "filters", "=", "None", ",", "sort_dir", "=", "'asc'", ",", "sort_key", "=", "'namespace'", ",", "marker", "=", "None", ",", "paginate", "=", "False", ")", ":", "# Listing namespaces requires the v2 API. If no...
40.309524
18.595238
def cb_full_documentation(self, option, optname, value, parser): """optik callback for printing full documentation""" self.linter.print_full_documentation() sys.exit(0)
[ "def", "cb_full_documentation", "(", "self", ",", "option", ",", "optname", ",", "value", ",", "parser", ")", ":", "self", ".", "linter", ".", "print_full_documentation", "(", ")", "sys", ".", "exit", "(", "0", ")" ]
47.25
12.75
def _delete_value(self, entity): """Internal helper to delete the value for this Property from an entity. Note that if no value exists this is a no-op; deleted values will not be serialized but requesting their value will return None (or an empty list in the case of a repeated Property). """ if...
[ "def", "_delete_value", "(", "self", ",", "entity", ")", ":", "if", "self", ".", "_name", "in", "entity", ".", "_values", ":", "del", "entity", ".", "_values", "[", "self", ".", "_name", "]" ]
42.111111
14.222222
def _get_populate_from_value(instance, field_name: Union[str, Tuple[str]], language: str): """Gets the value to create a slug from in the specified language. Arguments: instance: The model that the field resides on. field_name: The name of the fi...
[ "def", "_get_populate_from_value", "(", "instance", ",", "field_name", ":", "Union", "[", "str", ",", "Tuple", "[", "str", "]", "]", ",", "language", ":", "str", ")", ":", "if", "callable", "(", "field_name", ")", ":", "return", "field_name", "(", "insta...
30.382353
21.411765
def setHorizontalAxis(self, axis): """ Sets the horizontal axis for this chart. :param axis | <XChartAxis> """ self._horizontalAxis = axis if axis: axis.setOrientation(Qt.Horizontal) self.uiXAxisVIEW.setFixedHeight(axis.minim...
[ "def", "setHorizontalAxis", "(", "self", ",", "axis", ")", ":", "self", ".", "_horizontalAxis", "=", "axis", "if", "axis", ":", "axis", ".", "setOrientation", "(", "Qt", ".", "Horizontal", ")", "self", ".", "uiXAxisVIEW", ".", "setFixedHeight", "(", "axis"...
32.833333
13.166667
def count_header_blanks(lines, count): """ Count the number of blank lines in the header """ blanks = 0 for i in range(2, count + 2): pair = _extract_header_value(lines[i]) if not pair: blanks += 1 return blanks
[ "def", "count_header_blanks", "(", "lines", ",", "count", ")", ":", "blanks", "=", "0", "for", "i", "in", "range", "(", "2", ",", "count", "+", "2", ")", ":", "pair", "=", "_extract_header_value", "(", "lines", "[", "i", "]", ")", "if", "not", "pai...
25.4
11
def get_operation_pattern(server_url, request_url_pattern): """Return an updated request URL pattern with the server URL removed.""" if server_url[-1] == "/": # operations have to start with a slash, so do not remove it server_url = server_url[:-1] if is_absolute(server_url): return ...
[ "def", "get_operation_pattern", "(", "server_url", ",", "request_url_pattern", ")", ":", "if", "server_url", "[", "-", "1", "]", "==", "\"/\"", ":", "# operations have to start with a slash, so do not remove it", "server_url", "=", "server_url", "[", ":", "-", "1", ...
53.25
14.75
def interpret_distro_name( location, basename, metadata, py_version=None, precedence=SOURCE_DIST, platform=None ): """Generate alternative interpretations of a source distro name Note: if `location` is a filesystem filename, you should call ``pkg_resources.normalize_path()`` on it before pa...
[ "def", "interpret_distro_name", "(", "location", ",", "basename", ",", "metadata", ",", "py_version", "=", "None", ",", "precedence", "=", "SOURCE_DIST", ",", "platform", "=", "None", ")", ":", "# Generate alternative interpretations of a source distro name", "# Because...
47
26.030303
def get_parent_bin_nodes(self): """Gets the parents of this bin. return: (osid.resource.BinNodeList) - the parents of the ``id`` *compliance: mandatory -- This method must be implemented.* """ parent_bin_nodes = [] for node in self._my_map['parentNodes']: pa...
[ "def", "get_parent_bin_nodes", "(", "self", ")", ":", "parent_bin_nodes", "=", "[", "]", "for", "node", "in", "self", ".", "_my_map", "[", "'parentNodes'", "]", ":", "parent_bin_nodes", ".", "append", "(", "BinNode", "(", "node", ".", "_my_map", ",", "runt...
35.933333
13.733333
def get_bits_needed(n): """ Calculates the smallest positive integer :math:`m` for which :math:`2^m\geq n`. :param int n: A positive integer :return: The positive integer :math:`m`, as specified above :rtype: int """ assert n > 0, "Inout should be positive" num_bits = int(np.ceil(...
[ "def", "get_bits_needed", "(", "n", ")", ":", "assert", "n", ">", "0", ",", "\"Inout should be positive\"", "num_bits", "=", "int", "(", "np", ".", "ceil", "(", "np", ".", "log2", "(", "n", ")", ")", ")", "return", "max", "(", "1", ",", "num_bits", ...
24.785714
17.785714
def from_representation(self, representation): """Convert given representation dict into internal object. Internal object is simply a dictionary of values with respect to field sources. This does not check if all required fields exist or values are valid in terms of value valid...
[ "def", "from_representation", "(", "self", ",", "representation", ")", ":", "object_dict", "=", "{", "}", "failed", "=", "{", "}", "for", "name", ",", "field", "in", "self", ".", "fields", ".", "items", "(", ")", ":", "if", "name", "not", "in", "repr...
39.696203
21.962025
def _item_sources(self): """List of places to look-up items for key-completion""" return [self.data_vars, self.coords, {d: self[d] for d in self.dims}, LevelCoordinatesSource(self)]
[ "def", "_item_sources", "(", "self", ")", ":", "return", "[", "self", ".", "data_vars", ",", "self", ".", "coords", ",", "{", "d", ":", "self", "[", "d", "]", "for", "d", "in", "self", ".", "dims", "}", ",", "LevelCoordinatesSource", "(", "self", "...
52.5
14.5
def compile_flags(args): """ Build a dictionnary with an entry for cppflags, ldflags, and cxxflags. These options are filled according to the command line defined options """ compiler_options = { 'define_macros': args.defines, 'undef_macros': args.undefs, 'include_dirs': a...
[ "def", "compile_flags", "(", "args", ")", ":", "compiler_options", "=", "{", "'define_macros'", ":", "args", ".", "defines", ",", "'undef_macros'", ":", "args", ".", "undefs", ",", "'include_dirs'", ":", "args", ".", "include_dirs", ",", "'extra_compile_args'", ...
28
16.727273
def stderr_with_input(cmd, stdin): """Runs a command, passing something in stdin, and returning whatever came out from stdout""" handle, gpg_stderr = stderr_handle() LOGGER.debug("GPG command %s", ' '.join(cmd)) try: gpg_proc = subprocess.Popen(cmd, # nosec ...
[ "def", "stderr_with_input", "(", "cmd", ",", "stdin", ")", ":", "handle", ",", "gpg_stderr", "=", "stderr_handle", "(", ")", "LOGGER", ".", "debug", "(", "\"GPG command %s\"", ",", "' '", ".", "join", "(", "cmd", ")", ")", "try", ":", "gpg_proc", "=", ...
38.333333
18.428571
def new(self): # type: () -> None ''' A method to create a new UDF Logical Volume Descriptor. Parameters: None. Returns: Nothing. ''' if self._initialized: raise pycdlibexception.PyCdlibInternalError('UDF Logical Volume Descriptor al...
[ "def", "new", "(", "self", ")", ":", "# type: () -> None", "if", "self", ".", "_initialized", ":", "raise", "pycdlibexception", ".", "PyCdlibInternalError", "(", "'UDF Logical Volume Descriptor already initialized'", ")", "self", ".", "desc_tag", "=", "UDFTag", "(", ...
31.342105
24.815789
async def get_or_create(cls, lang: str, *, client_token: str = None, mounts: Iterable[str] = None, envs: Mapping[str, str] = None, resources: Mapping[str, int] = None, cluster_size...
[ "async", "def", "get_or_create", "(", "cls", ",", "lang", ":", "str", ",", "*", ",", "client_token", ":", "str", "=", "None", ",", "mounts", ":", "Iterable", "[", "str", "]", "=", "None", ",", "envs", ":", "Mapping", "[", "str", ",", "str", "]", ...
46.112903
20.564516
def _unpack_observation(self, obs_batch): """Unpacks the action mask / tuple obs from agent grouping. Returns: obs (Tensor): flattened obs tensor of shape [B, n_agents, obs_size] mask (Tensor): action mask, if any """ unpacked = _unpack_obs( np.array(...
[ "def", "_unpack_observation", "(", "self", ",", "obs_batch", ")", ":", "unpacked", "=", "_unpack_obs", "(", "np", ".", "array", "(", "obs_batch", ")", ",", "self", ".", "observation_space", ".", "original_space", ",", "tensorlib", "=", "np", ")", "if", "se...
41.8
15.88
def fetch_next(self, query=None, **kwargs): """Generator to yield data one row at a time. Yields a Result, not the entire ResultSet. The containing ResultSet can be accessed through `Result.resultset`, but be careful not to manipulate the ResultSet until it is populated (when this genera...
[ "def", "fetch_next", "(", "self", ",", "query", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "query", ":", "self", ".", "query", "=", "query", "hash_", "=", "self", ".", "_hash", "if", "hash_", "in", "self", ".", "_data", ":", "for", "re...
38.653846
15.884615
def _remaining_points(hands): ''' :param list hands: hands for which to compute the remaining points :return: a list indicating the amount of points remaining in each of the input hands ''' points = [] for hand in hands: points.append(sum(d.first + d.second for d in hand)) ...
[ "def", "_remaining_points", "(", "hands", ")", ":", "points", "=", "[", "]", "for", "hand", "in", "hands", ":", "points", ".", "append", "(", "sum", "(", "d", ".", "first", "+", "d", ".", "second", "for", "d", "in", "hand", ")", ")", "return", "p...
29.727273
23
def _dump_stats_group(self, title, items, normal_formatter=None, verbose_formatter=None): """Dump a statistics group. In verbose mode, do so as a config file so that other processors can load the information if they want to. :param normal_formatter: the callable to apply...
[ "def", "_dump_stats_group", "(", "self", ",", "title", ",", "items", ",", "normal_formatter", "=", "None", ",", "verbose_formatter", "=", "None", ")", ":", "if", "self", ".", "verbose", ":", "self", ".", "outf", ".", "write", "(", "\"[%s]\\n\"", "%", "("...
43.961538
12.884615
def to_jd(baktun, katun, tun, uinal, kin): '''Determine Julian day from Mayan long count''' return EPOCH + (baktun * 144000) + (katun * 7200) + (tun * 360) + (uinal * 20) + kin
[ "def", "to_jd", "(", "baktun", ",", "katun", ",", "tun", ",", "uinal", ",", "kin", ")", ":", "return", "EPOCH", "+", "(", "baktun", "*", "144000", ")", "+", "(", "katun", "*", "7200", ")", "+", "(", "tun", "*", "360", ")", "+", "(", "uinal", ...
60.666667
20.666667
def _ensureDir(dir_name): """Create dir_name as a directory if it does not exist. If it exists, make sure that it is, in fact, a directory. Can raise OSError str -> NoneType """ try: os.makedirs(dir_name) except OSError, why: if why.errno != EEXIST or not os.path.isdir(dir_...
[ "def", "_ensureDir", "(", "dir_name", ")", ":", "try", ":", "os", ".", "makedirs", "(", "dir_name", ")", "except", "OSError", ",", "why", ":", "if", "why", ".", "errno", "!=", "EEXIST", "or", "not", "os", ".", "path", ".", "isdir", "(", "dir_name", ...
25.538462
19.538462
def start(self): """Activate a patch, returning any created mock.""" result = self.__enter__() self._active_patches.add(self) return result
[ "def", "start", "(", "self", ")", ":", "result", "=", "self", ".", "__enter__", "(", ")", "self", ".", "_active_patches", ".", "add", "(", "self", ")", "return", "result" ]
33.4
10.4
def clean_caches(path): """ Removes all python cache files recursively on a path. :param path: the path :return: None """ for dirname, subdirlist, filelist in os.walk(path): for f in filelist: if f.endswith('pyc'): try: os.remove(os.path...
[ "def", "clean_caches", "(", "path", ")", ":", "for", "dirname", ",", "subdirlist", ",", "filelist", "in", "os", ".", "walk", "(", "path", ")", ":", "for", "f", "in", "filelist", ":", "if", "f", ".", "endswith", "(", "'pyc'", ")", ":", "try", ":", ...
24.578947
17.315789
def login_checking_email(pending_id, ticket, response, detail_url='https://pswdless.appspot.com/rest/detail'): """ Log user in using Passwordless service :param pending_id: PendingExternalToMainUser's id :param ticket: ticket returned from Passwordless :param response: Response object from webapp2 ...
[ "def", "login_checking_email", "(", "pending_id", ",", "ticket", ",", "response", ",", "detail_url", "=", "'https://pswdless.appspot.com/rest/detail'", ")", ":", "return", "LoginCheckingEmail", "(", "pending_id", ",", "ticket", ",", "response", ",", "USER_COOKIE_NAME", ...
51.8
18.4
def fit(self, X, y, n_iter=None): """w = w + α * δ * X""" self.n_iter = self.n_iter if n_iter is None else n_iter X = getattr(X, 'values', X).reshape(len(X), 1) X_1 = self.homogenize(X) for i in range(self.n_iter): for i in range(0, len(X), 10): # minibatch learning ...
[ "def", "fit", "(", "self", ",", "X", ",", "y", ",", "n_iter", "=", "None", ")", ":", "self", ".", "n_iter", "=", "self", ".", "n_iter", "if", "n_iter", "is", "None", "else", "n_iter", "X", "=", "getattr", "(", "X", ",", "'values'", ",", "X", ")...
50.153846
17
def close(self): """ Shutdown the environment. """ if "_tx" in self.__dict__ and "_proc" in self.__dict__: self._tx.put(("close", (), {})) self._proc.join()
[ "def", "close", "(", "self", ")", ":", "if", "\"_tx\"", "in", "self", ".", "__dict__", "and", "\"_proc\"", "in", "self", ".", "__dict__", ":", "self", ".", "_tx", ".", "put", "(", "(", "\"close\"", ",", "(", ")", ",", "{", "}", ")", ")", "self", ...
29.428571
9.714286
async def fetch_emojis(self): r"""|coro| Retrieves all custom :class:`Emoji`\s from the guild. .. note:: This method is an API call. For general usage, consider :attr:`emojis` instead. Raises --------- HTTPException An error occurred fetching t...
[ "async", "def", "fetch_emojis", "(", "self", ")", ":", "data", "=", "await", "self", ".", "_state", ".", "http", ".", "get_all_custom_emojis", "(", "self", ".", "id", ")", "return", "[", "Emoji", "(", "guild", "=", "self", ",", "state", "=", "self", ...
26.857143
24.52381
def dt_to_timestamp(dt): """Converts from a :class:`~datetime.datetime` object to an integer timestamp, suitable interoperation with :func:`time.time` and other `Epoch-based timestamps`. .. _Epoch-based timestamps: https://en.wikipedia.org/wiki/Unix_time >>> abs(round(time.time() - dt_to_timestamp...
[ "def", "dt_to_timestamp", "(", "dt", ")", ":", "if", "dt", ".", "tzinfo", ":", "td", "=", "dt", "-", "EPOCH_AWARE", "else", ":", "td", "=", "dt", "-", "EPOCH_NAIVE", "return", "total_seconds", "(", "td", ")" ]
39.56
21.24
def extra_args_parser(parser=None, skip_args=None, **kwargs): """Adds --temps to MCMCIO parser. """ if skip_args is None: skip_args = [] parser, actions = MCMCMetadataIO.extra_args_parser( parser=parser, skip_args=skip_args, **kwargs) if 'temps' not in ski...
[ "def", "extra_args_parser", "(", "parser", "=", "None", ",", "skip_args", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "skip_args", "is", "None", ":", "skip_args", "=", "[", "]", "parser", ",", "actions", "=", "MCMCMetadataIO", ".", "extra_args_...
48.75
16.75
def __fade_in(self): """ Starts the Widget fade in. """ self.__timer.stop() self.__vector = self.__fade_speed self.__timer.start()
[ "def", "__fade_in", "(", "self", ")", ":", "self", ".", "__timer", ".", "stop", "(", ")", "self", ".", "__vector", "=", "self", ".", "__fade_speed", "self", ".", "__timer", ".", "start", "(", ")" ]
21.5
11.5
def _validate_value(key, value, expected_type): """ function to check expected type and raise error if type is not correct """ if not isinstance(value, expected_type): raise TypeError("{} argument must have a type {} not {}".format( key, expected_type, type(value)))
[ "def", "_validate_value", "(", "key", ",", "value", ",", "expected_type", ")", ":", "if", "not", "isinstance", "(", "value", ",", "expected_type", ")", ":", "raise", "TypeError", "(", "\"{} argument must have a type {} not {}\"", ".", "format", "(", "key", ",", ...
48.833333
8
def x_rotate(rotationAmt): """Create a matrix that rotates around the x axis.""" ma4 = Matrix4((1, 0, 0, 0), (0, math.cos(rotationAmt), -math.sin(rotationAmt), 0), (0, math.sin(rotationAmt), math.cos(rotationAmt), 0), (0, 0, 0, 1)) ...
[ "def", "x_rotate", "(", "rotationAmt", ")", ":", "ma4", "=", "Matrix4", "(", "(", "1", ",", "0", ",", "0", ",", "0", ")", ",", "(", "0", ",", "math", ".", "cos", "(", "rotationAmt", ")", ",", "-", "math", ".", "sin", "(", "rotationAmt", ")", ...
40.75
19.625
def setEmergencyDecel(self, vehID, decel): """setEmergencyDecel(string, double) -> None Sets the maximal physically possible deceleration in m/s^2 for this vehicle. """ self._connection._sendDoubleCmd( tc.CMD_SET_VEHICLE_VARIABLE, tc.VAR_EMERGENCY_DECEL, vehID, decel)
[ "def", "setEmergencyDecel", "(", "self", ",", "vehID", ",", "decel", ")", ":", "self", ".", "_connection", ".", "_sendDoubleCmd", "(", "tc", ".", "CMD_SET_VEHICLE_VARIABLE", ",", "tc", ".", "VAR_EMERGENCY_DECEL", ",", "vehID", ",", "decel", ")" ]
43.857143
17.714286
def q_if(self, *qregs): """Add controls to this gate.""" self.data = [gate.q_if(qregs) for gate in self.data] return self
[ "def", "q_if", "(", "self", ",", "*", "qregs", ")", ":", "self", ".", "data", "=", "[", "gate", ".", "q_if", "(", "qregs", ")", "for", "gate", "in", "self", ".", "data", "]", "return", "self" ]
35.5
14.5
def login(method): """Require user to login.""" def wrapper(*args, **kwargs): crawler = args[0].crawler # args[0] is a NetEase object try: if os.path.isfile(cookie_path): with open(cookie_path, 'r') as cookie_file: cookie = cookie_file.read() ...
[ "def", "login", "(", "method", ")", ":", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "crawler", "=", "args", "[", "0", "]", ".", "crawler", "# args[0] is a NetEase object", "try", ":", "if", "os", ".", "path", ".", "isfile"...
34.2
18.44
def listSubjectsResponse( self, query, status=None, start=None, count=None, vendorSpecific=None ): """CNIdentity.listSubjects(session, query, status, start, count) → SubjectList https://releases.dataone.org/online/api- documentation-v2.0.1/apis/CN_APIs.html#CNIdentity.listSubjects. ...
[ "def", "listSubjectsResponse", "(", "self", ",", "query", ",", "status", "=", "None", ",", "start", "=", "None", ",", "count", "=", "None", ",", "vendorSpecific", "=", "None", ")", ":", "url_query", "=", "{", "'status'", ":", "status", ",", "'start'", ...
31.842105
25.684211
def _dns_info_mapper(self, raw_dns): """The method maps the specific fields/flags in a DNS record to human readable form""" output = {} # Indentification output['identification'] = raw_dns['id'] # Pull out all the flags flags = {} flags['type'] = 'query' if raw_...
[ "def", "_dns_info_mapper", "(", "self", ",", "raw_dns", ")", ":", "output", "=", "{", "}", "# Indentification", "output", "[", "'identification'", "]", "=", "raw_dns", "[", "'id'", "]", "# Pull out all the flags", "flags", "=", "{", "}", "flags", "[", "'type...
39.421875
19.390625
def init_neutron_consumer(self, mq): """ Init openstack neutron mq 1. Check if enable listening neutron notification 2. Create consumer :param mq: class ternya.mq.MQ """ if not self.enable_component_notification(Openstack.Neutron): log.debug("disable...
[ "def", "init_neutron_consumer", "(", "self", ",", "mq", ")", ":", "if", "not", "self", ".", "enable_component_notification", "(", "Openstack", ".", "Neutron", ")", ":", "log", ".", "debug", "(", "\"disable listening neutron notification\"", ")", "return", "for", ...
36.210526
21.368421
def show(self, commit): """Display one commit line. The output will be: <uuid> <#lines> <author> <short-commit-date> If verbose flag set, the output will be: <uuid> <#lines> <author+email> <long-date> <committer+email> """ author = commit.author ...
[ "def", "show", "(", "self", ",", "commit", ")", ":", "author", "=", "commit", ".", "author", "author_width", "=", "25", "committer", "=", "''", "commit_date", "=", "date_to_str", "(", "commit", ".", "committer_time", ",", "commit", ".", "committer_tz", ","...
38.285714
17.52381
def on_channel_open(self, channel): """This method is invoked by pika when the channel has been opened. It will change the state to CONNECTED, add the callbacks and setup the channel to start consuming. :param pika.channel.Channel channel: The channel object """ self.lo...
[ "def", "on_channel_open", "(", "self", ",", "channel", ")", ":", "self", ".", "logger", ".", "debug", "(", "'Channel opened'", ")", "self", ".", "set_state", "(", "self", ".", "STATE_CONNECTED", ")", "self", ".", "channel", "=", "channel", "self", ".", "...
44
15.388889
def posterior(self, x): """Model is X_1,...,X_n ~ N(0, 1/theta), theta ~ Gamma(a, b)""" return Gamma(a=self.a + 0.5 * x.size, b=self.b + 0.5 * np.sum(x**2))
[ "def", "posterior", "(", "self", ",", "x", ")", ":", "return", "Gamma", "(", "a", "=", "self", ".", "a", "+", "0.5", "*", "x", ".", "size", ",", "b", "=", "self", ".", "b", "+", "0.5", "*", "np", ".", "sum", "(", "x", "**", "2", ")", ")" ...
47.5
8.25
def get_imports(fname): """ get a list of imports from a Python program """ txt = '' with open(fname, 'r') as f: for line in f: if line[0:6] == 'import': txt += '<PRE>' + strip_text_after_string(line[7:], ' as ') + '</PRE>\n' return txt + '<BR>'
[ "def", "get_imports", "(", "fname", ")", ":", "txt", "=", "''", "with", "open", "(", "fname", ",", "'r'", ")", "as", "f", ":", "for", "line", "in", "f", ":", "if", "line", "[", "0", ":", "6", "]", "==", "'import'", ":", "txt", "+=", "'<PRE>'", ...
36.25
17.375
def doubleclick(self, window_name, object_name): """ Double click on the object @param window_name: Window name to look for, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @param object_name: Object name to look for, either fu...
[ "def", "doubleclick", "(", "self", ",", "window_name", ",", "object_name", ")", ":", "object_handle", "=", "self", ".", "_get_object_handle", "(", "window_name", ",", "object_name", ")", "if", "not", "object_handle", ".", "AXEnabled", ":", "raise", "LdtpServerEx...
40.916667
15.75
def get_commensurate_points(supercell_matrix): # wrt primitive cell """Commensurate q-points are returned. Parameters ---------- supercell_matrix : array_like Supercell matrix with respect to primitive cell basis vectors. shape=(3, 3) dtype=intc """ smat = np.array(su...
[ "def", "get_commensurate_points", "(", "supercell_matrix", ")", ":", "# wrt primitive cell", "smat", "=", "np", ".", "array", "(", "supercell_matrix", ",", "dtype", "=", "int", ")", "rec_primitive", "=", "PhonopyAtoms", "(", "numbers", "=", "[", "1", "]", ",",...
36
18.52381
def check_variable_names(self, ds): """ Ensures all variables have a standard_name set. """ msgs = [] count = 0 for k, v in ds.variables.items(): if 'standard_name' in v.ncattrs(): count += 1 else: msgs.append("Vari...
[ "def", "check_variable_names", "(", "self", ",", "ds", ")", ":", "msgs", "=", "[", "]", "count", "=", "0", "for", "k", ",", "v", "in", "ds", ".", "variables", ".", "items", "(", ")", ":", "if", "'standard_name'", "in", "v", ".", "ncattrs", "(", "...
32
20.142857
def process_item(self, item, spider): # pylint: disable=unused-argument """ Stops processing item if we've already seen this URL before. """ url = self.clean_url(item["url"]) if self.is_sequence_start_page(url): url = url.parent if url in self.urls_seen: ...
[ "def", "process_item", "(", "self", ",", "item", ",", "spider", ")", ":", "# pylint: disable=unused-argument", "url", "=", "self", ".", "clean_url", "(", "item", "[", "\"url\"", "]", ")", "if", "self", ".", "is_sequence_start_page", "(", "url", ")", ":", "...
33
18.285714
def add_user(self, users=None, groups=None): """Add the specified users or groups to this project role. One of ``users`` or ``groups`` must be specified. :param users: a user or users to add to the role :type users: string, list or tuple :param groups: a group or groups to add ...
[ "def", "add_user", "(", "self", ",", "users", "=", "None", ",", "groups", "=", "None", ")", ":", "if", "users", "is", "not", "None", "and", "isinstance", "(", "users", ",", "string_types", ")", ":", "users", "=", "(", "users", ",", ")", "if", "grou...
35.263158
18.578947
def deserialize_value(ty, value): ''' Deserialize a value of some type ''' uty = ty.upper() if uty == 'BOOLEAN': if value.isdigit(): return bool(int(value)) elif value.upper() == 'FALSE': return False elif value.upper() == 'TRUE': retu...
[ "def", "deserialize_value", "(", "ty", ",", "value", ")", ":", "uty", "=", "ty", ".", "upper", "(", ")", "if", "uty", "==", "'BOOLEAN'", ":", "if", "value", ".", "isdigit", "(", ")", ":", "return", "bool", "(", "int", "(", "value", ")", ")", "eli...
23.242424
17.666667
def set_base_headers(self, hdr): """Set metadata in FITS headers.""" hdr = super(StareImageRecipe2, self).set_base_headers(hdr) # Set EXP to 0 hdr['EXP'] = 0 return hdr
[ "def", "set_base_headers", "(", "self", ",", "hdr", ")", ":", "hdr", "=", "super", "(", "StareImageRecipe2", ",", "self", ")", ".", "set_base_headers", "(", "hdr", ")", "# Set EXP to 0", "hdr", "[", "'EXP'", "]", "=", "0", "return", "hdr" ]
33.833333
15.333333
def to_message(self): """Collate all message elements to a single message.""" my_message = m.Message() if self.static_message is not None: my_message.add(self.static_message) for myDynamic in self.dynamic_messages: my_message.add(myDynamic) return my_messa...
[ "def", "to_message", "(", "self", ")", ":", "my_message", "=", "m", ".", "Message", "(", ")", "if", "self", ".", "static_message", "is", "not", "None", ":", "my_message", ".", "add", "(", "self", ".", "static_message", ")", "for", "myDynamic", "in", "s...
39.375
7.75
def is_stale(target, source): """Test whether the target file/directory is stale based on the source file/directory. """ if not os.path.exists(target): return True target_mtime = recursive_mtime(target) or 0 return compare_recursive_mtime(source, cutoff=target_mtime)
[ "def", "is_stale", "(", "target", ",", "source", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "target", ")", ":", "return", "True", "target_mtime", "=", "recursive_mtime", "(", "target", ")", "or", "0", "return", "compare_recursive_mtime",...
36.875
10.75
def _valcache_lookup(self, cache, branch, turn, tick): """Return the value at the given time in ``cache``""" if branch in cache: branc = cache[branch] try: if turn in branc and branc[turn].rev_gettable(tick): return branc[turn][tick] ...
[ "def", "_valcache_lookup", "(", "self", ",", "cache", ",", "branch", ",", "turn", ",", "tick", ")", ":", "if", "branch", "in", "cache", ":", "branc", "=", "cache", "[", "branch", "]", "try", ":", "if", "turn", "in", "branc", "and", "branc", "[", "t...
43
11.366667
def from_mapping(self, mapping: Optional[Mapping[str, Any]]=None, **kwargs: Any) -> None: """Load the configuration values from a mapping. This allows either a mapping to be directly passed or as keyword arguments, for example, .. code-block:: python config = {'FOO': 'bar'...
[ "def", "from_mapping", "(", "self", ",", "mapping", ":", "Optional", "[", "Mapping", "[", "str", ",", "Any", "]", "]", "=", "None", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "None", ":", "mappings", ":", "Dict", "[", "str", ",", "Any", "]",...
34.083333
15.458333
def read_if_vcf(params): """ Checks if input is VCF and reads in appropriately if it is """ ref = None aln = params.aln fixed_pi = None if hasattr(params, 'aln') and params.aln is not None: if any([params.aln.lower().endswith(x) for x in ['.vcf', '.vcf.gz']]): if not para...
[ "def", "read_if_vcf", "(", "params", ")", ":", "ref", "=", "None", "aln", "=", "params", ".", "aln", "fixed_pi", "=", "None", "if", "hasattr", "(", "params", ",", "'aln'", ")", "and", "params", ".", "aln", "is", "not", "None", ":", "if", "any", "("...
41.12
20.24
def query_pager_by_slug(slug, current_page_num=1, tag='', order=False): ''' Query pager via category slug. ''' cat_rec = MCategory.get_by_slug(slug) if cat_rec: cat_id = cat_rec.uid else: return None # The flowing code is valid. if...
[ "def", "query_pager_by_slug", "(", "slug", ",", "current_page_num", "=", "1", ",", "tag", "=", "''", ",", "order", "=", "False", ")", ":", "cat_rec", "=", "MCategory", ".", "get_by_slug", "(", "slug", ")", "if", "cat_rec", ":", "cat_id", "=", "cat_rec", ...
32.326531
18.612245
def generate_megaman_manifold(sampling=2, nfolds=2, rotate=True, random_state=None): """Generate a manifold of the megaman data""" X, c = generate_megaman_data(sampling) for i in range(nfolds): X = np.hstack([_make_S_curve(x) for x in X.T]) if rotate: rand ...
[ "def", "generate_megaman_manifold", "(", "sampling", "=", "2", ",", "nfolds", "=", "2", ",", "rotate", "=", "True", ",", "random_state", "=", "None", ")", ":", "X", ",", "c", "=", "generate_megaman_data", "(", "sampling", ")", "for", "i", "in", "range", ...
33.285714
16.214286
def get_token_from_offset(self, offset): """ Returns the token containing the given character offset (0-based position in source text), or the preceeding token if the position is between tokens. """ return self._tokens[bisect.bisect(self._token_offsets, offset) - 1]
[ "def", "get_token_from_offset", "(", "self", ",", "offset", ")", ":", "return", "self", ".", "_tokens", "[", "bisect", ".", "bisect", "(", "self", ".", "_token_offsets", ",", "offset", ")", "-", "1", "]" ]
46.833333
17.833333
def get_dump(self, fmap='', with_stats=False): """ Returns the dump the model as a list of strings. """ length = ctypes.c_ulong() sarr = ctypes.POINTER(ctypes.c_char_p)() if self.feature_names is not None and fmap == '': flen = int(len(self.feature_names)) ...
[ "def", "get_dump", "(", "self", ",", "fmap", "=", "''", ",", "with_stats", "=", "False", ")", ":", "length", "=", "ctypes", ".", "c_ulong", "(", ")", "sarr", "=", "ctypes", ".", "POINTER", "(", "ctypes", ".", "c_char_p", ")", "(", ")", "if", "self"...
47.628571
20.657143
def _should_cache_target_dir(self, vt): """Return true if the given vt should be written to a cache (if configured).""" return ( self.cache_target_dirs and vt.cacheable and (not vt.is_incremental or self.cache_incremental) and self.artifact_cache_writes_enabled() )
[ "def", "_should_cache_target_dir", "(", "self", ",", "vt", ")", ":", "return", "(", "self", ".", "cache_target_dirs", "and", "vt", ".", "cacheable", "and", "(", "not", "vt", ".", "is_incremental", "or", "self", ".", "cache_incremental", ")", "and", "self", ...
36.75
13.875
def get_partition_column_statistics(self, db_name, tbl_name, part_name, col_name): """ Parameters: - db_name - tbl_name - part_name - col_name """ self.send_get_partition_column_statistics(db_name, tbl_name, part_name, col_name) return self.recv_get_partition_column_statistics()
[ "def", "get_partition_column_statistics", "(", "self", ",", "db_name", ",", "tbl_name", ",", "part_name", ",", "col_name", ")", ":", "self", ".", "send_get_partition_column_statistics", "(", "db_name", ",", "tbl_name", ",", "part_name", ",", "col_name", ")", "retu...
31
22.6
def match_function_pattern(self, first, rest=None, least=1, offset=0): """Match each char sequentially from current SourceString position until the pattern doesnt match and return all maches. Integer argument least defines and minimum amount of chars that can be matched. This v...
[ "def", "match_function_pattern", "(", "self", ",", "first", ",", "rest", "=", "None", ",", "least", "=", "1", ",", "offset", "=", "0", ")", ":", "if", "not", "self", ".", "has_space", "(", "offset", "=", "offset", ")", ":", "return", "''", "firstchar...
33.757576
21.181818
def cmd_whois_domain(domain): """Simple whois client to check domain names. Example: \b $ habu.whois.domain portantier.com { "domain_name": "portantier.com", "registrar": "Amazon Registrar, Inc.", "whois_server": "whois.registrar.amazon.com", ... """ warnin...
[ "def", "cmd_whois_domain", "(", "domain", ")", ":", "warnings", ".", "filterwarnings", "(", "\"ignore\"", ")", "data", "=", "whois", ".", "whois", "(", "domain", ")", "data", "=", "remove_duplicates", "(", "data", ")", "print", "(", "json", ".", "dumps", ...
22.35
19.35
def closing_plugin(self, cancelable=False): """Perform actions before parent main window is closed""" self.save_history() self.set_option('zoom_factor', self.pydocbrowser.webview.get_zoom_factor()) return True
[ "def", "closing_plugin", "(", "self", ",", "cancelable", "=", "False", ")", ":", "self", ".", "save_history", "(", ")", "self", ".", "set_option", "(", "'zoom_factor'", ",", "self", ".", "pydocbrowser", ".", "webview", ".", "get_zoom_factor", "(", ")", ")"...
44.166667
11.166667