text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def _get_NTLMv2_response(user_name, password, domain_name, server_challenge, client_challenge, timestamp, target_info): """ [MS-NLMP] v28.0 2016-07-14 2.2.2.8 NTLM V2 Response: NTLMv2_RESPONSE The NTLMv2_RESPONSE strucutre define...
[ "def", "_get_NTLMv2_response", "(", "user_name", ",", "password", ",", "domain_name", ",", "server_challenge", ",", "client_challenge", ",", "timestamp", ",", "target_info", ")", ":", "nt_hash", "=", "comphash", ".", "_ntowfv2", "(", "user_name", ",", "password", ...
46.909091
0.001898
def semester_feature(catalog, soup): """The year and semester information that this xml file hold courses for. """ raw = soup.coursedb['semesternumber'] catalog.year = int(raw[:4]) month_mapping = {1: 'Spring', 5: 'Summer', 9: 'Fall'} catalog.month = int(raw[4:]) catalog.semester = month_ma...
[ "def", "semester_feature", "(", "catalog", ",", "soup", ")", ":", "raw", "=", "soup", ".", "coursedb", "[", "'semesternumber'", "]", "catalog", ".", "year", "=", "int", "(", "raw", "[", ":", "4", "]", ")", "month_mapping", "=", "{", "1", ":", "'Sprin...
33.076923
0.002262
def getFileLine(where=-1, targetModule=None): """ Return the filename and line number for the given location. If where is a negative integer, look for the code entry in the current stack that is the given number of frames above this module. If where is a function, look for the code entry of the fun...
[ "def", "getFileLine", "(", "where", "=", "-", "1", ",", "targetModule", "=", "None", ")", ":", "co", "=", "None", "lineno", "=", "None", "if", "isinstance", "(", "where", ",", "types", ".", "FunctionType", ")", ":", "co", "=", "where", ".", "func_cod...
31.113208
0.001176
def parse(self, mimetypes): """ Invoke the RFC 2388 spec compliant parser """ self._parse_top_level_content_type() link = 'tools.ietf.org/html/rfc2388' parts = cgi.FieldStorage( fp=self.req.stream, environ=self.req.env, ) if not parts: ...
[ "def", "parse", "(", "self", ",", "mimetypes", ")", ":", "self", ".", "_parse_top_level_content_type", "(", ")", "link", "=", "'tools.ietf.org/html/rfc2388'", "parts", "=", "cgi", ".", "FieldStorage", "(", "fp", "=", "self", ".", "req", ".", "stream", ",", ...
37.727273
0.00235
def parse(self, line, namespace=None): """Parses a line into a dictionary of arguments, expanding meta-variables from a namespace. """ try: if namespace is None: ipy = IPython.get_ipython() namespace = ipy.user_ns args = CommandParser.create_args(line, namespace) return self.pa...
[ "def", "parse", "(", "self", ",", "line", ",", "namespace", "=", "None", ")", ":", "try", ":", "if", "namespace", "is", "None", ":", "ipy", "=", "IPython", ".", "get_ipython", "(", ")", "namespace", "=", "ipy", ".", "user_ns", "args", "=", "CommandPa...
35.363636
0.017544
def update(self, pbar): """Updates the widget to show the ETA or total time when finished.""" if pbar.currval == 0: return 'ETA: --:--:--' elif pbar.finished: return 'Time: %s' % self.format_time(pbar.seconds_elapsed) else: elapsed = pbar.seconds_elap...
[ "def", "update", "(", "self", ",", "pbar", ")", ":", "if", "pbar", ".", "currval", "==", "0", ":", "return", "'ETA: --:--:--'", "elif", "pbar", ".", "finished", ":", "return", "'Time: %s'", "%", "self", ".", "format_time", "(", "pbar", ".", "seconds_ela...
49.823529
0.002317
def pdf(cls, mass, log_mode=True): """ PDF for the Chabrier IMF. The functional form and coefficients are described in Eq 17 and Tab 1 of Chabrier (2003): m <= 1 Msun: E(log m) = A1*exp(-(log m - log m_c)^2 / 2 sigma^2) m > 1 Msun: E(log m) = A2 * m^-x ...
[ "def", "pdf", "(", "cls", ",", "mass", ",", "log_mode", "=", "True", ")", ":", "log_mass", "=", "np", ".", "log10", "(", "mass", ")", "# Constants from Chabrier 2003", "m_c", "=", "0.079", "sigma", "=", "0.69", "x", "=", "1.3", "# This value is set to norm...
33.08
0.008808
def run_task(factory, **kwargs): """\ Run a MapReduce task. Available keyword arguments: * ``raw_keys`` (default: :obj:`False`): pass map input keys to context as byte strings (ignore any type information) * ``raw_values`` (default: :obj:`False`): pass map input values to context as by...
[ "def", "run_task", "(", "factory", ",", "*", "*", "kwargs", ")", ":", "context", "=", "TaskContext", "(", "factory", ",", "*", "*", "kwargs", ")", "pstats_dir", "=", "kwargs", ".", "get", "(", "\"pstats_dir\"", ",", "os", ".", "getenv", "(", "PSTATS_DI...
36.469388
0.000545
def workflow_overwrite(object_id, input_params={}, always_retry=True, **kwargs): """ Invokes the /workflow-xxxx/overwrite API method. For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Workflows-and-Analyses#API-method%3A-%2Fworkflow-xxxx%2Foverwrite """ return DXHTTPRequest('/%...
[ "def", "workflow_overwrite", "(", "object_id", ",", "input_params", "=", "{", "}", ",", "always_retry", "=", "True", ",", "*", "*", "kwargs", ")", ":", "return", "DXHTTPRequest", "(", "'/%s/overwrite'", "%", "object_id", ",", "input_params", ",", "always_retry...
55.714286
0.010101
def sift(data, required_items=None): """ Receive a ``data`` object that will be in the form of a normalized structure (e.g. ``{0: {'a': 0}}``) and filter out keys that match the ``required_items``. """ required_items = required_items or [] new_data = {} for k, v in data.items(): ...
[ "def", "sift", "(", "data", ",", "required_items", "=", "None", ")", ":", "required_items", "=", "required_items", "or", "[", "]", "new_data", "=", "{", "}", "for", "k", ",", "v", "in", "data", ".", "items", "(", ")", ":", "if", "v", "[", "0", "]...
31.526316
0.001621
def allreduce_grads_hierarchical(all_grads, devices, average=False): """ Hierarchical allreduce for DGX-1 system. Args: all_grads (K x N): List of list of gradients. N is the number of variables. devices ([str]): K str for the K devices. average (bool): average gradients or not. ...
[ "def", "allreduce_grads_hierarchical", "(", "all_grads", ",", "devices", ",", "average", "=", "False", ")", ":", "num_gpu", "=", "len", "(", "devices", ")", "assert", "num_gpu", "==", "8", ",", "num_gpu", "assert", "len", "(", "all_grads", ")", "==", "num_...
38.169492
0.001732
def is_tile_strictly_isolated(hand_34, tile_34): """ Tile is strictly isolated if it doesn't have -2, -1, 0, +1, +2 neighbors :param hand_34: array of tiles in 34 tile format :param tile_34: int :return: bool """ hand_34 = copy.copy(hand_34) # we don't need to count target tile in the ha...
[ "def", "is_tile_strictly_isolated", "(", "hand_34", ",", "tile_34", ")", ":", "hand_34", "=", "copy", ".", "copy", "(", "hand_34", ")", "# we don't need to count target tile in the hand", "hand_34", "[", "tile_34", "]", "-=", "1", "if", "hand_34", "[", "tile_34", ...
31.722222
0.001699
def to_json(self): """ Returns: str: Json for commands array object and all of the commands inside the array.""" commands = ",".join(map(lambda x: x.to_json(), self._commands)) return "{\"commands\": [" + commands + "]}"
[ "def", "to_json", "(", "self", ")", ":", "commands", "=", "\",\"", ".", "join", "(", "map", "(", "lambda", "x", ":", "x", ".", "to_json", "(", ")", ",", "self", ".", "_commands", ")", ")", "return", "\"{\\\"commands\\\": [\"", "+", "commands", "+", "...
43.333333
0.011321
def set_item(self, key, value): """ Sets the item by key, and refills the table sorted. """ keys = list(self.keys()) # if it exists, update if key in keys: self.set_value(1,keys.index(key),str(value)) # otherwise we have to add an element els...
[ "def", "set_item", "(", "self", ",", "key", ",", "value", ")", ":", "keys", "=", "list", "(", "self", ".", "keys", "(", ")", ")", "# if it exists, update", "if", "key", "in", "keys", ":", "self", ".", "set_value", "(", "1", ",", "keys", ".", "index...
29.642857
0.014019
def stats(self, keys=None, keystats=False): """Request server statistics. Fetches stats from each node in the cluster. Without a key specified the server will respond with a default set of statistical information. It returns the a `dict` with stats keys and node-value pairs as a...
[ "def", "stats", "(", "self", ",", "keys", "=", "None", ",", "keystats", "=", "False", ")", ":", "if", "keys", "and", "not", "isinstance", "(", "keys", ",", "(", "tuple", ",", "list", ")", ")", ":", "keys", "=", "(", "keys", ",", ")", "return", ...
35.142857
0.001978
def get_report_zip(results): """ Creates a zip file of parsed report output Args: results (OrderedDict): The parsed results Returns: bytes: zip file bytes """ def add_subdir(root_path, subdir): subdir_path = os.path.join(root_path, subdir) for subdir_root, subdi...
[ "def", "get_report_zip", "(", "results", ")", ":", "def", "add_subdir", "(", "root_path", ",", "subdir", ")", ":", "subdir_path", "=", "os", ".", "path", ".", "join", "(", "root_path", ",", "subdir", ")", "for", "subdir_root", ",", "subdir_dirs", ",", "s...
39.906977
0.000569
def replace_braces(s, env): """Makes tox substitutions to s, with respect to environment env. Example ------- >>> replace_braces("echo {posargs:{env:USER:} passed no posargs}") "echo andy passed no posargs" Note: first "{env:USER:}" is replaced with os.environ.get("USER", ""), the "{posarg...
[ "def", "replace_braces", "(", "s", ",", "env", ")", ":", "def", "replace", "(", "m", ")", ":", "return", "_replace_match", "(", "m", ",", "env", ")", "for", "_", "in", "range", "(", "DEPTH", ")", ":", "s", "=", "re", ".", "sub", "(", "r\"{[^{}]*}...
29
0.001855
def rws_call(ctx, method, default_attr=None): """Make request to RWS""" try: response = ctx.obj['RWS'].send_request(method) if ctx.obj['RAW']: # use response from RWS result = ctx.obj['RWS'].last_result.text elif default_attr is not None: # human-readable summary ...
[ "def", "rws_call", "(", "ctx", ",", "method", ",", "default_attr", "=", "None", ")", ":", "try", ":", "response", "=", "ctx", ".", "obj", "[", "'RWS'", "]", ".", "send_request", "(", "method", ")", "if", "ctx", ".", "obj", "[", "'RAW'", "]", ":", ...
34.666667
0.001337
def setup_logging(): """Logging config.""" logging.basicConfig(format=("[%(levelname)s\033[0m] " "\033[1;31m%(module)s\033[0m: " "%(message)s"), level=logging.INFO, stream=sys.stdout) logging.addL...
[ "def", "setup_logging", "(", ")", ":", "logging", ".", "basicConfig", "(", "format", "=", "(", "\"[%(levelname)s\\033[0m] \"", "\"\\033[1;31m%(module)s\\033[0m: \"", "\"%(message)s\"", ")", ",", "level", "=", "logging", ".", "INFO", ",", "stream", "=", "sys", ".",...
46
0.002132
def video_category(self): """doc: http://open.youku.com/docs/doc?id=90 """ url = 'https://openapi.youku.com/v2/schemas/video/category.json' r = requests.get(url) check_error(r) return r.json()
[ "def", "video_category", "(", "self", ")", ":", "url", "=", "'https://openapi.youku.com/v2/schemas/video/category.json'", "r", "=", "requests", ".", "get", "(", "url", ")", "check_error", "(", "r", ")", "return", "r", ".", "json", "(", ")" ]
33.428571
0.008333
def add(self, item): """ Transactional implementation of :func:`Set.add(item) <hazelcast.proxy.set.Set.add>` :param item: (object), the new item to be added. :return: (bool), ``true`` if item is added successfully, ``false`` otherwise. """ check_not_none(item, "item can'...
[ "def", "add", "(", "self", ",", "item", ")", ":", "check_not_none", "(", "item", ",", "\"item can't be none\"", ")", "return", "self", ".", "_encode_invoke", "(", "transactional_set_add_codec", ",", "item", "=", "self", ".", "_to_data", "(", "item", ")", ")"...
45.888889
0.011876
def __ensure_provisioning_alarm(table_name, key_name): """ Ensure that provisioning alarm threshold is not exceeded :type table_name: str :param table_name: Name of the DynamoDB table :type key_name: str :param key_name: Configuration option key name """ lookback_window_start = get_table_op...
[ "def", "__ensure_provisioning_alarm", "(", "table_name", ",", "key_name", ")", ":", "lookback_window_start", "=", "get_table_option", "(", "key_name", ",", "'lookback_window_start'", ")", "lookback_period", "=", "get_table_option", "(", "key_name", ",", "'lookback_period'...
40.923913
0.000519
def lastmod(self, author): """Return the last modification of the entry.""" lastitems = EntryModel.objects.published().order_by('-modification_date').filter(author=author).only('modification_date') return lastitems[0].modification_date
[ "def", "lastmod", "(", "self", ",", "author", ")", ":", "lastitems", "=", "EntryModel", ".", "objects", ".", "published", "(", ")", ".", "order_by", "(", "'-modification_date'", ")", ".", "filter", "(", "author", "=", "author", ")", ".", "only", "(", "...
64
0.011583
def response(self, text, response_type='ephemeral', attachments=None): """Return a response with json format :param text: the text returned to the client :param response_type: optional. When `in_channel` is assigned, both the response message and the initial ...
[ "def", "response", "(", "self", ",", "text", ",", "response_type", "=", "'ephemeral'", ",", "attachments", "=", "None", ")", ":", "from", "flask", "import", "jsonify", "if", "attachments", "is", "None", ":", "attachments", "=", "[", "]", "data", "=", "{"...
41.541667
0.001961
def mul_block(self, index, val): """Multiply values in block""" self._prepare_cache_slice(index) self.msinds[self.cache_slice] *= val
[ "def", "mul_block", "(", "self", ",", "index", ",", "val", ")", ":", "self", ".", "_prepare_cache_slice", "(", "index", ")", "self", ".", "msinds", "[", "self", ".", "cache_slice", "]", "*=", "val" ]
38.5
0.012739
def reopen(args): """reopens a closed poll.""" if not args.isadmin: return "Nope, not gonna do it." msg = args.msg.split() if not msg: return "Syntax: !poll reopen <pollnum>" if not msg[0].isdigit(): return "Not a valid positve integer." pid = int(msg[0]) poll = get_o...
[ "def", "reopen", "(", "args", ")", ":", "if", "not", "args", ".", "isadmin", ":", "return", "\"Nope, not gonna do it.\"", "msg", "=", "args", ".", "msg", ".", "split", "(", ")", "if", "not", "msg", ":", "return", "\"Syntax: !poll reopen <pollnum>\"", "if", ...
31.533333
0.002053
def _interleaved_dtype( blocks: List[Block] ) -> Optional[Union[np.dtype, ExtensionDtype]]: """Find the common dtype for `blocks`. Parameters ---------- blocks : List[Block] Returns ------- dtype : Optional[Union[np.dtype, ExtensionDtype]] None is returned when `blocks` is ...
[ "def", "_interleaved_dtype", "(", "blocks", ":", "List", "[", "Block", "]", ")", "->", "Optional", "[", "Union", "[", "np", ".", "dtype", ",", "ExtensionDtype", "]", "]", ":", "if", "not", "len", "(", "blocks", ")", ":", "return", "None", "return", "...
23.166667
0.002304
def plot(self, colorbar=True, cb_orientation='horizontal', tick_interval=[60, 60], minor_tick_interval=[20, 20], xlabel='Longitude', ylabel='Latitude', axes_labelsize=9, tick_labelsize=8, show=True, fname=None, **kwargs): """ Plot the three vector comp...
[ "def", "plot", "(", "self", ",", "colorbar", "=", "True", ",", "cb_orientation", "=", "'horizontal'", ",", "tick_interval", "=", "[", "60", ",", "60", "]", ",", "minor_tick_interval", "=", "[", "20", ",", "20", "]", ",", "xlabel", "=", "'Longitude'", "...
45.184783
0.001883
def extract(self, content, output): """Try to extract lines from the invoice""" # First apply default options. plugin_settings = DEFAULT_OPTIONS.copy() plugin_settings.update(self['lines']) self['lines'] = plugin_settings # Validate settings assert 'start' in self['lines'], 'Lines start re...
[ "def", "extract", "(", "self", ",", "content", ",", "output", ")", ":", "# First apply default options.", "plugin_settings", "=", "DEFAULT_OPTIONS", ".", "copy", "(", ")", "plugin_settings", ".", "update", "(", "self", "[", "'lines'", "]", ")", "self", "[", ...
39.226667
0.000332
def attention_lm_moe_unscramble_base(): """Version to use with languagemodel_wiki_scramble1k50.""" hparams = attention_lm_no_moe_small() hparams.use_inputs = True hparams.min_length_bucket = 1024 hparams.max_length = 1024 hparams.batch_size = 5000 hparams.layer_prepostprocess_dropout = 0.0 hparams.layer...
[ "def", "attention_lm_moe_unscramble_base", "(", ")", ":", "hparams", "=", "attention_lm_no_moe_small", "(", ")", "hparams", ".", "use_inputs", "=", "True", "hparams", ".", "min_length_bucket", "=", "1024", "hparams", ".", "max_length", "=", "1024", "hparams", ".",...
36.090909
0.027027
def get_activities_by_ids(self, activity_ids=None): """Gets an ActivityList corresponding to the given IdList. In plenary mode, the returned list contains all of the activities specified in the Id list, in the order of the list, including duplicates, or an error results if an Id in the ...
[ "def", "get_activities_by_ids", "(", "self", ",", "activity_ids", "=", "None", ")", ":", "if", "activity_ids", "is", "None", ":", "raise", "NullArgument", "(", ")", "activities", "=", "[", "]", "for", "i", "in", "activity_ids", ":", "activity", "=", "None"...
43.975
0.001112
def create_blog_pages(self, posts, blog_index, *args, **options): """create Blog post entries from wordpress data""" for post in posts: post_id = post.get('ID') title = post.get('title') if title: new_title = self.convert_html_entities(title) ...
[ "def", "create_blog_pages", "(", "self", ",", "posts", ",", "blog_index", ",", "*", "args", ",", "*", "*", "options", ")", ":", "for", "post", "in", "posts", ":", "post_id", "=", "post", ".", "get", "(", "'ID'", ")", "title", "=", "post", ".", "get...
42.870968
0.001471
def iam(self): """ :rtype: IAMConnection """ if self.__iam is None: self.__iam = self.__aws_connect(iam, 'universal') return self.__iam
[ "def", "iam", "(", "self", ")", ":", "if", "self", ".", "__iam", "is", "None", ":", "self", ".", "__iam", "=", "self", ".", "__aws_connect", "(", "iam", ",", "'universal'", ")", "return", "self", ".", "__iam" ]
25.857143
0.010695
def get(self, path, default_value): """ Get value for config item into a string value; leading slash is optional and ignored. """ return lib.zconfig_get(self._as_parameter_, path, default_value)
[ "def", "get", "(", "self", ",", "path", ",", "default_value", ")", ":", "return", "lib", ".", "zconfig_get", "(", "self", ".", "_as_parameter_", ",", "path", ",", "default_value", ")" ]
36.833333
0.013274
def disconnect(self): """disconnect events""" self.canvas.mpl_disconnect(self._cidmotion) self.canvas.mpl_disconnect(self._ciddraw)
[ "def", "disconnect", "(", "self", ")", ":", "self", ".", "canvas", ".", "mpl_disconnect", "(", "self", ".", "_cidmotion", ")", "self", ".", "canvas", ".", "mpl_disconnect", "(", "self", ".", "_ciddraw", ")" ]
38
0.012903
def _get_runner(classpath, main, jvm_options, args, executor, cwd, distribution, create_synthetic_jar, synthetic_jar_dir): """Gets the java runner for execute_java and execute_java_async.""" executor = executor or SubprocessExecutor(distribution) safe_cp = classpath if create_syn...
[ "def", "_get_runner", "(", "classpath", ",", "main", ",", "jvm_options", ",", "args", ",", "executor", ",", "cwd", ",", "distribution", ",", "create_synthetic_jar", ",", "synthetic_jar_dir", ")", ":", "executor", "=", "executor", "or", "SubprocessExecutor", "(",...
42.384615
0.017762
def options(self, parser, env): """ Register command-line options. """ parser.add_option("--processes", action="store", default=env.get('NOSE_PROCESSES', 0), dest="multiprocess_workers", metavar="NUM", ...
[ "def", "options", "(", "self", ",", "parser", ",", "env", ")", ":", "parser", ".", "add_option", "(", "\"--processes\"", ",", "action", "=", "\"store\"", ",", "default", "=", "env", ".", "get", "(", "'NOSE_PROCESSES'", ",", "0", ")", ",", "dest", "=", ...
57.32
0.001373
def tgv_phantom(space, edge_smoothing=0.2): """Piecewise affine phantom. This phantom is taken from [Bre+2010] and includes both linearly varying regions and sharp discontinuities. It is designed to work well with Total Generalized Variation (TGV) type regularization. Parameters ---------- ...
[ "def", "tgv_phantom", "(", "space", ",", "edge_smoothing", "=", "0.2", ")", ":", "if", "space", ".", "ndim", "!=", "2", ":", "raise", "ValueError", "(", "'`space.ndim` must be 2, got {}'", "''", ".", "format", "(", "space", ".", "ndim", ")", ")", "y", ",...
32.142857
0.000359
def export_definitions_element(): """ Creates root element ('definitions') for exported BPMN XML file. :return: definitions XML element. """ root = eTree.Element(consts.Consts.definitions) root.set("xmlns", "http://www.omg.org/spec/BPMN/20100524/MODEL") root.set(...
[ "def", "export_definitions_element", "(", ")", ":", "root", "=", "eTree", ".", "Element", "(", "consts", ".", "Consts", ".", "definitions", ")", "root", ".", "set", "(", "\"xmlns\"", ",", "\"http://www.omg.org/spec/BPMN/20100524/MODEL\"", ")", "root", ".", "set"...
49
0.002225
def kms_decrypt(cfg, aws_config=None): """Decrypt KMS objects in configuration. Args: cfg (dict): configuration dictionary aws_config (dict): aws credentials dict of arguments passed into boto3 session example: aws_creds = {'aws_access_key_id': aws_access...
[ "def", "kms_decrypt", "(", "cfg", ",", "aws_config", "=", "None", ")", ":", "def", "decrypt", "(", "obj", ")", ":", "\"\"\"Decrypt the object.\n\n It is an inner function because we must first configure our KMS\n client. Then we call this recursively on the object.\n ...
36.742857
0.001893
def _calc_auc(self, model, params, idx): """ Helper function to calculate the area under the curve of a model Parameters ---------- model : callable Probably either ut.lorentzian or ut.gaussian, but any function will do, as long as its first parameter is ...
[ "def", "_calc_auc", "(", "self", ",", "model", ",", "params", ",", "idx", ")", ":", "# Here's what we are going to do: For each transient, we generate", "# the spectrum for two distinct sets of parameters: one is exactly as", "# fit to the data, the other is the same expect with amplitud...
41
0.001932
def vgsr_to_vhel(coordinate, vgsr, vsun=None): """ Convert a radial velocity in the Galactic standard of rest (GSR) to a barycentric radial velocity. Parameters ---------- coordinate : :class:`~astropy.coordinates.SkyCoord` An Astropy SkyCoord object or anything object that can be passe...
[ "def", "vgsr_to_vhel", "(", "coordinate", ",", "vgsr", ",", "vsun", "=", "None", ")", ":", "if", "vsun", "is", "None", ":", "vsun", "=", "coord", ".", "Galactocentric", ".", "galcen_v_sun", ".", "to_cartesian", "(", ")", ".", "xyz", "return", "vgsr", "...
31.928571
0.001086
def calc_regenerated(self, lastvotetime): ''' Uses math formula to calculate the amount of steem power that would have been regenerated given a certain datetime object ''' delta = datetime.utcnow() - datetime.strptime(lastvotetime,'%Y-%m-%dT%H:%M:%S') td = delta.days ...
[ "def", "calc_regenerated", "(", "self", ",", "lastvotetime", ")", ":", "delta", "=", "datetime", ".", "utcnow", "(", ")", "-", "datetime", ".", "strptime", "(", "lastvotetime", ",", "'%Y-%m-%dT%H:%M:%S'", ")", "td", "=", "delta", ".", "days", "ts", "=", ...
40.2
0.009732
def read_nonblocking(self, size=1, timeout=-1): '''This reads at most size characters from the child application. It includes a timeout. If the read does not complete within the timeout period then a TIMEOUT exception is raised. If the end of file is read then an EOF exception will be ra...
[ "def", "read_nonblocking", "(", "self", ",", "size", "=", "1", ",", "timeout", "=", "-", "1", ")", ":", "if", "self", ".", "closed", ":", "raise", "ValueError", "(", "'I/O operation on closed file.'", ")", "if", "timeout", "==", "-", "1", ":", "timeout",...
46.356164
0.000579
def visit_boolean_query(self, node): """Convert BooleanRule into AndOp or OrOp nodes.""" left = node.left.accept(self) right = node.right.accept(self) is_journal_keyword_op = isinstance(left, KeywordOp) and left.left == Keyword('journal') if is_journal_keyword_op: j...
[ "def", "visit_boolean_query", "(", "self", ",", "node", ")", ":", "left", "=", "node", ".", "left", ".", "accept", "(", "self", ")", "right", "=", "node", ".", "right", ".", "accept", "(", "self", ")", "is_journal_keyword_op", "=", "isinstance", "(", "...
41.642857
0.008389
def managed(name, data, **kwargs): ''' Manage the device configuration given the input data structured according to the YANG models. data YANG structured data. models A list of models to be used when generating the config. profiles: ``None`` Us...
[ "def", "managed", "(", "name", ",", "data", ",", "*", "*", "kwargs", ")", ":", "models", "=", "kwargs", ".", "get", "(", "'models'", ",", "None", ")", "if", "isinstance", "(", "models", ",", "tuple", ")", "and", "isinstance", "(", "models", "[", "0...
36.88
0.001267
def _script(name, source, saltenv='base', args=None, template=None, exec_driver=None, stdin=None, python_shell=True, output_loglevel='debug', ignore_retcode=False, use_vt=False, keep_env=N...
[ "def", "_script", "(", "name", ",", "source", ",", "saltenv", "=", "'base'", ",", "args", "=", "None", ",", "template", "=", "None", ",", "exec_driver", "=", "None", ",", "stdin", "=", "None", ",", "python_shell", "=", "True", ",", "output_loglevel", "...
29.26087
0.000479
def patch_custom_resource_definition(self, name, body, **kwargs): # noqa: E501 """patch_custom_resource_definition # noqa: E501 partially update the specified CustomResourceDefinition # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP r...
[ "def", "patch_custom_resource_definition", "(", "self", ",", "name", ",", "body", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async_req'", ")", ":", "retur...
60.75
0.00135
def setData(self, index, value, role=Qt.EditRole): """ Reimplements the :meth:`QAbstractItemModel.setData` method. :param index: Index. :type index: QModelIndex :param value: Value. :type value: QVariant :param role: Role. :type role: int :return:...
[ "def", "setData", "(", "self", ",", "index", ",", "value", ",", "role", "=", "Qt", ".", "EditRole", ")", ":", "if", "not", "index", ".", "isValid", "(", ")", ":", "return", "False", "node", "=", "self", ".", "get_node", "(", "index", ")", "if", "...
30.972222
0.001739
def sum_tbl(tbl, kfield, vfields): """ Aggregate a composite array and compute the totals on a given key. >>> dt = numpy.dtype([('name', (bytes, 10)), ('value', int)]) >>> tbl = numpy.array([('a', 1), ('a', 2), ('b', 3)], dt) >>> sum_tbl(tbl, 'name', ['value'])['value'] array([3, 3]) """ ...
[ "def", "sum_tbl", "(", "tbl", ",", "kfield", ",", "vfields", ")", ":", "pairs", "=", "[", "(", "n", ",", "tbl", ".", "dtype", "[", "n", "]", ")", "for", "n", "in", "[", "kfield", "]", "+", "vfields", "]", "dt", "=", "numpy", ".", "dtype", "("...
34.461538
0.001086
def download(tickers, start=None, end=None, actions=False, threads=False, group_by='column', auto_adjust=False, progress=True, period="max", interval="1d", prepost=False, **kwargs): """Download yahoo tickers :Parameters: tickers : str, list List of tickers to downlo...
[ "def", "download", "(", "tickers", ",", "start", "=", "None", ",", "end", "=", "None", ",", "actions", "=", "False", ",", "threads", "=", "False", ",", "group_by", "=", "'column'", ",", "auto_adjust", "=", "False", ",", "progress", "=", "True", ",", ...
36.730769
0.00034
def _getArgSpec(func): """ Normalize inspect.ArgSpec across python versions and convert mutable attributes to immutable types. :param Callable func: A function. :return: The function's ArgSpec. :rtype: ArgSpec """ spec = getArgsSpec(func) return ArgSpec( args=tuple(spec.args...
[ "def", "_getArgSpec", "(", "func", ")", ":", "spec", "=", "getArgsSpec", "(", "func", ")", "return", "ArgSpec", "(", "args", "=", "tuple", "(", "spec", ".", "args", ")", ",", "varargs", "=", "spec", ".", "varargs", ",", "varkw", "=", "spec", ".", "...
33.136364
0.001333
def dist_abs(self, src, tar, mode='lev', cost=(1, 1, 1, 1)): """Return the Levenshtein distance between two strings. Parameters ---------- src : str Source string for comparison tar : str Target string for comparison mode : str Specifi...
[ "def", "dist_abs", "(", "self", ",", "src", ",", "tar", ",", "mode", "=", "'lev'", ",", "cost", "=", "(", "1", ",", "1", ",", "1", ",", "1", ")", ")", ":", "ins_cost", ",", "del_cost", ",", "sub_cost", ",", "trans_cost", "=", "cost", "if", "src...
32.705882
0.000698
def _has_only_files(local_folder): """ Return whether a folder contains only files. This will be False if the folder contains any subdirectories. :param local_folder: full path to the local folder :type local_folder: string :returns: True if the folder contains only files :rtype: bool "...
[ "def", "_has_only_files", "(", "local_folder", ")", ":", "return", "not", "any", "(", "os", ".", "path", ".", "isdir", "(", "os", ".", "path", ".", "join", "(", "local_folder", ",", "entry", ")", ")", "for", "entry", "in", "os", ".", "listdir", "(", ...
36.416667
0.002232
def setup_lookup(apps, lookup_class=TemplateLookup): """ Registering template directories of apps to Lookup. Lookups will be set up as dictionary, app name as key and lookup for this app will be it's value. Each lookups is correspond to each template directories of apps._lookups. The directory shou...
[ "def", "setup_lookup", "(", "apps", ",", "lookup_class", "=", "TemplateLookup", ")", ":", "global", "_lookups", "_lookups", "=", "{", "}", "for", "app", "in", "apps", ":", "app_template_dir", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ...
43.222222
0.001258
def rmswidth(self, wavelengths=None, threshold=None): """Calculate the :ref:`bandpass RMS width <synphot-formula-rmswidth>`. Not to be confused with :func:`photbw`. Parameters ---------- wavelengths : array-like, `~astropy.units.quantity.Quantity`, or `None` Waveleng...
[ "def", "rmswidth", "(", "self", ",", "wavelengths", "=", "None", ",", "threshold", "=", "None", ")", ":", "x", "=", "self", ".", "_validate_wavelengths", "(", "wavelengths", ")", ".", "value", "y", "=", "self", "(", "x", ")", ".", "value", "if", "thr...
33
0.00109
def parse_processors(processor_definition): """ Returns a dictionary that contains the imported processors and kwargs. For example, passing in: processors = [ {'processor': 'thumbnails.processors.resize', 'width': 10, 'height': 10}, {'processor': 'thumbnails.processors.crop', 'width': 1...
[ "def", "parse_processors", "(", "processor_definition", ")", ":", "parsed_processors", "=", "[", "]", "for", "processor", "in", "processor_definition", ":", "processor_function", "=", "import_attribute", "(", "processor", "[", "'PATH'", "]", ")", "kwargs", "=", "d...
30.535714
0.002268
def substitution_scores_match(self, other): '''Check to make sure that the substitution scores agree. If one map has a null score and the other has a non-null score, we trust the other's score and vice versa.''' overlap = set(self.substitution_scores.keys()).intersection(set(other.substitution_scores.ke...
[ "def", "substitution_scores_match", "(", "self", ",", "other", ")", ":", "overlap", "=", "set", "(", "self", ".", "substitution_scores", ".", "keys", "(", ")", ")", ".", "intersection", "(", "set", "(", "other", ".", "substitution_scores", ".", "keys", "("...
71.875
0.012027
def _copy_context_into_mutable(context): """Copy a properly formatted context into a mutable data structure. """ def make_mutable(val): if isinstance(val, Mapping): return dict(val) else: return val if not isinstance(context, (str, Mapping)): try: ...
[ "def", "_copy_context_into_mutable", "(", "context", ")", ":", "def", "make_mutable", "(", "val", ")", ":", "if", "isinstance", "(", "val", ",", "Mapping", ")", ":", "return", "dict", "(", "val", ")", "else", ":", "return", "val", "if", "not", "isinstanc...
28.8
0.002242
def mini(args): """ %prog mini bamfile minibamfile Prepare mini-BAMs that contain only the STR loci. """ p = OptionParser(mini.__doc__) p.add_option("--pad", default=20000, type="int", help="Add padding to the STR reigons") p.add_option("--treds", default=None, ...
[ "def", "mini", "(", "args", ")", ":", "p", "=", "OptionParser", "(", "mini", ".", "__doc__", ")", "p", ".", "add_option", "(", "\"--pad\"", ",", "default", "=", "20000", ",", "type", "=", "\"int\"", ",", "help", "=", "\"Add padding to the STR reigons\"", ...
30.708333
0.001316
def P_stagnation(P, T, Tst, k): r'''Calculates stagnation flow pressure `Pst` for a fluid with the given isentropic coefficient and specified stagnation temperature and normal temperature. Normally used with converging/diverging nozzles. .. math:: \frac{P_0}{P}=\left(\frac{T_0}{T}\right)^{\frac...
[ "def", "P_stagnation", "(", "P", ",", "T", ",", "Tst", ",", "k", ")", ":", "return", "P", "*", "(", "Tst", "/", "T", ")", "**", "(", "k", "/", "(", "k", "-", "1.0", ")", ")" ]
26.219512
0.000897
def to_inputs(self, indices=None): """Converts a Transaction's outputs to spendable inputs. Note: Takes the Transaction's outputs and derives inputs from that can then be passed into `Transaction.transfer` as `inputs`. A list of intege...
[ "def", "to_inputs", "(", "self", ",", "indices", "=", "None", ")", ":", "# NOTE: If no indices are passed, we just assume to take all outputs", "# as inputs.", "indices", "=", "indices", "or", "range", "(", "len", "(", "self", ".", "outputs", ")", ")", "return...
39.689655
0.001696
def resolve(self, key, keylist): """Hook to resolve ambiguities in selected keys""" raise AmbiguousKeyError("Ambiguous key "+ repr(key) + ", could be any of " + str(sorted(keylist)))
[ "def", "resolve", "(", "self", ",", "key", ",", "keylist", ")", ":", "raise", "AmbiguousKeyError", "(", "\"Ambiguous key \"", "+", "repr", "(", "key", ")", "+", "\", could be any of \"", "+", "str", "(", "sorted", "(", "keylist", ")", ")", ")" ]
52.75
0.018692
def publishing_column(self, obj): """ Render publishing-related status icons and view links for display in the admin. """ # TODO Hack to convert polymorphic objects to real instances if hasattr(obj, 'get_real_instance'): obj = obj.get_real_instance() ...
[ "def", "publishing_column", "(", "self", ",", "obj", ")", ":", "# TODO Hack to convert polymorphic objects to real instances", "if", "hasattr", "(", "obj", ",", "'get_real_instance'", ")", ":", "obj", "=", "obj", ".", "get_real_instance", "(", ")", "try", ":", "ob...
36.818182
0.001604
def change_keyboard_mapping(self, first_keycode, keysyms, onerror = None): """Modify the keyboard mapping, starting with first_keycode. keysyms is a list of tuples of keysyms. keysyms[n][i] will be assigned to keycode first_keycode+n at index i.""" request.ChangeKeyboardMapping(display =...
[ "def", "change_keyboard_mapping", "(", "self", ",", "first_keycode", ",", "keysyms", ",", "onerror", "=", "None", ")", ":", "request", ".", "ChangeKeyboardMapping", "(", "display", "=", "self", ".", "display", ",", "onerror", "=", "onerror", ",", "first_keycod...
63.75
0.023211
def is_available(workshift_profile, shift): """ Check whether a specified user is able to do a specified workshift. Parameters: workshift_profile is the workshift profile for a user shift is a weekly recurring workshift Returns: True if the user has enough free time between the s...
[ "def", "is_available", "(", "workshift_profile", ",", "shift", ")", ":", "if", "shift", ".", "week_long", ":", "return", "True", "start_time", "=", "(", "shift", ".", "start_time", "if", "shift", ".", "start_time", "is", "not", "None", "else", "time", "(",...
31.383562
0.000423
def media(self, uri): """Play a media file.""" try: local_path, _ = urllib.request.urlretrieve(uri) metadata = mutagen.File(local_path, easy=True) if metadata.tags: self._tags = metadata.tags title = self._tags.get(TAG_TITLE, []) ...
[ "def", "media", "(", "self", ",", "uri", ")", ":", "try", ":", "local_path", ",", "_", "=", "urllib", ".", "request", ".", "urlretrieve", "(", "uri", ")", "metadata", "=", "mutagen", ".", "File", "(", "local_path", ",", "easy", "=", "True", ")", "i...
45.884615
0.001642
def do_fullscreen(self, line): """ Make the current window fullscreen """ self.bot.canvas.sink.trigger_fullscreen_action(True) print(self.response_prompt, file=self.stdout)
[ "def", "do_fullscreen", "(", "self", ",", "line", ")", ":", "self", ".", "bot", ".", "canvas", ".", "sink", ".", "trigger_fullscreen_action", "(", "True", ")", "print", "(", "self", ".", "response_prompt", ",", "file", "=", "self", ".", "stdout", ")" ]
34.5
0.009434
def generate_tab_names(name): """ Return the names to lextab and yacctab modules for the given module name. Typical usage should be like so:: >>> lextab, yacctab = generate_tab_names(__name__) """ package_name, module_name = name.rsplit('.', 1) version = ply_dist.version.replace( ...
[ "def", "generate_tab_names", "(", "name", ")", ":", "package_name", ",", "module_name", "=", "name", ".", "rsplit", "(", "'.'", ",", "1", ")", "version", "=", "ply_dist", ".", "version", ".", "replace", "(", "'.'", ",", "'_'", ")", "if", "ply_dist", "i...
33.3125
0.001825
def _nanpercentile_1d(values, mask, q, na_value, interpolation): """ Wraper for np.percentile that skips missing values, specialized to 1-dimensional case. Parameters ---------- values : array over which to find quantiles mask : ndarray[bool] locations in values that should be consi...
[ "def", "_nanpercentile_1d", "(", "values", ",", "mask", ",", "q", ",", "na_value", ",", "interpolation", ")", ":", "# mask is Union[ExtensionArray, ndarray]", "values", "=", "values", "[", "~", "mask", "]", "if", "len", "(", "values", ")", "==", "0", ":", ...
28.4
0.001135
def _refresh_grpc(operations_stub, operation_name): """Refresh an operation using a gRPC client. Args: operations_stub (google.longrunning.operations_pb2.OperationsStub): The gRPC operations stub. operation_name (str): The name of the operation. Returns: google.longrunn...
[ "def", "_refresh_grpc", "(", "operations_stub", ",", "operation_name", ")", ":", "request_pb", "=", "operations_pb2", ".", "GetOperationRequest", "(", "name", "=", "operation_name", ")", "return", "operations_stub", ".", "GetOperation", "(", "request_pb", ")" ]
37.307692
0.002012
def log (self, msg, prefix=None): """Logs a message with an optional prefix.""" if prefix: if not prefix.strip().endswith(':'): prefix += ': ' msg = prefix + msg self.messages.append(msg)
[ "def", "log", "(", "self", ",", "msg", ",", "prefix", "=", "None", ")", ":", "if", "prefix", ":", "if", "not", "prefix", ".", "strip", "(", ")", ".", "endswith", "(", "':'", ")", ":", "prefix", "+=", "': '", "msg", "=", "prefix", "+", "msg", "s...
30.428571
0.018265
def propose_value(self, value): ''' Sets the proposal value for this node iff this node is not already aware of a previous proposal value. If the node additionally believes itself to be the current leader, an Accept message will be returned ''' if self.proposed_value is N...
[ "def", "propose_value", "(", "self", ",", "value", ")", ":", "if", "self", ".", "proposed_value", "is", "None", ":", "self", ".", "proposed_value", "=", "value", "if", "self", ".", "leader", ":", "self", ".", "current_accept_msg", "=", "Accept", "(", "se...
43.416667
0.009398
def process_event(self, module_name, event, default_event=False): """ Process the event for the named module. Events may have been declared in i3status.conf, modules may have on_click() functions. There is a default middle click event etc. """ # get the module that the e...
[ "def", "process_event", "(", "self", ",", "module_name", ",", "event", ",", "default_event", "=", "False", ")", ":", "# get the module that the event is for", "module_info", "=", "self", ".", "output_modules", ".", "get", "(", "module_name", ")", "# if module is a p...
43.529412
0.001983
def grant_db_access(conn, schema, table, role): r"""Gives access to database users/ groups Parameters ---------- conn : sqlalchemy connection object A valid connection to a database schema : str The database schema table : str The database table role : str da...
[ "def", "grant_db_access", "(", "conn", ",", "schema", ",", "table", ",", "role", ")", ":", "grant_str", "=", "\"\"\"GRANT ALL ON TABLE {schema}.{table}\n TO {role} WITH GRANT OPTION;\"\"\"", ".", "format", "(", "schema", "=", "schema", ",", "table", "=", "table", ...
27.8
0.001739
def congestion(self): """Retrieves the congestion information of the incident/incidents from the output response Returns: congestion(namedtuple): List of named tuples of congestion info of the incident/incidents """ resource_list = self.traffic_incident()...
[ "def", "congestion", "(", "self", ")", ":", "resource_list", "=", "self", ".", "traffic_incident", "(", ")", "congestion", "=", "namedtuple", "(", "'congestion'", ",", "'congestion'", ")", "if", "len", "(", "resource_list", ")", "==", "1", "and", "resource_l...
38.5
0.002304
def perm(lst, func): ''' Produce permutations of `lst`, where permutations are mutated by `func`. Used for flipping constraints. highly possible that returned constraints can be unsat this does it blindly, without any attention to the constraints themselves Considering lst as a list of constraints, e.g...
[ "def", "perm", "(", "lst", ",", "func", ")", ":", "for", "i", "in", "range", "(", "1", ",", "2", "**", "len", "(", "lst", ")", ")", ":", "yield", "[", "func", "(", "item", ")", "if", "(", "1", "<<", "j", ")", "&", "i", "else", "item", "fo...
40.62963
0.008014
def get_new_driver(self, browser=None, headless=None, servername=None, port=None, proxy=None, agent=None, switch_to=True, cap_file=None, disable_csp=None): """ This method spins up an extra browser for tests that require more than one. The first browser ...
[ "def", "get_new_driver", "(", "self", ",", "browser", "=", "None", ",", "headless", "=", "None", ",", "servername", "=", "None", ",", "port", "=", "None", ",", "proxy", "=", "None", ",", "agent", "=", "None", ",", "switch_to", "=", "True", ",", "cap_...
51.708738
0.000737
def get(self, name): """Provides a method to retrieve all routemap configuration related to the name attribute. Args: name (string): The name of the routemap. Returns: None if the specified routemap does not exists. If the routermap exists a dictiona...
[ "def", "get", "(", "self", ",", "name", ")", ":", "if", "not", "self", ".", "get_block", "(", "r'route-map\\s%s\\s\\w+\\s\\d+'", "%", "name", ")", ":", "return", "None", "return", "self", ".", "_parse_entries", "(", "name", ")" ]
40.139535
0.001131
def answered_by(self, rec): """Returns true if the question is answered by the record""" return self.clazz == rec.clazz and \ (self.type == rec.type or self.type == _TYPE_ANY) and \ self.name == rec.name
[ "def", "answered_by", "(", "self", ",", "rec", ")", ":", "return", "self", ".", "clazz", "==", "rec", ".", "clazz", "and", "(", "self", ".", "type", "==", "rec", ".", "type", "or", "self", ".", "type", "==", "_TYPE_ANY", ")", "and", "self", ".", ...
49.4
0.015936
def get_system_config_dirs(app_name, app_author, force_xdg=True): r"""Returns a list of system-wide config folders for the application. For an example application called ``"My App"`` by ``"Acme"``, something like the following folders could be returned: macOS (non-XDG): ``['/Library/Application ...
[ "def", "get_system_config_dirs", "(", "app_name", ",", "app_author", ",", "force_xdg", "=", "True", ")", ":", "if", "WIN", ":", "folder", "=", "os", ".", "environ", ".", "get", "(", "'PROGRAMDATA'", ")", "return", "[", "os", ".", "path", ".", "join", "...
42
0.000727
def get_site(self, plot_voronoi_sites=False): """Return primaty (top, bridge, hollow, 4fold) and secondary (chemical elements in close environment) site designation""" if self.dissociated: return 'dissociated', '' if self.is_desorbed(): return 'desorbed', '' ...
[ "def", "get_site", "(", "self", ",", "plot_voronoi_sites", "=", "False", ")", ":", "if", "self", ".", "dissociated", ":", "return", "'dissociated'", ",", "''", "if", "self", ".", "is_desorbed", "(", ")", ":", "return", "'desorbed'", ",", "''", "if", "sel...
30.366667
0.001063
def download_script(script_file_name): '''Send a script directly from the scripts directory''' return "Sorry! Temporarily disabled." if script_file_name[:-3] in registered_modules: loaded_module = registered_modules[script_file_name[:-3]] package_path = os.sep.join(loaded_module.__package__....
[ "def", "download_script", "(", "script_file_name", ")", ":", "return", "\"Sorry! Temporarily disabled.\"", "if", "script_file_name", "[", ":", "-", "3", "]", "in", "registered_modules", ":", "loaded_module", "=", "registered_modules", "[", "script_file_name", "[", ":"...
49.666667
0.001647
def parse_env_var(s): """Parse an environment variable string Returns a key-value tuple Apply the same logic as `docker run -e`: "If the operator names an environment variable without specifying a value, then the current value of the named variable is propagated into the container's environmen...
[ "def", "parse_env_var", "(", "s", ")", ":", "parts", "=", "s", ".", "split", "(", "'='", ",", "1", ")", "if", "len", "(", "parts", ")", "==", "2", ":", "k", ",", "v", "=", "parts", "return", "(", "k", ",", "v", ")", "k", "=", "parts", "[", ...
27
0.002105
def list_trilegal_filtersystems(): ''' This just lists all the filter systems available for TRILEGAL. ''' print('%-40s %s' % ('FILTER SYSTEM NAME','DESCRIPTION')) print('%-40s %s' % ('------------------','-----------')) for key in sorted(TRILEGAL_FILTER_SYSTEMS.keys()): print('%-40s %s...
[ "def", "list_trilegal_filtersystems", "(", ")", ":", "print", "(", "'%-40s %s'", "%", "(", "'FILTER SYSTEM NAME'", ",", "'DESCRIPTION'", ")", ")", "print", "(", "'%-40s %s'", "%", "(", "'------------------'", ",", "'-----------'", ")", ")", "for", "key", "in", ...
35.9
0.008152
def project_dev_requirements(): """ List requirements for peltak commands configured for the project. This list is dynamic and depends on the commands you have configured in your project's pelconf.yaml. This will be the combined list of packages needed to be installed in order for all the configured co...
[ "def", "project_dev_requirements", "(", ")", ":", "from", "peltak", ".", "core", "import", "conf", "from", "peltak", ".", "core", "import", "shell", "for", "dep", "in", "sorted", "(", "conf", ".", "requirements", ")", ":", "shell", ".", "cprint", "(", "d...
39
0.002088
def get_cpu_usage(user=None, ignore_self=True): """ Returns the total CPU usage for all available cores. :param user: If given, returns only the total CPU usage of all processes for the given user. :param ignore_self: If ``True`` the process that runs this script will be ignored. """ ...
[ "def", "get_cpu_usage", "(", "user", "=", "None", ",", "ignore_self", "=", "True", ")", ":", "pid", "=", "os", ".", "getpid", "(", ")", "cmd", "=", "\"ps aux\"", "output", "=", "getoutput", "(", "cmd", ")", "total", "=", "0", "largest_process", "=", ...
32.666667
0.001101
def put(self, taskid, priority=0, exetime=0): """ Put a task into task queue when use heap sort, if we put tasks(with the same priority and exetime=0) into queue, the queue is not a strict FIFO queue, but more like a FILO stack. It is very possible that when there are co...
[ "def", "put", "(", "self", ",", "taskid", ",", "priority", "=", "0", ",", "exetime", "=", "0", ")", ":", "now", "=", "time", ".", "time", "(", ")", "task", "=", "InQueueTask", "(", "taskid", ",", "priority", ",", "exetime", ")", "self", ".", "mut...
43.277778
0.010672
def data_transforms_cifar10(args): """ data_transforms for cifar10 dataset """ cifar_mean = [0.49139968, 0.48215827, 0.44653124] cifar_std = [0.24703233, 0.24348505, 0.26158768] train_transform = transforms.Compose( [ transforms.RandomCrop(32, padding=4), transforms...
[ "def", "data_transforms_cifar10", "(", "args", ")", ":", "cifar_mean", "=", "[", "0.49139968", ",", "0.48215827", ",", "0.44653124", "]", "cifar_std", "=", "[", "0.24703233", ",", "0.24348505", ",", "0.26158768", "]", "train_transform", "=", "transforms", ".", ...
31.409091
0.001404
def get_isolated_cpus(): """Get the list of isolated CPUs. Return a sorted list of CPU identifiers, or return None if no CPU is isolated. """ # The cpu/isolated sysfs was added in Linux 4.2 # (commit 59f30abe94bff50636c8cad45207a01fdcb2ee49) path = sysfs_path('devices/system/cpu/isolated') ...
[ "def", "get_isolated_cpus", "(", ")", ":", "# The cpu/isolated sysfs was added in Linux 4.2", "# (commit 59f30abe94bff50636c8cad45207a01fdcb2ee49)", "path", "=", "sysfs_path", "(", "'devices/system/cpu/isolated'", ")", "isolated", "=", "read_first_line", "(", "path", ")", "if",...
30.333333
0.001522
def absent(name, export=False, force=False): ''' ensure storage pool is absent on the system name : string name of storage pool export : boolean export instread of destroy the zpool if present force : boolean force destroy or export ''' ret = {'name': name, ...
[ "def", "absent", "(", "name", ",", "export", "=", "False", ",", "force", "=", "False", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'changes'", ":", "{", "}", ",", "'result'", ":", "None", ",", "'comment'", ":", "''", "}", "# log configu...
30.372549
0.001251
def readPhenoFile(pfile,idx=None): """" reading in phenotype file pfile root of the file containing the phenotypes as NxP matrix (N=number of samples, P=number of traits) """ usecols = None if idx!=None: """ different traits are comma-seperated """ usecols = [int(...
[ "def", "readPhenoFile", "(", "pfile", ",", "idx", "=", "None", ")", ":", "usecols", "=", "None", "if", "idx", "!=", "None", ":", "\"\"\" different traits are comma-seperated \"\"\"", "usecols", "=", "[", "int", "(", "x", ")", "for", "x", "in", "idx", ".", ...
30.25
0.019231
def __RetrieveContent(host, port, adapter, version, path, keyFile, certFile, thumbprint, sslContext, connectionPoolTimeout=CONNECTION_POOL_IDLE_TIMEOUT_SEC): """ Retrieve service instance for connection. @param host: Which host to connect to. @type host: string @param port: Port ...
[ "def", "__RetrieveContent", "(", "host", ",", "port", ",", "adapter", ",", "version", ",", "path", ",", "keyFile", ",", "certFile", ",", "thumbprint", ",", "sslContext", ",", "connectionPoolTimeout", "=", "CONNECTION_POOL_IDLE_TIMEOUT_SEC", ")", ":", "# XXX remove...
38.259259
0.013686
def viewable_width(self): """ The available combined character width when all padding is removed. """ return sum(self.widths) + sum(x['padding'] for x in self.colspec)
[ "def", "viewable_width", "(", "self", ")", ":", "return", "sum", "(", "self", ".", "widths", ")", "+", "sum", "(", "x", "[", "'padding'", "]", "for", "x", "in", "self", ".", "colspec", ")" ]
47
0.010471
def vectorize(e, tolerance=0.1): """ vectorizes the pdf object's bounding box min_width is the width under which we consider it a line instead of a big rectangle """ tolerance = max(tolerance, e.linewidth) is_high = e.height > tolerance is_wide = e.width > tolerance # if skewed towar...
[ "def", "vectorize", "(", "e", ",", "tolerance", "=", "0.1", ")", ":", "tolerance", "=", "max", "(", "tolerance", ",", "e", ".", "linewidth", ")", "is_high", "=", "e", ".", "height", ">", "tolerance", "is_wide", "=", "e", ".", "width", ">", "tolerance...
31.5
0.002203
def validate_df(df, dm, con=None): """ Take in a DataFrame and corresponding data model. Run all validations for that DataFrame. Output is the original DataFrame with some new columns that contain the validation output. Validation columns start with: presence_pass_ (checking that req'd colum...
[ "def", "validate_df", "(", "df", ",", "dm", ",", "con", "=", "None", ")", ":", "# check column validity", "required_one", "=", "{", "}", "# keep track of req'd one in group validations here", "cols", "=", "df", ".", "columns", "invalid_cols", "=", "[", "col", "f...
48.25
0.002257
def get_class(class_key): """Form a music service data structure class from the class key Args: class_key (str): A concatenation of the base class (e.g. MediaMetadata) and the class name Returns: class: Subclass of MusicServiceItem """ if class_key not in CLASSES: ...
[ "def", "get_class", "(", "class_key", ")", ":", "if", "class_key", "not", "in", "CLASSES", ":", "for", "basecls", "in", "(", "MediaMetadata", ",", "MediaCollection", ")", ":", "if", "class_key", ".", "startswith", "(", "basecls", ".", "__name__", ")", ":",...
40.65
0.001202
def position(self, chromosome, position, exact=False): """ Shortcut to do a single position filter on genomic datasets. """ return self._clone( filters=[GenomicFilter(chromosome, position, exact=exact)])
[ "def", "position", "(", "self", ",", "chromosome", ",", "position", ",", "exact", "=", "False", ")", ":", "return", "self", ".", "_clone", "(", "filters", "=", "[", "GenomicFilter", "(", "chromosome", ",", "position", ",", "exact", "=", "exact", ")", "...
40.333333
0.008097
def _get_dpi(ctm_shorthand, image_size): """Given the transformation matrix and image size, find the image DPI. PDFs do not include image resolution information within image data. Instead, the PDF page content stream describes the location where the image will be rasterized, and the effective resolutio...
[ "def", "_get_dpi", "(", "ctm_shorthand", ",", "image_size", ")", ":", "a", ",", "b", ",", "c", ",", "d", ",", "_", ",", "_", "=", "ctm_shorthand", "# Calculate the width and height of the image in PDF units", "image_drawn_width", "=", "hypot", "(", "a", ",", "...
42.145161
0.000374
def lstm_asr_v1(): """Basic LSTM Params.""" hparams = lstm_bahdanau_attention() hparams.num_hidden_layers = 2 hparams.hidden_size = 256 hparams.batch_size = 36 hparams.max_input_seq_length = 600000 hparams.max_target_seq_length = 350 hparams.max_length = hparams.max_input_seq_length hparams.min_length...
[ "def", "lstm_asr_v1", "(", ")", ":", "hparams", "=", "lstm_bahdanau_attention", "(", ")", "hparams", ".", "num_hidden_layers", "=", "2", "hparams", ".", "hidden_size", "=", "256", "hparams", ".", "batch_size", "=", "36", "hparams", ".", "max_input_seq_length", ...
33.333333
0.029197