text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def get_files_to_check(self): """Generate files and error codes to check on each one. Walk dir trees under `self._arguments` and yield file names that `match` under each directory that `match_dir`. The method locates the configuration for each file name and yields a tuple of (fi...
[ "def", "get_files_to_check", "(", "self", ")", ":", "def", "_get_matches", "(", "conf", ")", ":", "\"\"\"Return the `match` and `match_dir` functions for `config`.\"\"\"", "match_func", "=", "re", "(", "conf", ".", "match", "+", "'$'", ")", ".", "match", "match_dir_...
44.590909
0.000998
def load_from_xml(self, path): """Load all objects from XML file and return as dict. The dict returned will have keys named the same as the JSSObject classes contained, and the values will be JSSObjectLists of all full objects of that class (for example, the equivalent of my_jss...
[ "def", "load_from_xml", "(", "self", ",", "path", ")", ":", "with", "open", "(", "os", ".", "path", ".", "expanduser", "(", "path", ")", ",", "\"r\"", ")", "as", "ifile", ":", "et", "=", "ElementTree", ".", "parse", "(", "ifile", ")", "root", "=", ...
36.230769
0.002068
def on_size(self, event): '''handle window size changes''' state = self.state size = event.GetSize() state.width = size.width state.height = size.height self.redraw_map()
[ "def", "on_size", "(", "self", ",", "event", ")", ":", "state", "=", "self", ".", "state", "size", "=", "event", ".", "GetSize", "(", ")", "state", ".", "width", "=", "size", ".", "width", "state", ".", "height", "=", "size", ".", "height", "self",...
30.285714
0.009174
def custom_decode(encoding): """Overrides encoding when charset declaration or charset determination is a subset of a larger charset. Created because of issues with Chinese websites""" encoding = encoding.lower() alternates = { 'big5': 'big5hkscs', 'gb2312': 'gb18030', ...
[ "def", "custom_decode", "(", "encoding", ")", ":", "encoding", "=", "encoding", ".", "lower", "(", ")", "alternates", "=", "{", "'big5'", ":", "'big5hkscs'", ",", "'gb2312'", ":", "'gb18030'", ",", "'ascii'", ":", "'utf-8'", ",", "'MacCyrillic'", ":", "'cp...
30.933333
0.002092
def from_mult_iters(cls, name=None, idx=None, **kwargs): """Load values from multiple iters Parameters ---------- name : string, default None Name of the data set. If None (default), the name will be set to ``'table'``. idx: string, default None ...
[ "def", "from_mult_iters", "(", "cls", ",", "name", "=", "None", ",", "idx", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "not", "name", ":", "name", "=", "'table'", "lengths", "=", "[", "len", "(", "v", ")", "for", "v", "in", "kwargs", ...
32.217391
0.00131
def process_json_str(json_str, citation=None): """Return a ReachProcessor by processing the given REACH json string. The output from the REACH parser is in this json format. For more information on the format, see: https://github.com/clulab/reach Parameters ---------- json_str : str Th...
[ "def", "process_json_str", "(", "json_str", ",", "citation", "=", "None", ")", ":", "if", "not", "isinstance", "(", "json_str", ",", "basestring", ")", ":", "raise", "TypeError", "(", "'{} is {} instead of {}'", ".", "format", "(", "json_str", ",", "json_str",...
37.088889
0.000584
def get_log(name=None): """Return a console logger. Output may be sent to the logger using the `debug`, `info`, `warning`, `error` and `critical` methods. Parameters ---------- name : str Name of the log. References ---------- .. [1] Logging facility for Pytho...
[ "def", "get_log", "(", "name", "=", "None", ")", ":", "if", "name", "is", "None", ":", "name", "=", "'oct2py'", "else", ":", "name", "=", "'oct2py.'", "+", "name", "log", "=", "logging", ".", "getLogger", "(", "name", ")", "log", ".", "setLevel", "...
21.64
0.00177
def validate_price(price): """ validation checks for price argument """ if isinstance(price, str): try: price = int(price) except ValueError: # fallback if convert to int failed price = float(price) if not isinstance(price, (int, float)): raise TypeError('Price should be a number: ' + repr(price)) retur...
[ "def", "validate_price", "(", "price", ")", ":", "if", "isinstance", "(", "price", ",", "str", ")", ":", "try", ":", "price", "=", "int", "(", "price", ")", "except", "ValueError", ":", "# fallback if convert to int failed", "price", "=", "float", "(", "pr...
31.8
0.033639
def downside_risk(returns, required_return=0, period=DAILY): """ Determines the downside deviation below a threshold Parameters ---------- returns : pd.Series or pd.DataFrame Daily returns of the strategy, noncumulative. - See full explanation in :func:`~pyfolio.timeseries.cum_retur...
[ "def", "downside_risk", "(", "returns", ",", "required_return", "=", "0", ",", "period", "=", "DAILY", ")", ":", "return", "ep", ".", "downside_risk", "(", "returns", ",", "required_return", "=", "required_return", ",", "period", "=", "period", ")" ]
30.142857
0.001148
def get_description(self, obj): """Set search entry description for object""" search_description = self.get_model_config_value(obj, 'search_description') if not search_description: return super().get_description(obj) return search_description.format(**obj.__dict__)
[ "def", "get_description", "(", "self", ",", "obj", ")", ":", "search_description", "=", "self", ".", "get_model_config_value", "(", "obj", ",", "'search_description'", ")", "if", "not", "search_description", ":", "return", "super", "(", ")", ".", "get_descriptio...
38
0.009646
def make_secure_stub(credentials, user_agent, stub_class, host, extra_options=()): """Makes a secure stub for an RPC service. Uses / depends on gRPC. :type credentials: :class:`google.auth.credentials.Credentials` :param credentials: The OAuth2 Credentials to use for creating a...
[ "def", "make_secure_stub", "(", "credentials", ",", "user_agent", ",", "stub_class", ",", "host", ",", "extra_options", "=", "(", ")", ")", ":", "channel", "=", "make_secure_channel", "(", "credentials", ",", "user_agent", ",", "host", ",", "extra_options", "=...
33.413793
0.002006
def loadByteArray(self, context, page, resultLen, resultData, returnError): """please override""" returnError.contents.value = self.IllegalStateError raise NotImplementedError("You must override this method.")
[ "def", "loadByteArray", "(", "self", ",", "context", ",", "page", ",", "resultLen", ",", "resultData", ",", "returnError", ")", ":", "returnError", ".", "contents", ".", "value", "=", "self", ".", "IllegalStateError", "raise", "NotImplementedError", "(", "\"Yo...
57.5
0.008584
def get_vertex_colors(self, indexed=None): """Get vertex colors Parameters ---------- indexed : str | None If None, return an array (Nv, 4) of vertex colors. If indexed=='faces', then instead return an indexed array (Nf, 3, 4). Returns ...
[ "def", "get_vertex_colors", "(", "self", ",", "indexed", "=", "None", ")", ":", "if", "indexed", "is", "None", ":", "return", "self", ".", "_vertex_colors", "elif", "indexed", "==", "'faces'", ":", "if", "self", ".", "_vertex_colors_indexed_by_faces", "is", ...
33.208333
0.002439
def download_file_insecure(url, target): ''' Use Python to download the file, even though it cannot authenticate the connection. ''' try: from urllib.request import urlopen except ImportError: from urllib2 import urlopen src = dst = None try: src = urlopen(url) ...
[ "def", "download_file_insecure", "(", "url", ",", "target", ")", ":", "try", ":", "from", "urllib", ".", "request", "import", "urlopen", "except", "ImportError", ":", "from", "urllib2", "import", "urlopen", "src", "=", "dst", "=", "None", "try", ":", "src"...
26.681818
0.001645
def _is_integer_like_by_dtype(dt): """Helper returning True if dtype.is_integer or is `bool`.""" if not _is_known_dtype(dt): raise TypeError("Unrecognized dtype: {}".format(dt.name)) return dt.is_integer or dt.base_dtype == tf.bool
[ "def", "_is_integer_like_by_dtype", "(", "dt", ")", ":", "if", "not", "_is_known_dtype", "(", "dt", ")", ":", "raise", "TypeError", "(", "\"Unrecognized dtype: {}\"", ".", "format", "(", "dt", ".", "name", ")", ")", "return", "dt", ".", "is_integer", "or", ...
47.4
0.016598
def get_metadata_path(name): """Get reference metadata file path.""" return pkg_resources.resource_filename('voobly', os.path.join(METADATA_PATH, '{}.json'.format(name)))
[ "def", "get_metadata_path", "(", "name", ")", ":", "return", "pkg_resources", ".", "resource_filename", "(", "'voobly'", ",", "os", ".", "path", ".", "join", "(", "METADATA_PATH", ",", "'{}.json'", ".", "format", "(", "name", ")", ")", ")" ]
58.666667
0.011236
def calc_PSD(Signal, SampleFreq, NPerSegment=1000000, window="hann"): """ Extracts the pulse spectral density (PSD) from the data. Parameters ---------- Signal : array-like Array containing the signal to have the PSD calculated for SampleFreq : float Sample frequency of the sign...
[ "def", "calc_PSD", "(", "Signal", ",", "SampleFreq", ",", "NPerSegment", "=", "1000000", ",", "window", "=", "\"hann\"", ")", ":", "freqs", ",", "PSD", "=", "scipy", ".", "signal", ".", "welch", "(", "Signal", ",", "SampleFreq", ",", "window", "=", "wi...
34.5
0.000829
def add_layers(self, *layers): """ Append given layers to this onion :param layers: layer to add :return: None """ for layer in layers: if layer.name() in self.__layers.keys(): raise ValueError('Layer "%s" already exists' % layer.name()) self.__layers[layer.name()] = layer
[ "def", "add_layers", "(", "self", ",", "*", "layers", ")", ":", "for", "layer", "in", "layers", ":", "if", "layer", ".", "name", "(", ")", "in", "self", ".", "__layers", ".", "keys", "(", ")", ":", "raise", "ValueError", "(", "'Layer \"%s\" already exi...
28.5
0.034014
def _reset_i(self, i): """ reset i-th progress information """ self.count[i].value=0 log.debug("reset counter %s", i) self.lock[i].acquire() for x in range(self.q[i].qsize()): self.q[i].get() self.lock[i].release() self.sta...
[ "def", "_reset_i", "(", "self", ",", "i", ")", ":", "self", ".", "count", "[", "i", "]", ".", "value", "=", "0", "log", ".", "debug", "(", "\"reset counter %s\"", ",", "i", ")", "self", ".", "lock", "[", "i", "]", ".", "acquire", "(", ")", "for...
28.25
0.011429
def bb(self,*args,**kwargs): """ NAME: bb PURPOSE: return Galactic latitude INPUT: t - (optional) time at which to get bb obs=[X,Y,Z] - (optional) position of observer (in kpc) (default=Object-wide default) ...
[ "def", "bb", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "_check_roSet", "(", "self", ",", "kwargs", ",", "'bb'", ")", "lbd", "=", "self", ".", "_lbd", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "lbd", "[", ...
34.863636
0.015228
def get(self, request, bot_id, id, format=None): """ Get Messenger chat state by id --- serializer: MessengerChatStateSerializer responseMessages: - code: 401 message: Not authenticated """ return super(MessengerChatStateDetail, s...
[ "def", "get", "(", "self", ",", "request", ",", "bot_id", ",", "id", ",", "format", "=", "None", ")", ":", "return", "super", "(", "MessengerChatStateDetail", ",", "self", ")", ".", "get", "(", "request", ",", "bot_id", ",", "id", ",", "format", ")" ...
34.8
0.011204
def initStats(self, extras=None): """Query and parse Web Server Status Page. @param extras: Include extra metrics, which can be computationally more expensive. """ url = "%s://%s:%d/%s" % (self._proto, self._host, self._port, self._monpath) ...
[ "def", "initStats", "(", "self", ",", "extras", "=", "None", ")", ":", "url", "=", "\"%s://%s:%d/%s\"", "%", "(", "self", ".", "_proto", ",", "self", ".", "_host", ",", "self", ".", "_port", ",", "self", ".", "_monpath", ")", "response", "=", "util",...
41.25
0.013834
def handle_lease(queue_name): """Leases a task from a queue.""" owner = request.form.get('owner', request.remote_addr, type=str) try: task_list = work_queue.lease( queue_name, owner, request.form.get('count', 1, type=int), request.form.get('timeout', 6...
[ "def", "handle_lease", "(", "queue_name", ")", ":", "owner", "=", "request", ".", "form", ".", "get", "(", "'owner'", ",", "request", ".", "remote_addr", ",", "type", "=", "str", ")", "try", ":", "task_list", "=", "work_queue", ".", "lease", "(", "queu...
33.75
0.001441
def align_transcriptome(fastq_file, pair_file, ref_file, data): """ bwa mem with settings for aligning to the transcriptome for eXpress/RSEM/etc """ work_bam = dd.get_work_bam(data) base, ext = os.path.splitext(work_bam) out_file = base + ".transcriptome" + ext if utils.file_exists(out_file)...
[ "def", "align_transcriptome", "(", "fastq_file", ",", "pair_file", ",", "ref_file", ",", "data", ")", ":", "work_bam", "=", "dd", ".", "get_work_bam", "(", "data", ")", "base", ",", "ext", "=", "os", ".", "path", ".", "splitext", "(", "work_bam", ")", ...
51.580645
0.002455
def get_model_name(model): """ Get model name for the field. Django 1.5 uses module_name, does not support model_name Django 1.6 uses module_name and model_name DJango 1.7 uses model_name, module_name raises RemovedInDjango18Warning """ opts = model._meta if django.VERSION[:2] < (1, 7): ...
[ "def", "get_model_name", "(", "model", ")", ":", "opts", "=", "model", ".", "_meta", "if", "django", ".", "VERSION", "[", ":", "2", "]", "<", "(", "1", ",", "7", ")", ":", "model_name", "=", "opts", ".", "module_name", "else", ":", "model_name", "=...
27.4
0.002353
def format(self, version=None, wipe=None): """Format the tag to make it NDEF compatible or erase content. The :meth:`format` method is highly dependent on the tag type, product and present status, for example a tag that has been made read-only with lock bits can no longer be formatted o...
[ "def", "format", "(", "self", ",", "version", "=", "None", ",", "wipe", "=", "None", ")", ":", "if", "hasattr", "(", "self", ",", "\"_format\"", ")", ":", "args", "=", "\"version={0!r}, wipe={1!r}\"", "args", "=", "args", ".", "format", "(", "version", ...
47.418605
0.000961
def sphere_pick_polar(d, n=1, rng=None): """Return vectors uniformly picked on the unit sphere. Vectors are in a polar representation. Parameters ---------- d: float The number of dimensions of the space in which the sphere lives. n: integer Number of samples to pick. Retur...
[ "def", "sphere_pick_polar", "(", "d", ",", "n", "=", "1", ",", "rng", "=", "None", ")", ":", "if", "rng", "is", "None", ":", "rng", "=", "np", ".", "random", "a", "=", "np", ".", "empty", "(", "[", "n", ",", "d", "]", ")", "if", "d", "==", ...
26.0625
0.001156
def add_volume(self, volume): """ Args: volume (Volume): """ self._add_volume(name=volume.name, configs=volume.configs)
[ "def", "add_volume", "(", "self", ",", "volume", ")", ":", "self", ".", "_add_volume", "(", "name", "=", "volume", ".", "name", ",", "configs", "=", "volume", ".", "configs", ")" ]
22.571429
0.012195
def delete_all_eggs(self): """ delete all the eggs in the directory specified """ path_to_delete = os.path.join(self.egg_directory, "lib", "python") if os.path.exists(path_to_delete): shutil.rmtree(path_to_delete)
[ "def", "delete_all_eggs", "(", "self", ")", ":", "path_to_delete", "=", "os", ".", "path", ".", "join", "(", "self", ".", "egg_directory", ",", "\"lib\"", ",", "\"python\"", ")", "if", "os", ".", "path", ".", "exists", "(", "path_to_delete", ")", ":", ...
49
0.008032
def markdown_table(data, headers): """ Creates MarkDown table. Returns list of strings Arguments: data -- [(cell00, cell01, ...), (cell10, cell11, ...), ...] headers -- sequence of strings: (header0, header1, ...) """ maxx = [max([len(x) for x in column]) for column in zip(*da...
[ "def", "markdown_table", "(", "data", ",", "headers", ")", ":", "maxx", "=", "[", "max", "(", "[", "len", "(", "x", ")", "for", "x", "in", "column", "]", ")", "for", "column", "in", "zip", "(", "*", "data", ")", "]", "maxx", "=", "[", "max", ...
31.105263
0.001642
def solve(self, linear_system, vector_factory=None, *args, **kwargs): '''Solve the given linear system with recycling. The provided `vector_factory` determines which vectors are used for deflation. :param linear_system: the :py:class:`~krypy.linsys.LinearSys...
[ "def", "solve", "(", "self", ",", "linear_system", ",", "vector_factory", "=", "None", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# replace linear_system with equivalent TimedLinearSystem on demand", "if", "not", "isinstance", "(", "linear_system", ",", ...
40.733333
0.001598
def generate_uris(self): """Generate several lambda uris.""" lambda_arn = "arn:aws:execute-api:{0}:{1}:{2}/*/{3}/{4}".format(self.region, self.account_id, self.api_id, self.trigger_settings['method'], ...
[ "def", "generate_uris", "(", "self", ")", ":", "lambda_arn", "=", "\"arn:aws:execute-api:{0}:{1}:{2}/*/{3}/{4}\"", ".", "format", "(", "self", ".", "region", ",", "self", ".", "account_id", ",", "self", ".", "api_id", ",", "self", ".", "trigger_settings", "[", ...
64.785714
0.009783
def vq_body(x, codebook_size, beta=0.25, decay=0.999, epsilon=1e-5, soft_em=False, num_samples=10, temperature=None, do_update=True): """Discretize each x into one of codebook_size codes.""" x_shape = common_layers.shape...
[ "def", "vq_body", "(", "x", ",", "codebook_size", ",", "beta", "=", "0.25", ",", "decay", "=", "0.999", ",", "epsilon", "=", "1e-5", ",", "soft_em", "=", "False", ",", "num_samples", "=", "10", ",", "temperature", "=", "None", ",", "do_update", "=", ...
36.645833
0.008306
def _get_colors(self, color_set, alpha, off_color, custom_colors={}): """ assign colors according to the surface energies of on_wulff facets. return: (color_list, color_proxy, color_proxy_on_wulff, miller_on_wulff, e_surf_on_wulff_list) """ import matplot...
[ "def", "_get_colors", "(", "self", ",", "color_set", ",", "alpha", ",", "off_color", ",", "custom_colors", "=", "{", "}", ")", ":", "import", "matplotlib", "as", "mpl", "import", "matplotlib", ".", "pyplot", "as", "plt", "color_list", "=", "[", "off_color"...
47.52381
0.001473
def partition_read( self, table, columns, keyset, index="", partition_size_bytes=None, max_partitions=None, ): """Perform a ``ParitionRead`` API request for rows in a table. :type table: str :param table: name of the table from which t...
[ "def", "partition_read", "(", "self", ",", "table", ",", "columns", ",", "keyset", ",", "index", "=", "\"\"", ",", "partition_size_bytes", "=", "None", ",", "max_partitions", "=", "None", ",", ")", ":", "if", "not", "self", ".", "_multi_use", ":", "raise...
33.338235
0.001714
def places_within_radius( self, place=None, latitude=None, longitude=None, radius=0, **kwargs ): """ Return descriptions of the places stored in the collection that are within the circle specified by the given location and radius. A list of dicts will be returned. Th...
[ "def", "places_within_radius", "(", "self", ",", "place", "=", "None", ",", "latitude", "=", "None", ",", "longitude", "=", "None", ",", "radius", "=", "0", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'withdist'", "]", "=", "True", "kwargs", "...
35.036364
0.001514
def deprecated(function): # pylint: disable=invalid-name """Decorator to mark functions or methods as deprecated.""" def IssueDeprecationWarning(*args, **kwargs): """Issue a deprecation warning.""" warnings.simplefilter('default', DeprecationWarning) warnings.warn('Call to deprecated function: {0:s}.'...
[ "def", "deprecated", "(", "function", ")", ":", "# pylint: disable=invalid-name", "def", "IssueDeprecationWarning", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "\"\"\"Issue a deprecation warning.\"\"\"", "warnings", ".", "simplefilter", "(", "'default'", ",",...
41.733333
0.010938
def from_array(array): """ Deserialize a new PassportData from a given dictionary. :return: new PassportData instance. :rtype: PassportData """ if array is None or not array: return None # end if assert_type_or_raise(array, dict, parameter_nam...
[ "def", "from_array", "(", "array", ")", ":", "if", "array", "is", "None", "or", "not", "array", ":", "return", "None", "# end if", "assert_type_or_raise", "(", "array", ",", "dict", ",", "parameter_name", "=", "\"array\"", ")", "from", "pytgbot", ".", "api...
37.55
0.009091
def genchanges(self): """Generate a .changes file for this package.""" chparams = self.params.copy() debpath = os.path.join(self.buildroot, self.rule.output_files[0]) chparams.update({ 'fullversion': '{epoch}:{version}-{release}'.format(**chparams), 'metahash': se...
[ "def", "genchanges", "(", "self", ")", ":", "chparams", "=", "self", ".", "params", ".", "copy", "(", ")", "debpath", "=", "os", ".", "path", ".", "join", "(", "self", ".", "buildroot", ",", "self", ".", "rule", ".", "output_files", "[", "0", "]", ...
42.674419
0.001066
def create_deletion_handler(preference): """ Will generate a dynamic handler to purge related preference on instance deletion """ def delete_related_preferences(sender, instance, *args, **kwargs): queryset = preference.registry.preference_model.objects\ ...
[ "def", "create_deletion_handler", "(", "preference", ")", ":", "def", "delete_related_preferences", "(", "sender", ",", "instance", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "queryset", "=", "preference", ".", "registry", ".", "preference_model", "....
46
0.001639
def get_script_definition(id): """ Find and return the script definition for card \a id """ for cardset in CARD_SETS: module = import_module("fireplace.cards.%s" % (cardset)) if hasattr(module, id): return getattr(module, id)
[ "def", "get_script_definition", "(", "id", ")", ":", "for", "cardset", "in", "CARD_SETS", ":", "module", "=", "import_module", "(", "\"fireplace.cards.%s\"", "%", "(", "cardset", ")", ")", "if", "hasattr", "(", "module", ",", "id", ")", ":", "return", "get...
28.625
0.033898
def _sub_period_array(self, other): """ Subtract a Period Array/Index from self. This is only valid if self is itself a Period Array/Index, raises otherwise. Both objects must have the same frequency. Parameters ---------- other : PeriodIndex or PeriodArray ...
[ "def", "_sub_period_array", "(", "self", ",", "other", ")", ":", "if", "not", "is_period_dtype", "(", "self", ")", ":", "raise", "TypeError", "(", "\"cannot subtract {dtype}-dtype from {cls}\"", ".", "format", "(", "dtype", "=", "other", ".", "dtype", ",", "cl...
39.473684
0.001301
def setup_repo(): r""" Creates default structure for a new repo CommandLine: python -m utool setup_repo --repo=dtool --codedir=~/code python -m utool setup_repo --repo=dtool --codedir=~/code python -m utool setup_repo --repo=ibeis-flukematch-module --codedir=~/code --modname=ibeis_...
[ "def", "setup_repo", "(", ")", ":", "print", "(", "'\\n [setup_repo]!'", ")", "# import os", "from", "functools", "import", "partial", "import", "utool", "as", "ut", "# import os", "code_dpath", "=", "ut", ".", "truepath", "(", "ut", ".", "get_argval", "(", ...
32.515406
0.001254
def has_active_subscription(self, plan=None): """ Checks to see if this customer has an active subscription to the given plan. :param plan: The plan for which to check for an active subscription. If plan is None and there exists only one active subscription, this method will check if that subscription is v...
[ "def", "has_active_subscription", "(", "self", ",", "plan", "=", "None", ")", ":", "if", "plan", "is", "None", ":", "valid_subscriptions", "=", "self", ".", "_get_valid_subscriptions", "(", ")", "if", "len", "(", "valid_subscriptions", ")", "==", "0", ":", ...
31.216216
0.031066
def binarize(qualitative): """ binarizes an expression dataset. """ thresholds = qualitative.min(1) + (qualitative.max(1) - qualitative.min(1))/2.0 binarized = qualitative > thresholds.reshape((len(thresholds), 1)).repeat(8,1) return binarized.astype(int)
[ "def", "binarize", "(", "qualitative", ")", ":", "thresholds", "=", "qualitative", ".", "min", "(", "1", ")", "+", "(", "qualitative", ".", "max", "(", "1", ")", "-", "qualitative", ".", "min", "(", "1", ")", ")", "/", "2.0", "binarized", "=", "qua...
39
0.014337
def _compute_am_i_owner(self): """Check if current user is the owner""" for rec in self: rec.am_i_owner = (rec.create_uid == self.env.user)
[ "def", "_compute_am_i_owner", "(", "self", ")", ":", "for", "rec", "in", "self", ":", "rec", ".", "am_i_owner", "=", "(", "rec", ".", "create_uid", "==", "self", ".", "env", ".", "user", ")" ]
41
0.011976
def p_NonAnyType_object(p): """NonAnyType : object TypeSuffix""" p[0] = helper.unwrapTypeSuffix(model.SimpleType( type=model.SimpleType.OBJECT), p[2])
[ "def", "p_NonAnyType_object", "(", "p", ")", ":", "p", "[", "0", "]", "=", "helper", ".", "unwrapTypeSuffix", "(", "model", ".", "SimpleType", "(", "type", "=", "model", ".", "SimpleType", ".", "OBJECT", ")", ",", "p", "[", "2", "]", ")" ]
38.75
0.018987
def add_document(self, key, url, **kwargs): """ Adds document to record Args: key (string): document key url (string): document url Keyword Args: description (string): simple description fulltext (bool): mark if this is a full text ...
[ "def", "add_document", "(", "self", ",", "key", ",", "url", ",", "*", "*", "kwargs", ")", ":", "document", "=", "self", ".", "_check_metadata_for_file", "(", "key", "=", "key", ",", "url", "=", "url", ",", "*", "*", "kwargs", ")", "for", "dict_key", ...
28.871795
0.001718
def get_draws_stan3(fit, model=None, variables=None, ignore=None): """Extract draws from PyStan3 fit.""" if ignore is None: ignore = [] dtypes = {} if model is not None: dtypes = infer_dtypes(fit, model) if variables is None: variables = fit.param_names elif ...
[ "def", "get_draws_stan3", "(", "fit", ",", "model", "=", "None", ",", "variables", "=", "None", ",", "ignore", "=", "None", ")", ":", "if", "ignore", "is", "None", ":", "ignore", "=", "[", "]", "dtypes", "=", "{", "}", "if", "model", "is", "not", ...
31.516129
0.001986
def is_total_slice(item, shape): """Determine whether `item` specifies a complete slice of array with the given `shape`. Used to optimize __setitem__ operations on the Chunk class.""" # N.B., assume shape is normalized if item == Ellipsis: return True if item == slice(None): re...
[ "def", "is_total_slice", "(", "item", ",", "shape", ")", ":", "# N.B., assume shape is normalized", "if", "item", "==", "Ellipsis", ":", "return", "True", "if", "item", "==", "slice", "(", "None", ")", ":", "return", "True", "if", "isinstance", "(", "item", ...
31.818182
0.001387
def nvmlDeviceGetDetailedEccErrors(handle, errorType, counterType): r""" /** * Retrieves the detailed ECC error counts for the device. * * @deprecated This API supports only a fixed set of ECC error locations * On different GPU architectures different locations are supported ...
[ "def", "nvmlDeviceGetDetailedEccErrors", "(", "handle", ",", "errorType", ",", "counterType", ")", ":", "c_counts", "=", "c_nvmlEccErrorCounts_t", "(", ")", "fn", "=", "_nvmlGetFunctionPointer", "(", "\"nvmlDeviceGetDetailedEccErrors\"", ")", "ret", "=", "fn", "(", ...
56.369565
0.00834
def load_energy(): """Loads an energy related dataset to use with sankey and graphs""" tbl_name = 'energy_usage' data = get_example_data('energy.json.gz') pdf = pd.read_json(data) pdf.to_sql( tbl_name, db.engine, if_exists='replace', chunksize=500, dtype={ ...
[ "def", "load_energy", "(", ")", ":", "tbl_name", "=", "'energy_usage'", "data", "=", "get_example_data", "(", "'energy.json.gz'", ")", "pdf", "=", "pd", ".", "read_json", "(", "data", ")", "pdf", ".", "to_sql", "(", "tbl_name", ",", "db", ".", "engine", ...
27.165138
0.000326
def _logger(self): """Create logger instance. Returns: logger: An instance of logging """ log_level = { 'debug': logging.DEBUG, 'info': logging.INFO, 'warning': logging.WARNING, 'error': logging.ERROR, 'critical': l...
[ "def", "_logger", "(", "self", ")", ":", "log_level", "=", "{", "'debug'", ":", "logging", ".", "DEBUG", ",", "'info'", ":", "logging", ".", "INFO", ",", "'warning'", ":", "logging", ".", "WARNING", ",", "'error'", ":", "logging", ".", "ERROR", ",", ...
28.930233
0.001555
def itermonthdates(cls, year, month): """ Returns an iterator for the month in a year This iterator will return all days (as NepDate objects) for the month and all days before the start of the month or after the end of the month that are required to get a complete week. "...
[ "def", "itermonthdates", "(", "cls", ",", "year", ",", "month", ")", ":", "curday", "=", "NepDate", ".", "from_bs_date", "(", "year", ",", "month", ",", "1", ")", "start_weekday", "=", "curday", ".", "weekday", "(", ")", "# Start_weekday represents the numbe...
44.142857
0.002375
def subsc_search(self, article_code, **kwargs): '''taobao.vas.subsc.search 订购记录导出 用于ISV查询自己名下的应用及收费项目的订购记录''' request = TOPRequest('taobao.vas.subsc.search') request['article_code'] = article_code for k, v in kwargs.iteritems(): if k not in ('item_code', 'nic...
[ "def", "subsc_search", "(", "self", ",", "article_code", ",", "*", "*", "kwargs", ")", ":", "request", "=", "TOPRequest", "(", "'taobao.vas.subsc.search'", ")", "request", "[", "'article_code'", "]", "=", "article_code", "for", "k", ",", "v", "in", "kwargs",...
55.181818
0.017828
def workflow_get_details(object_id, input_params={}, always_retry=True, **kwargs): """ Invokes the /workflow-xxxx/getDetails API method. For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Details-and-Links#API-method%3A-%2Fclass-xxxx%2FgetDetails """ return DXHTTPRequest('/%s/ge...
[ "def", "workflow_get_details", "(", "object_id", ",", "input_params", "=", "{", "}", ",", "always_retry", "=", "True", ",", "*", "*", "kwargs", ")", ":", "return", "DXHTTPRequest", "(", "'/%s/getDetails'", "%", "object_id", ",", "input_params", ",", "always_re...
55.285714
0.010178
def view_directory(dname=None, fname=None, verbose=True): """ View a directory in the operating system file browser. Currently supports windows explorer, mac open, and linux nautlius. Args: dname (str): directory name fname (str): a filename to select in the directory (nautlius only) ...
[ "def", "view_directory", "(", "dname", "=", "None", ",", "fname", "=", "None", ",", "verbose", "=", "True", ")", ":", "from", "utool", ".", "util_arg", "import", "STRICT", "from", "utool", ".", "util_path", "import", "checkpath", "# from utool.util_str import ...
31.772152
0.000386
def from_dict(data): """ Build input parameters of `voluptuous.Schema` constructors from a Python `dict` description. :param :dict: data: same structure than what the YAML loader below loads. :return: tuple of 2 arguments. The first argument is the dict that must be given to `voluptuous.S...
[ "def", "from_dict", "(", "data", ")", ":", "assert", "isinstance", "(", "data", ",", "dict", ")", "options", "=", "data", ".", "get", "(", "'options'", ",", "{", "}", ")", "content", "=", "data", ".", "get", "(", "'content'", ",", "{", "}", ")", ...
38.448529
0.000559
def check_running(self, role, number): """ Check that a certain number of instances in a role are running. """ instances = self.get_instances_in_role(role, "running") if len(instances) != number: print "Expected %s instances in role %s, but was %s %s" % \ (number, role, len(instances),...
[ "def", "check_running", "(", "self", ",", "role", ",", "number", ")", ":", "instances", "=", "self", ".", "get_instances_in_role", "(", "role", ",", "\"running\"", ")", "if", "len", "(", "instances", ")", "!=", "number", ":", "print", "\"Expected %s instance...
33.909091
0.010444
def get_tile(url): """ Threadable function to retrieve map tiles from the internet :param url: URL of tile to get """ log = "" connection = None try: if six.PY3: connection = urlopen(url=url, timeout=2) # NOQA else: connection = urlopen(url=url) ...
[ "def", "get_tile", "(", "url", ")", ":", "log", "=", "\"\"", "connection", "=", "None", "try", ":", "if", "six", ".", "PY3", ":", "connection", "=", "urlopen", "(", "url", "=", "url", ",", "timeout", "=", "2", ")", "# NOQA", "else", ":", "connectio...
25.266667
0.001271
def lstrip_ws_and_chars(string, chars): """Remove leading whitespace and characters from a string. Parameters ---------- string : `str` String to strip. chars : `str` Characters to remove. Returns ------- `str` Stripped string. Examples -------- >>>...
[ "def", "lstrip_ws_and_chars", "(", "string", ",", "chars", ")", ":", "res", "=", "string", ".", "lstrip", "(", ")", ".", "lstrip", "(", "chars", ")", "while", "len", "(", "res", ")", "!=", "len", "(", "string", ")", ":", "string", "=", "res", "res"...
20.64
0.001852
def add_residue_from_geo(structure, geo): '''Adds a residue to chain A model 0 of the given structure, and returns the new structure. The residue to be added is determined by the geometry object given as second argument. This function is a helper function and should not normally be called direc...
[ "def", "add_residue_from_geo", "(", "structure", ",", "geo", ")", ":", "resRef", "=", "getReferenceResidue", "(", "structure", ")", "AA", "=", "geo", ".", "residue_name", "segID", "=", "resRef", ".", "get_id", "(", ")", "[", "1", "]", "segID", "+=", "1",...
35.141304
0.02858
def encrypt_pcbc(self, data, init_vector): """ Return an iterator that encrypts `data` using the Propagating Cipher-Block Chaining (PCBC) mode of operation. PCBC mode can only operate on `data` that is a multiple of the block-size in length. Each iteration returns a block-sized :obj:`b...
[ "def", "encrypt_pcbc", "(", "self", ",", "data", ",", "init_vector", ")", ":", "S1", ",", "S2", ",", "S3", ",", "S4", "=", "self", ".", "S", "P", "=", "self", ".", "P", "u4_1_pack", "=", "self", ".", "_u4_1_pack", "u1_4_unpack", "=", "self", ".", ...
33.042553
0.011257
def hello(environ, start_response): '''The WSGI_ application handler which returns an iterable over the "Hello World!" message.''' if environ['REQUEST_METHOD'] == 'GET': data = b'Hello World!\n' status = '200 OK' response_headers = [ ('Content-type', 'text/plain'), ...
[ "def", "hello", "(", "environ", ",", "start_response", ")", ":", "if", "environ", "[", "'REQUEST_METHOD'", "]", "==", "'GET'", ":", "data", "=", "b'Hello World!\\n'", "status", "=", "'200 OK'", "response_headers", "=", "[", "(", "'Content-type'", ",", "'text/p...
33.928571
0.002049
def cursor(lcd, row, col): """ Context manager to control cursor position. DEPRECATED. """ warnings.warn('The `cursor` context manager is deprecated', DeprecationWarning) lcd.cursor_pos = (row, col) yield
[ "def", "cursor", "(", "lcd", ",", "row", ",", "col", ")", ":", "warnings", ".", "warn", "(", "'The `cursor` context manager is deprecated'", ",", "DeprecationWarning", ")", "lcd", ".", "cursor_pos", "=", "(", "row", ",", "col", ")", "yield" ]
31.714286
0.008772
def from_name(cls, name): """Retrieve vlan id associated to a name.""" result = cls.list() vlans = {} for vlan in result: vlans[vlan['name']] = vlan['id'] return vlans.get(name)
[ "def", "from_name", "(", "cls", ",", "name", ")", ":", "result", "=", "cls", ".", "list", "(", ")", "vlans", "=", "{", "}", "for", "vlan", "in", "result", ":", "vlans", "[", "vlan", "[", "'name'", "]", "]", "=", "vlan", "[", "'id'", "]", "retur...
27.875
0.008696
def _run_program(self, bin, fastafile, params=None): """ Run AMD and predict motifs from a FASTA file. Parameters ---------- bin : str Command used to run the tool. fastafile : str Name of the FASTA input file. params : dict, opt...
[ "def", "_run_program", "(", "self", ",", "bin", ",", "fastafile", ",", "params", "=", "None", ")", ":", "params", "=", "self", ".", "_parse_params", "(", "params", ")", "fgfile", "=", "os", ".", "path", ".", "join", "(", "self", ".", "tmpdir", ",", ...
25.877193
0.009144
def get_user_config(project_path, use_cache=True): """ Produces a TidyPy configuration that incorporates the configuration files stored in the current user's home directory. :param project_path: the path to the project that is going to be analyzed :type project_path: str :param use_cache: ...
[ "def", "get_user_config", "(", "project_path", ",", "use_cache", "=", "True", ")", ":", "if", "sys", ".", "platform", "==", "'win32'", ":", "user_config", "=", "os", ".", "path", ".", "expanduser", "(", "r'~\\\\tidypy'", ")", "else", ":", "user_config", "=...
33.83871
0.000927
def insert_many(self, rows, chunk_size=1000): """ Add many rows at a time, which is significantly faster than adding them one by one. Per default the rows are processed in chunks of 1000 per commit, unless you specify a different ``chunk_size``. See :py:meth:`insert() <dataset.Ta...
[ "def", "insert_many", "(", "self", ",", "rows", ",", "chunk_size", "=", "1000", ")", ":", "def", "_process_chunk", "(", "chunk", ")", ":", "self", ".", "table", ".", "insert", "(", ")", ".", "execute", "(", "chunk", ")", "self", ".", "_check_dropped", ...
33
0.002356
def _compile_tag_re(self): """ Compile regex strings from device_tag_re option and return list of compiled regex/tag pairs """ device_tag_list = [] for regex_str, tags in iteritems(self._device_tag_re): try: device_tag_list.append([re.compile(regex_str...
[ "def", "_compile_tag_re", "(", "self", ")", ":", "device_tag_list", "=", "[", "]", "for", "regex_str", ",", "tags", "in", "iteritems", "(", "self", ".", "_device_tag_re", ")", ":", "try", ":", "device_tag_list", ".", "append", "(", "[", "re", ".", "compi...
50.090909
0.008913
def split_by_fname_file(self, fname:PathOrStr, path:PathOrStr=None)->'ItemLists': "Split the data by using the names in `fname` for the validation set. `path` will override `self.path`." path = Path(ifnone(path, self.path)) valid_names = loadtxt_str(path/fname) return self.split_by_files...
[ "def", "split_by_fname_file", "(", "self", ",", "fname", ":", "PathOrStr", ",", "path", ":", "PathOrStr", "=", "None", ")", "->", "'ItemLists'", ":", "path", "=", "Path", "(", "ifnone", "(", "path", ",", "self", ".", "path", ")", ")", "valid_names", "=...
65.8
0.027027
def run(self): """ Run the plugin. """ # Only run if the build was successful if self.workflow.build_process_failed: self.log.info("Not promoting failed build to koji") return koji_metadata, output_files = self.get_metadata() if not is_sc...
[ "def", "run", "(", "self", ")", ":", "# Only run if the build was successful", "if", "self", ".", "workflow", ".", "build_process_failed", ":", "self", ".", "log", ".", "info", "(", "\"Not promoting failed build to koji\"", ")", "return", "koji_metadata", ",", "outp...
33.763158
0.001515
def now(self): ''' Display Taiwan Time now 顯示台灣此刻時間 ''' localtime = datetime.datetime.now() return localtime + datetime.timedelta(hours = time.timezone/60/60 + self.TimeZone)
[ "def", "now", "(", "self", ")", ":", "localtime", "=", "datetime", ".", "datetime", ".", "now", "(", ")", "return", "localtime", "+", "datetime", ".", "timedelta", "(", "hours", "=", "time", ".", "timezone", "/", "60", "/", "60", "+", "self", ".", ...
32.166667
0.020202
def class_name_to_instant_name(name): """ This will convert from 'ParentName_ChildName' to 'parent_name.child_name' """ name = name.replace('/', '_') ret = name[0].lower() for i in range(1, len(name)): if name[i] == '_': ret += '.' elif '9' < name[i] < 'a' and name[i - 1]...
[ "def", "class_name_to_instant_name", "(", "name", ")", ":", "name", "=", "name", ".", "replace", "(", "'/'", ",", "'_'", ")", "ret", "=", "name", "[", "0", "]", ".", "lower", "(", ")", "for", "i", "in", "range", "(", "1", ",", "len", "(", "name",...
32.384615
0.002309
def get_site_dict(self, ads_pos): """Get dictionary with high symmetry sites close to adsorbate position. Top sites: Optained from the atomic positions of the top layer of the slab. Bridge sites: The average position of atomic pairs Hollow sites: Optained as ...
[ "def", "get_site_dict", "(", "self", ",", "ads_pos", ")", ":", "# Get top layer", "C", "=", "self", ".", "B", "[", "-", "self", ".", "ntop", "-", "1", ":", "-", "1", "]", "SC", "=", "C", "*", "(", "3", ",", "3", ",", "1", ")", "D", "=", "{"...
38.84375
0.001046
def gfonts_repo_structure(fonts): """ The family at the given font path follows the files and directory structure typical of a font project hosted on the Google Fonts repo on GitHub ? """ from fontbakery.utils import get_absolute_path # FIXME: Improve this with more details # about the...
[ "def", "gfonts_repo_structure", "(", "fonts", ")", ":", "from", "fontbakery", ".", "utils", "import", "get_absolute_path", "# FIXME: Improve this with more details", "# about the expected structure.", "abspath", "=", "get_absolute_path", "(", "fonts", "[", "0", "]", ...
39.818182
0.015625
def navigate(self): """Return the longitudes and latitudes of the scene. """ tic = datetime.now() lons40km = self._data["pos"][:, :, 1] * 1e-4 lats40km = self._data["pos"][:, :, 0] * 1e-4 try: from geotiepoints import SatelliteInterpolator except Impo...
[ "def", "navigate", "(", "self", ")", ":", "tic", "=", "datetime", ".", "now", "(", ")", "lons40km", "=", "self", ".", "_data", "[", "\"pos\"", "]", "[", ":", ",", ":", ",", "1", "]", "*", "1e-4", "lats40km", "=", "self", ".", "_data", "[", "\"p...
38.214286
0.001823
def _clean_header_df(self, df): """Format the header dataframe and add units.""" if self.suffix == '-drvd.txt': df.units = {'release_time': 'second', 'precipitable_water': 'millimeter', 'inv_pressure': 'hPa', 'inv_height...
[ "def", "_clean_header_df", "(", "self", ",", "df", ")", ":", "if", "self", ".", "suffix", "==", "'-drvd.txt'", ":", "df", ".", "units", "=", "{", "'release_time'", ":", "'second'", ",", "'precipitable_water'", ":", "'millimeter'", ",", "'inv_pressure'", ":",...
43.709677
0.001444
def add_location(self, location): """ Add a media location to this subject. - **location** can be an open :py:class:`file` object, a path to a local file, or a :py:class:`dict` containing MIME types and URLs for remote media. Examples:: subject.add_loca...
[ "def", "add_location", "(", "self", ",", "location", ")", ":", "if", "type", "(", "location", ")", "is", "dict", ":", "self", ".", "locations", ".", "append", "(", "location", ")", "self", ".", "_media_files", ".", "append", "(", "None", ")", "return",...
37.170732
0.001918
def get_books(self): """Pass through to provider BookLookupSession.get_books""" # Implemented from kitosid template for - # osid.resource.BinLookupSession.get_bins_template catalogs = self._get_provider_session('book_lookup_session').get_books() cat_list = [] for cat in c...
[ "def", "get_books", "(", "self", ")", ":", "# Implemented from kitosid template for -", "# osid.resource.BinLookupSession.get_bins_template", "catalogs", "=", "self", ".", "_get_provider_session", "(", "'book_lookup_session'", ")", ".", "get_books", "(", ")", "cat_list", "=...
49.444444
0.00883
def _sign(private_key, data, hash_algorithm, rsa_pss_padding=False): """ Generates an RSA, DSA or ECDSA signature :param private_key: The PrivateKey to generate the signature with :param data: A byte string of the data the signature is for :param hash_algorithm: A unicode ...
[ "def", "_sign", "(", "private_key", ",", "data", ",", "hash_algorithm", ",", "rsa_pss_padding", "=", "False", ")", ":", "if", "not", "isinstance", "(", "private_key", ",", "PrivateKey", ")", ":", "raise", "TypeError", "(", "pretty_message", "(", "'''\n ...
35.29927
0.000905
def setitem(self, key, value): # type: (Any, Any, Any) -> Any '''Takes an object, a key, and a value and produces a new object that is a copy of the original but with ``value`` as the new value of ``key``. The following equality should hold for your definition: .. code-block:: python ...
[ "def", "setitem", "(", "self", ",", "key", ",", "value", ")", ":", "# type: (Any, Any, Any) -> Any", "try", ":", "self", ".", "_lens_setitem", "except", "AttributeError", ":", "selfcopy", "=", "copy", ".", "copy", "(", "self", ")", "selfcopy", "[", "key", ...
34.714286
0.000801
def op_funcdef_handle(tokens): """Process infix defs.""" func, base_args = get_infix_items(tokens) args = [] for arg in base_args[:-1]: rstrip_arg = arg.rstrip() if not rstrip_arg.endswith(unwrapper): if not rstrip_arg.endswith(","): arg += ", " el...
[ "def", "op_funcdef_handle", "(", "tokens", ")", ":", "func", ",", "base_args", "=", "get_infix_items", "(", "tokens", ")", "args", "=", "[", "]", "for", "arg", "in", "base_args", "[", ":", "-", "1", "]", ":", "rstrip_arg", "=", "arg", ".", "rstrip", ...
32.882353
0.001739
def __parse_stream(self, stream): """Generic method to parse mailmap streams""" nline = 0 lines = stream.split('\n') for line in lines: nline += 1 # Ignore blank lines and comments m = re.match(self.LINES_TO_IGNORE_REGEX, line, re.UNICODE) ...
[ "def", "__parse_stream", "(", "self", ",", "stream", ")", ":", "nline", "=", "0", "lines", "=", "stream", ".", "split", "(", "'\\n'", ")", "for", "line", "in", "lines", ":", "nline", "+=", "1", "# Ignore blank lines and comments", "m", "=", "re", ".", ...
27.868421
0.001825
def _format_credentials(self): """ Returns the current credentials in the format expected by the authentication service. """ tenant_name = self.tenant_name or self.username tenant_id = self.tenant_id or self.username return {"auth": {"passwordCredentials": ...
[ "def", "_format_credentials", "(", "self", ")", ":", "tenant_name", "=", "self", ".", "tenant_name", "or", "self", ".", "username", "tenant_id", "=", "self", ".", "tenant_id", "or", "self", ".", "username", "return", "{", "\"auth\"", ":", "{", "\"passwordCre...
37.083333
0.008772
def _fetch_losc_data_file(url, *args, **kwargs): """Internal function for fetching a single LOSC file and returning a Series """ cls = kwargs.pop('cls', TimeSeries) cache = kwargs.pop('cache', None) verbose = kwargs.pop('verbose', False) # match file format if url.endswith('.gz'): e...
[ "def", "_fetch_losc_data_file", "(", "url", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "cls", "=", "kwargs", ".", "pop", "(", "'cls'", ",", "TimeSeries", ")", "cache", "=", "kwargs", ".", "pop", "(", "'cache'", ",", "None", ")", "verbose", ...
35.22449
0.000564
def sub_network_pf(sub_network, snapshots=None, skip_pre=False, x_tol=1e-6, use_seed=False): """ Non-linear power flow for connected sub-network. Parameters ---------- snapshots : list-like|single snapshot A subset or an elements of network.snapshots on which to run the power flow, ...
[ "def", "sub_network_pf", "(", "sub_network", ",", "snapshots", "=", "None", ",", "skip_pre", "=", "False", ",", "x_tol", "=", "1e-6", ",", "use_seed", "=", "False", ")", ":", "snapshots", "=", "_as_snapshots", "(", "sub_network", ".", "network", ",", "snap...
44.742574
0.012772
def run_pipeline_steps(steps, context): """Run the run_step(context) method of each step in steps. Args: steps: list. Sequence of Steps to execute context: pypyr.context.Context. The pypyr context. Will mutate. """ logger.debug("starting") assert isinstance( context, dict), ...
[ "def", "run_pipeline_steps", "(", "steps", ",", "context", ")", ":", "logger", ".", "debug", "(", "\"starting\"", ")", "assert", "isinstance", "(", "context", ",", "dict", ")", ",", "\"context must be a dictionary, even if empty {}.\"", "if", "steps", "is", "None"...
28
0.001439
def _train(self): """Implements train() for a Function API. If the RunnerThread finishes without reporting "done", Tune will automatically provide a magic keyword __duplicate__ along with a result with "done=True". The TrialRunner will handle the result accordingly (see tune/tri...
[ "def", "_train", "(", "self", ")", ":", "if", "self", ".", "_runner", ".", "is_alive", "(", ")", ":", "# if started and alive, inform the reporter to continue and", "# generate the next result", "self", ".", "_continue_semaphore", ".", "release", "(", ")", "else", "...
41.507042
0.000663
def get_checker_names(self): """Get all the checker names that this linter knows about.""" current_checkers = self.get_checkers() return sorted( {check.name for check in current_checkers if check.name != "master"} )
[ "def", "get_checker_names", "(", "self", ")", ":", "current_checkers", "=", "self", ".", "get_checkers", "(", ")", "return", "sorted", "(", "{", "check", ".", "name", "for", "check", "in", "current_checkers", "if", "check", ".", "name", "!=", "\"master\"", ...
42.333333
0.011583
def load_subcommands(group): """ Decorator used to load subcommands from a given ``pkg_resources`` entrypoint group. Each function must be appropriately decorated with the ``cli_tools`` decorators to be considered an extension. :param group: The name of the ``pkg_resources`` entrypoint group. ...
[ "def", "load_subcommands", "(", "group", ")", ":", "def", "decorator", "(", "func", ")", ":", "adaptor", "=", "ScriptAdaptor", ".", "_get_adaptor", "(", "func", ")", "adaptor", ".", "_add_extensions", "(", "group", ")", "return", "func", "return", "decorator...
33.357143
0.002083
def Schmidt(D, mu=None, nu=None, rho=None): r'''Calculates Schmidt number or `Sc` for a fluid with the given parameters. .. math:: Sc = \frac{\mu}{D\rho} = \frac{\nu}{D} Inputs can be any of the following sets: * Diffusivity, dynamic viscosity, and density * Diffusivity and kinematic ...
[ "def", "Schmidt", "(", "D", ",", "mu", "=", "None", ",", "nu", "=", "None", ",", "rho", "=", "None", ")", ":", "if", "rho", "and", "mu", ":", "return", "mu", "/", "(", "rho", "*", "D", ")", "elif", "nu", ":", "return", "nu", "/", "D", "else...
26.678571
0.001291
def post_tracking_beacon(self, tracking_beacons_id, **data): """ POST /tracking_beacons/:tracking_beacons_id/ Updates the :format:`tracking_beacons` with the specified :tracking_beacons_id. Though ``event_id`` and ``user_id`` are not individually required, it is a requirement to have a tracking ...
[ "def", "post_tracking_beacon", "(", "self", ",", "tracking_beacons_id", ",", "*", "*", "data", ")", ":", "return", "self", ".", "post", "(", "\"/tracking_beacons/{0}/\"", ".", "format", "(", "tracking_beacons_id", ")", ",", "data", "=", "data", ")" ]
74.428571
0.009488
def reduce_operators(source): """ Remove spaces between operators in *source* and returns the result. Example:: def foo(foo, bar, blah): test = "This is a %s" % foo Will become:: def foo(foo,bar,blah): test="This is a %s"%foo .. note:: Also remov...
[ "def", "reduce_operators", "(", "source", ")", ":", "io_obj", "=", "io", ".", "StringIO", "(", "source", ")", "prev_tok", "=", "None", "out_tokens", "=", "[", "]", "out", "=", "\"\"", "last_lineno", "=", "-", "1", "last_col", "=", "0", "nl_types", "=",...
37.291667
0.001451
def statementize(e: ast.AST) -> ast.AST: """Transform non-statements into ast.Expr nodes so they can stand alone as statements.""" # noinspection PyPep8 if isinstance( e, ( ast.Assign, ast.AnnAssign, ast.AugAssign, ast.Expr, ast...
[ "def", "statementize", "(", "e", ":", "ast", ".", "AST", ")", "->", "ast", ".", "AST", ":", "# noinspection PyPep8", "if", "isinstance", "(", "e", ",", "(", "ast", ".", "Assign", ",", "ast", ".", "AnnAssign", ",", "ast", ".", "AugAssign", ",", "ast",...
23.783784
0.001092
def read_yaml_config(filename, check=True, osreplace=True, exit=True): """ reads in a yaml file from the specified filename. If check is set to true the code will fail if the file does not exist. However if it is set to false and the file does not exist, None is returned. :param exit: if true is ex...
[ "def", "read_yaml_config", "(", "filename", ",", "check", "=", "True", ",", "osreplace", "=", "True", ",", "exit", "=", "True", ")", ":", "location", "=", "filename", "if", "location", "is", "not", "None", ":", "location", "=", "path_expand", "(", "locat...
32.087719
0.000531
def make_dict(obj): """This method creates a dictionary out of a non-builtin object""" # Recursion base case if is_builtin(obj) or isinstance(obj, OrderedDict): return obj output_dict = {} for key in dir(obj): if not key.startswith('__') and not callable(getattr(obj, key)): ...
[ "def", "make_dict", "(", "obj", ")", ":", "# Recursion base case", "if", "is_builtin", "(", "obj", ")", "or", "isinstance", "(", "obj", ",", "OrderedDict", ")", ":", "return", "obj", "output_dict", "=", "{", "}", "for", "key", "in", "dir", "(", "obj", ...
30.5
0.00159
def chunkiter(objs, n=100): """ Chunk an iterator of unknown size. The optional keyword 'n' sets the chunk size (default 100). """ objs = iter(objs) try: while (1): chunk = [] while len(chunk) < n: chunk.append(six.next(objs)) yield ch...
[ "def", "chunkiter", "(", "objs", ",", "n", "=", "100", ")", ":", "objs", "=", "iter", "(", "objs", ")", "try", ":", "while", "(", "1", ")", ":", "chunk", "=", "[", "]", "while", "len", "(", "chunk", ")", "<", "n", ":", "chunk", ".", "append",...
22.647059
0.002494
def write(self, h, txt='', link=''): "Output text in flowing mode" txt = self.normalize_text(txt) cw=self.current_font['cw'] w=self.w-self.r_margin-self.x wmax=(w-2*self.c_margin)*1000.0/self.font_size s=txt.replace("\r",'') nb=len(s) sep=-1 i=0 ...
[ "def", "write", "(", "self", ",", "h", ",", "txt", "=", "''", ",", "link", "=", "''", ")", ":", "txt", "=", "self", ".", "normalize_text", "(", "txt", ")", "cw", "=", "self", ".", "current_font", "[", "'cw'", "]", "w", "=", "self", ".", "w", ...
32.439394
0.043064
def data(self, index, role=Qt.DisplayRole): """Qt Override.""" row = index.row() if not index.isValid() or not (0 <= row < len(self.shortcuts)): return to_qvariant() shortcut = self.shortcuts[row] key = shortcut.key column = index.column() ...
[ "def", "data", "(", "self", ",", "index", ",", "role", "=", "Qt", ".", "DisplayRole", ")", ":", "row", "=", "index", ".", "row", "(", ")", "if", "not", "index", ".", "isValid", "(", ")", "or", "not", "(", "0", "<=", "row", "<", "len", "(", "s...
44.257143
0.001263