text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def i2repr(self, pkt, x):
# type: (Optional[packet.Packet], int) -> str
""" i2repr is overloaded to restrict the acceptable x values (not None)
@param packet.Packet|None pkt: the packet instance containing this field instance; probably unused. # noqa: E501
@param int x: the value to co... | [
"def",
"i2repr",
"(",
"self",
",",
"pkt",
",",
"x",
")",
":",
"# type: (Optional[packet.Packet], int) -> str",
"return",
"super",
"(",
"UVarIntField",
",",
"self",
")",
".",
"i2repr",
"(",
"pkt",
",",
"x",
")"
] | 47.555556 | 18.666667 |
def _select_ontology(self, line):
"""try to select an ontology NP: the actual load from FS is in <_load_ontology> """
try:
var = int(line) # it's a string
if var in range(1, len(self.all_ontologies)+1):
self._load_ontology(self.all_ontologies[var-1])
exce... | [
"def",
"_select_ontology",
"(",
"self",
",",
"line",
")",
":",
"try",
":",
"var",
"=",
"int",
"(",
"line",
")",
"# it's a string",
"if",
"var",
"in",
"range",
"(",
"1",
",",
"len",
"(",
"self",
".",
"all_ontologies",
")",
"+",
"1",
")",
":",
"self"... | 41.857143 | 12.785714 |
def find_mappable(*axes):
"""Find the most recently added mappable layer in the given axes
Parameters
----------
*axes : `~matplotlib.axes.Axes`
one or more axes to search for a mappable
"""
for ax in axes:
for aset in ('collections', 'images'):
try:
... | [
"def",
"find_mappable",
"(",
"*",
"axes",
")",
":",
"for",
"ax",
"in",
"axes",
":",
"for",
"aset",
"in",
"(",
"'collections'",
",",
"'images'",
")",
":",
"try",
":",
"return",
"getattr",
"(",
"ax",
",",
"aset",
")",
"[",
"-",
"1",
"]",
"except",
... | 32.3125 | 14.25 |
def configure(self, config):
"""
Configures component by passing configuration parameters.
:param config: configuration parameters to be set.
"""
self._timeout = config.get_as_long_with_default("options.timeout", self._default_timeout)
self._max_size = config.get_as_long... | [
"def",
"configure",
"(",
"self",
",",
"config",
")",
":",
"self",
".",
"_timeout",
"=",
"config",
".",
"get_as_long_with_default",
"(",
"\"options.timeout\"",
",",
"self",
".",
"_default_timeout",
")",
"self",
".",
"_max_size",
"=",
"config",
".",
"get_as_long... | 46.25 | 26.5 |
def save_to_file(self, data, stamp):
"""Saves data to current dataset.
:param data: data to save to file
:type data: numpy.ndarray
:param stamp: time stamp of when the data was acquired
:type stamp: str
"""
self.datafile.append(self.current_dataset_name, data)
... | [
"def",
"save_to_file",
"(",
"self",
",",
"data",
",",
"stamp",
")",
":",
"self",
".",
"datafile",
".",
"append",
"(",
"self",
".",
"current_dataset_name",
",",
"data",
")",
"# save stimulu info",
"info",
"=",
"dict",
"(",
"self",
".",
"_stimulus",
".",
"... | 41.2 | 15.2 |
def extender(self, edge):
"See what edges can be extended by this edge."
(j, k, B, _, _) = edge
for (i, j, A, alpha, B1b) in self.chart[j]:
if B1b and B == B1b[0]:
self.add_edge([i, k, A, alpha + [edge], B1b[1:]]) | [
"def",
"extender",
"(",
"self",
",",
"edge",
")",
":",
"(",
"j",
",",
"k",
",",
"B",
",",
"_",
",",
"_",
")",
"=",
"edge",
"for",
"(",
"i",
",",
"j",
",",
"A",
",",
"alpha",
",",
"B1b",
")",
"in",
"self",
".",
"chart",
"[",
"j",
"]",
":... | 43.333333 | 13.333333 |
def datasets(self) -> tuple:
"""Datasets."""
return tuple(v for _, v in self.items() if isinstance(v, h5py.Dataset)) | [
"def",
"datasets",
"(",
"self",
")",
"->",
"tuple",
":",
"return",
"tuple",
"(",
"v",
"for",
"_",
",",
"v",
"in",
"self",
".",
"items",
"(",
")",
"if",
"isinstance",
"(",
"v",
",",
"h5py",
".",
"Dataset",
")",
")"
] | 43.333333 | 17 |
def get_verb_function(data, verb):
"""
Return function that implements the verb for given data type
"""
try:
module = type_lookup[type(data)]
except KeyError:
# Some guess work for subclasses
for type_, mod in type_lookup.items():
if isinstance(data, type_):
... | [
"def",
"get_verb_function",
"(",
"data",
",",
"verb",
")",
":",
"try",
":",
"module",
"=",
"type_lookup",
"[",
"type",
"(",
"data",
")",
"]",
"except",
"KeyError",
":",
"# Some guess work for subclasses",
"for",
"type_",
",",
"mod",
"in",
"type_lookup",
".",... | 31.882353 | 10.705882 |
def calc_networkmeasure(self, networkmeasure, **measureparams):
"""
Calculate network measure.
Parameters
-----------
networkmeasure : str
Function to call. Functions available are in teneto.networkmeasures
measureparams : kwargs
kwargs for tenet... | [
"def",
"calc_networkmeasure",
"(",
"self",
",",
"networkmeasure",
",",
"*",
"*",
"measureparams",
")",
":",
"availablemeasures",
"=",
"[",
"f",
"for",
"f",
"in",
"dir",
"(",
"teneto",
".",
"networkmeasures",
")",
"if",
"not",
"f",
".",
"startswith",
"(",
... | 40.809524 | 20.714286 |
def small_image_url(self):
"""Optional[:class:`str`]: Returns a URL pointing to the small image asset of this activity if applicable."""
if self.application_id is None:
return None
try:
small_image = self.assets['small_image']
except KeyError:
return ... | [
"def",
"small_image_url",
"(",
"self",
")",
":",
"if",
"self",
".",
"application_id",
"is",
"None",
":",
"return",
"None",
"try",
":",
"small_image",
"=",
"self",
".",
"assets",
"[",
"'small_image'",
"]",
"except",
"KeyError",
":",
"return",
"None",
"else"... | 40 | 22.090909 |
def register_eventclass(event_id):
"""Decorator for registering event classes for parsing
"""
def register(cls):
if not issubclass(cls, Event):
raise MessageException(('Cannot register a class that'
' is not a subclass of Event'))
EVENT_REGISTR... | [
"def",
"register_eventclass",
"(",
"event_id",
")",
":",
"def",
"register",
"(",
"cls",
")",
":",
"if",
"not",
"issubclass",
"(",
"cls",
",",
"Event",
")",
":",
"raise",
"MessageException",
"(",
"(",
"'Cannot register a class that'",
"' is not a subclass of Event'... | 38.5 | 13.583333 |
def handle_output(self, workunit, label, stream):
"""Implementation of Reporter callback."""
self._root_id_to_workunit_stack[str(workunit.root().id)][-1]['outputs'][label] += stream | [
"def",
"handle_output",
"(",
"self",
",",
"workunit",
",",
"label",
",",
"stream",
")",
":",
"self",
".",
"_root_id_to_workunit_stack",
"[",
"str",
"(",
"workunit",
".",
"root",
"(",
")",
".",
"id",
")",
"]",
"[",
"-",
"1",
"]",
"[",
"'outputs'",
"]"... | 46.75 | 25.25 |
def state_full(self):
"""unicode, the full name of the object's state.
>>> address = Address(country='US', state='CO')
>>> address.state
u'CO'
>>> address.state_full
u'Colorado'
"""
if self.is_valid_state:
ret... | [
"def",
"state_full",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_valid_state",
":",
"return",
"STATES",
"[",
"self",
".",
"country",
".",
"upper",
"(",
")",
"]",
".",
"get",
"(",
"self",
".",
"state",
".",
"upper",
"(",
")",
")"
] | 28 | 18.384615 |
def ac_encode(text, probs):
"""Encode a text using arithmetic coding with the provided probabilities.
This is a wrapper for :py:meth:`Arithmetic.encode`.
Parameters
----------
text : str
A string to encode
probs : dict
A probability statistics dictionary generated by
:p... | [
"def",
"ac_encode",
"(",
"text",
",",
"probs",
")",
":",
"coder",
"=",
"Arithmetic",
"(",
")",
"coder",
".",
"set_probs",
"(",
"probs",
")",
"return",
"coder",
".",
"encode",
"(",
"text",
")"
] | 22.5 | 21.928571 |
def _get_joined_path(ctx):
"""
@type ctx: L{_URLContext}
@param ctx: A URL context.
@return: The path component, un-urlencoded, but joined by slashes.
@rtype: L{bytes}
"""
return b'/' + b'/'.join(seg.encode('utf-8') for seg in ctx.path) | [
"def",
"_get_joined_path",
"(",
"ctx",
")",
":",
"return",
"b'/'",
"+",
"b'/'",
".",
"join",
"(",
"seg",
".",
"encode",
"(",
"'utf-8'",
")",
"for",
"seg",
"in",
"ctx",
".",
"path",
")"
] | 28.555556 | 17 |
def check_file_encoding(self, input_file_path):
"""
Check whether the given file is UTF-8 encoded.
:param string input_file_path: the path of the file to be checked
:rtype: :class:`~aeneas.validator.ValidatorResult`
"""
self.log([u"Checking encoding of file '%s'", input_... | [
"def",
"check_file_encoding",
"(",
"self",
",",
"input_file_path",
")",
":",
"self",
".",
"log",
"(",
"[",
"u\"Checking encoding of file '%s'\"",
",",
"input_file_path",
"]",
")",
"self",
".",
"result",
"=",
"ValidatorResult",
"(",
")",
"if",
"self",
".",
"_ar... | 43.777778 | 15.333333 |
def resolve_implicit_levels(storage, debug):
"""Resolving implicit levels (I1, I2)
See: http://unicode.org/reports/tr9/#Resolving_Implicit_Levels
"""
for run in storage['runs']:
start, length = run['start'], run['length']
chars = storage['chars'][start:start+length]
for _ch in... | [
"def",
"resolve_implicit_levels",
"(",
"storage",
",",
"debug",
")",
":",
"for",
"run",
"in",
"storage",
"[",
"'runs'",
"]",
":",
"start",
",",
"length",
"=",
"run",
"[",
"'start'",
"]",
",",
"run",
"[",
"'length'",
"]",
"chars",
"=",
"storage",
"[",
... | 38.451613 | 18 |
def decompose_select(selectx):
"return [(parent,setter) for scalar_subquery], wherex_including_on, NameIndexer. helper for run_select"
nix = NameIndexer.ctor_fromlist(selectx.tables)
where = []
for fromx in selectx.tables:
if isinstance(fromx,sqparse2.JoinX) and fromx.on_stmt is not None:
# todo: what... | [
"def",
"decompose_select",
"(",
"selectx",
")",
":",
"nix",
"=",
"NameIndexer",
".",
"ctor_fromlist",
"(",
"selectx",
".",
"tables",
")",
"where",
"=",
"[",
"]",
"for",
"fromx",
"in",
"selectx",
".",
"tables",
":",
"if",
"isinstance",
"(",
"fromx",
",",
... | 52.1 | 27.3 |
def marginals(self, X):
"""
Compute the marginals for the given candidates X.
Note: split into batches to avoid OOM errors.
:param X: The input data which is a (list of Candidate objects, a sparse
matrix of corresponding features) pair or a list of
(Candidate, fe... | [
"def",
"marginals",
"(",
"self",
",",
"X",
")",
":",
"nn",
".",
"Module",
".",
"train",
"(",
"self",
",",
"False",
")",
"if",
"self",
".",
"_check_input",
"(",
"X",
")",
":",
"X",
"=",
"self",
".",
"_preprocess_data",
"(",
"X",
")",
"dataloader",
... | 30.733333 | 18.666667 |
def has_local_job_refs(io_hash):
'''
:param io_hash: input/output hash
:type io_hash: dict
:returns: boolean indicating whether any job-based object references are found in *io_hash*
'''
q = []
for field in io_hash:
if is_job_ref(io_hash[field]):
if get_job_from_jbor(io_... | [
"def",
"has_local_job_refs",
"(",
"io_hash",
")",
":",
"q",
"=",
"[",
"]",
"for",
"field",
"in",
"io_hash",
":",
"if",
"is_job_ref",
"(",
"io_hash",
"[",
"field",
"]",
")",
":",
"if",
"get_job_from_jbor",
"(",
"io_hash",
"[",
"field",
"]",
")",
".",
... | 36.939394 | 20.69697 |
def link(obj_files, out_file=None, shared=False, CompilerRunner_=None,
cwd=None, cplus=False, fort=False, **kwargs):
"""
Link object files.
Parameters
----------
obj_files: iterable of path strings
out_file: path string (optional)
path to executable/shared library, if missing
... | [
"def",
"link",
"(",
"obj_files",
",",
"out_file",
"=",
"None",
",",
"shared",
"=",
"False",
",",
"CompilerRunner_",
"=",
"None",
",",
"cwd",
"=",
"None",
",",
"cplus",
"=",
"False",
",",
"fort",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"if"... | 32.178082 | 17.986301 |
def compute_transitions(self, density_normalize=True):
"""Compute transition matrix.
Parameters
----------
density_normalize : `bool`
The density rescaling of Coifman and Lafon (2006): Then only the
geometry of the data matters, not the sampled density.
... | [
"def",
"compute_transitions",
"(",
"self",
",",
"density_normalize",
"=",
"True",
")",
":",
"W",
"=",
"self",
".",
"_connectivities",
"# density normalization as of Coifman et al. (2005)",
"# ensures that kernel matrix is independent of sampling density",
"if",
"density_normalize... | 37.638889 | 19.694444 |
def _call_fan(branch, calls, executable):
"""Appends a list of callees to the branch for each parent
in the call list that calls this executable.
"""
#Since we don't keep track of the specific logic in the executables
#it is possible that we could get a infinite recursion of executables
#that ke... | [
"def",
"_call_fan",
"(",
"branch",
",",
"calls",
",",
"executable",
")",
":",
"#Since we don't keep track of the specific logic in the executables",
"#it is possible that we could get a infinite recursion of executables",
"#that keep calling each other.",
"if",
"executable",
"in",
"b... | 35.5625 | 13.75 |
def _serialiseFirstJob(self, jobStore):
"""
Serialises the root job. Returns the wrapping job.
:param toil.jobStores.abstractJobStore.AbstractJobStore jobStore:
"""
# Check if the workflow root is a checkpoint but not a leaf vertex.
# All other job vertices in the graph... | [
"def",
"_serialiseFirstJob",
"(",
"self",
",",
"jobStore",
")",
":",
"# Check if the workflow root is a checkpoint but not a leaf vertex.",
"# All other job vertices in the graph are checked by checkNewCheckpointsAreLeafVertices",
"if",
"self",
".",
"checkpoint",
"and",
"not",
"Job",... | 47.863636 | 24.5 |
def matrix_decomp(self, cache=None):
"""Compute a Hermitian eigenbasis decomposition of the matrix.
Parameters
----------
cache : bool or None, optional
If ``True``, store the decomposition internally. For None,
the ``cache_mat_decomp`` from class initialization ... | [
"def",
"matrix_decomp",
"(",
"self",
",",
"cache",
"=",
"None",
")",
":",
"# Lazy import to improve `import odl` time",
"import",
"scipy",
".",
"linalg",
"import",
"scipy",
".",
"sparse",
"# TODO: fix dead link `scipy.linalg.decomp.eigh`",
"if",
"scipy",
".",
"sparse",
... | 32.142857 | 19.714286 |
def requirement_args(argv, want_paths=False, want_other=False):
"""Return an iterable of filtered arguments.
:arg argv: Arguments, starting after the subcommand
:arg want_paths: If True, the returned iterable includes the paths to any
requirements files following a ``-r`` or ``--requirement`` optio... | [
"def",
"requirement_args",
"(",
"argv",
",",
"want_paths",
"=",
"False",
",",
"want_other",
"=",
"False",
")",
":",
"was_r",
"=",
"False",
"for",
"arg",
"in",
"argv",
":",
"# Allow for requirements files named \"-r\", don't freak out if there's a",
"# trailing \"-r\", e... | 36.782609 | 21.608696 |
def tenant_create(name, description=None, enabled=True, profile=None,
**connection_args):
'''
Create a keystone tenant
CLI Examples:
.. code-block:: bash
salt '*' keystone.tenant_create nova description='nova tenant'
salt '*' keystone.tenant_create test enabled=False... | [
"def",
"tenant_create",
"(",
"name",
",",
"description",
"=",
"None",
",",
"enabled",
"=",
"True",
",",
"profile",
"=",
"None",
",",
"*",
"*",
"connection_args",
")",
":",
"kstone",
"=",
"auth",
"(",
"profile",
",",
"*",
"*",
"connection_args",
")",
"n... | 33.533333 | 25.533333 |
def __prepare_body(self, search_value, search_type='url'):
"""
Prepares the http body for querying safebrowsing api. Maybe the list need to get adjusted.
:param search_value: value to search for
:type search_value: str
:param search_type: 'url' or 'ip'
:type search_type:... | [
"def",
"__prepare_body",
"(",
"self",
",",
"search_value",
",",
"search_type",
"=",
"'url'",
")",
":",
"body",
"=",
"{",
"'client'",
":",
"{",
"'clientId'",
":",
"self",
".",
"client_id",
",",
"'clientVersion'",
":",
"self",
".",
"client_version",
"}",
"}"... | 37.947368 | 21.421053 |
def json(
body,
status=200,
headers=None,
content_type="application/json",
dumps=json_dumps,
**kwargs
):
"""
Returns response object with body in json format.
:param body: Response data to be serialized.
:param status: Response code.
:param headers: Custom Headers.
:para... | [
"def",
"json",
"(",
"body",
",",
"status",
"=",
"200",
",",
"headers",
"=",
"None",
",",
"content_type",
"=",
"\"application/json\"",
",",
"dumps",
"=",
"json_dumps",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"HTTPResponse",
"(",
"dumps",
"(",
"body",... | 23.545455 | 18.545455 |
def validate_config(self, config):
"""
Validate configuration dict keys are supported
:type config: dict
:param config: configuration dictionary
"""
try:
hosts = config['hosts']
except KeyError:
raise InvalidConfigurationError('hosts', ""... | [
"def",
"validate_config",
"(",
"self",
",",
"config",
")",
":",
"try",
":",
"hosts",
"=",
"config",
"[",
"'hosts'",
"]",
"except",
"KeyError",
":",
"raise",
"InvalidConfigurationError",
"(",
"'hosts'",
",",
"\"\"",
",",
"reason",
"=",
"(",
"'hosts configurat... | 39.940299 | 21.58209 |
def to_table(self, filter_function=None):
"""Return string with data in tabular form."""
table = []
for p in self:
if filter_function is not None and filter_function(p): continue
table.append([p.basename, p.symbol, p.Z_val, p.l_max, p.l_local, p.xc, p.type])
retur... | [
"def",
"to_table",
"(",
"self",
",",
"filter_function",
"=",
"None",
")",
":",
"table",
"=",
"[",
"]",
"for",
"p",
"in",
"self",
":",
"if",
"filter_function",
"is",
"not",
"None",
"and",
"filter_function",
"(",
"p",
")",
":",
"continue",
"table",
".",
... | 55.875 | 24.125 |
def get_by(self, field, value):
"""
Gets all drive enclosures that match the filter.
The search is case-insensitive.
Args:
Field: field name to filter.
Value: value to filter.
Returns:
list: A list of drive enclosures.
"""
re... | [
"def",
"get_by",
"(",
"self",
",",
"field",
",",
"value",
")",
":",
"return",
"self",
".",
"_client",
".",
"get_by",
"(",
"field",
"=",
"field",
",",
"value",
"=",
"value",
")"
] | 25.5 | 16.214286 |
def to_filter(self, query, arg):
"""Json-server filter using the _or_ operator."""
return filter_from_url_arg(self.model_cls, query, arg, query_operator=or_) | [
"def",
"to_filter",
"(",
"self",
",",
"query",
",",
"arg",
")",
":",
"return",
"filter_from_url_arg",
"(",
"self",
".",
"model_cls",
",",
"query",
",",
"arg",
",",
"query_operator",
"=",
"or_",
")"
] | 57 | 16.666667 |
def parse(md, model, encoding='utf-8', config=None):
"""
Translate the Versa Markdown syntax into Versa model relationships
md -- markdown source text
model -- Versa model to take the output relationship
encoding -- character encoding (defaults to UTF-8)
Returns: The overall base URI (`@base`)... | [
"def",
"parse",
"(",
"md",
",",
"model",
",",
"encoding",
"=",
"'utf-8'",
",",
"config",
"=",
"None",
")",
":",
"#Set up configuration to interpret the conventions for the Markdown",
"config",
"=",
"config",
"or",
"{",
"}",
"#This mapping takes syntactical elements such... | 48.273438 | 23.492188 |
def log(cls, x: 'TensorFluent') -> 'TensorFluent':
'''Returns a TensorFluent for the log function.
Args:
x: The input fluent.
Returns:
A TensorFluent wrapping the log function.
'''
return cls._unary_op(x, tf.log, tf.float32) | [
"def",
"log",
"(",
"cls",
",",
"x",
":",
"'TensorFluent'",
")",
"->",
"'TensorFluent'",
":",
"return",
"cls",
".",
"_unary_op",
"(",
"x",
",",
"tf",
".",
"log",
",",
"tf",
".",
"float32",
")"
] | 28.1 | 21.7 |
def get_package_versions(package):
"""Get the package version information (=SetuptoolsVersion) which is
comparable.
note: we use the pip list_command implementation for this
:param package: name of the package
:return: installed version, latest available version
"""
list_command = ListComma... | [
"def",
"get_package_versions",
"(",
"package",
")",
":",
"list_command",
"=",
"ListCommand",
"(",
")",
"options",
",",
"args",
"=",
"list_command",
".",
"parse_args",
"(",
"[",
"]",
")",
"packages",
"=",
"[",
"get_dist",
"(",
"package",
")",
"]",
"dists",
... | 35.647059 | 14.764706 |
def extract(self, item, list_article_candidate):
"""Compares the extracted authors.
:param item: The corresponding NewscrawlerItem
:param list_article_candidate: A list, the list of ArticleCandidate-Objects which have been extracted
:return: A string, the most likely authors
"""... | [
"def",
"extract",
"(",
"self",
",",
"item",
",",
"list_article_candidate",
")",
":",
"list_author",
"=",
"[",
"]",
"# The authors of the ArticleCandidates and the respective extractors are saved in a tuple in list_author.",
"for",
"article_candidate",
"in",
"list_article_candidat... | 45.269231 | 27.538462 |
def ssh(lancet, print_cmd, environment):
"""
SSH into the given environment, based on the dploi configuration.
"""
namespace = {}
with open(lancet.config.get('dploi', 'deployment_spec')) as fh:
code = compile(fh.read(), 'deployment.py', 'exec')
exec(code, {}, namespace)
config ... | [
"def",
"ssh",
"(",
"lancet",
",",
"print_cmd",
",",
"environment",
")",
":",
"namespace",
"=",
"{",
"}",
"with",
"open",
"(",
"lancet",
".",
"config",
".",
"get",
"(",
"'dploi'",
",",
"'deployment_spec'",
")",
")",
"as",
"fh",
":",
"code",
"=",
"comp... | 32.055556 | 18.833333 |
def get_status(self, channel=Channel.CHANNEL_CH0):
"""
Returns the error status of a specific CAN channel.
:param int channel: CAN channel, to be used (:data:`Channel.CHANNEL_CH0` or :data:`Channel.CHANNEL_CH1`).
:return: Tuple with CAN and USB status (see structure :class:`Status`).
... | [
"def",
"get_status",
"(",
"self",
",",
"channel",
"=",
"Channel",
".",
"CHANNEL_CH0",
")",
":",
"status",
"=",
"Status",
"(",
")",
"UcanGetStatusEx",
"(",
"self",
".",
"_handle",
",",
"channel",
",",
"byref",
"(",
"status",
")",
")",
"return",
"status",
... | 44.636364 | 21.545455 |
def spaced_coordinate(name, keys, ordered=True):
"""
Create a subclass of Coordinate, instances of which must have exactly the given keys.
Parameters
----------
name : str
Name of the new class
keys : sequence
Keys which instances must exclusively have
ordered : bool
... | [
"def",
"spaced_coordinate",
"(",
"name",
",",
"keys",
",",
"ordered",
"=",
"True",
")",
":",
"def",
"validate",
"(",
"self",
")",
":",
"\"\"\"Raise a ValueError if the instance's keys are incorrect\"\"\"",
"if",
"set",
"(",
"keys",
")",
"!=",
"set",
"(",
"self",... | 32.666667 | 26.291667 |
def _run_init_queries(self):
'''
Initialization queries
'''
for obj in (Package, PackageCfgFile, PayloadFile, IgnoredDir, AllowedDir):
self._db.create_table_from_object(obj()) | [
"def",
"_run_init_queries",
"(",
"self",
")",
":",
"for",
"obj",
"in",
"(",
"Package",
",",
"PackageCfgFile",
",",
"PayloadFile",
",",
"IgnoredDir",
",",
"AllowedDir",
")",
":",
"self",
".",
"_db",
".",
"create_table_from_object",
"(",
"obj",
"(",
")",
")"... | 35.666667 | 22.333333 |
def _set_igmpPIM(self, v, load=False):
"""
Setter method for igmpPIM, mapped from YANG variable /interface_vlan/vlan/ip/igmpPIM (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_igmpPIM is considered as a private
method. Backends looking to populate this va... | [
"def",
"_set_igmpPIM",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
"base",... | 82.181818 | 38.5 |
def enforce_relationship_refs(instance):
"""Ensures that all SDOs being referenced by the SRO are contained
within the same bundle"""
if instance['type'] != 'bundle' or 'objects' not in instance:
return
rel_references = set()
"""Find and store all ids"""
for obj in instance['objects']:... | [
"def",
"enforce_relationship_refs",
"(",
"instance",
")",
":",
"if",
"instance",
"[",
"'type'",
"]",
"!=",
"'bundle'",
"or",
"'objects'",
"not",
"in",
"instance",
":",
"return",
"rel_references",
"=",
"set",
"(",
")",
"\"\"\"Find and store all ids\"\"\"",
"for",
... | 44.36 | 20.64 |
def _make_actor_method_executor(self, method_name, method, actor_imported):
"""Make an executor that wraps a user-defined actor method.
The wrapped method updates the worker's internal state and performs any
necessary checkpointing operations.
Args:
method_name (str): The n... | [
"def",
"_make_actor_method_executor",
"(",
"self",
",",
"method_name",
",",
"method",
",",
"actor_imported",
")",
":",
"def",
"actor_method_executor",
"(",
"dummy_return_id",
",",
"actor",
",",
"*",
"args",
")",
":",
"# Update the actor's task counter to reflect the tas... | 48.355932 | 23.40678 |
def get_format_spec(self):
'''
The format specification according to the values of `align` and `width`
'''
return u"{{:{align}{width}}}".format(align=self.align, width=self.width) | [
"def",
"get_format_spec",
"(",
"self",
")",
":",
"return",
"u\"{{:{align}{width}}}\"",
".",
"format",
"(",
"align",
"=",
"self",
".",
"align",
",",
"width",
"=",
"self",
".",
"width",
")"
] | 41.4 | 30.2 |
def run(cls, return_results=False):
""" Iterates through all associated Fields and applies all attached Rules. Depending on 'return_collated_results',
this method will either return True (all rules successful), False (all, or some, rules failed)
or a dictionary list
containing the collat... | [
"def",
"run",
"(",
"cls",
",",
"return_results",
"=",
"False",
")",
":",
"cls",
".",
"result",
"=",
"[",
"]",
"passed",
"=",
"True",
"for",
"field",
"in",
"cls",
".",
"fields",
":",
"result",
",",
"errors",
"=",
"field",
".",
"run",
"(",
")",
"re... | 31.21875 | 20.625 |
def datetime_to_str(self,format="%Y-%m-%dT%H:%M:%S%ZP"):
"""
Create a new SArray with all the values cast to str. The string format is
specified by the 'format' parameter.
Parameters
----------
format : str
The format to output the string. Default format is "... | [
"def",
"datetime_to_str",
"(",
"self",
",",
"format",
"=",
"\"%Y-%m-%dT%H:%M:%S%ZP\"",
")",
":",
"if",
"(",
"self",
".",
"dtype",
"!=",
"datetime",
".",
"datetime",
")",
":",
"raise",
"TypeError",
"(",
"\"datetime_to_str expects SArray of datetime as input SArray\"",
... | 31.052632 | 25.263158 |
def error_log(self, msg='', level=20, traceback=False):
"""Write error message to log.
Args:
msg (str): error message
level (int): logging level
traceback (bool): add traceback to output or not
"""
# Override this in subclasses as desired
sys.... | [
"def",
"error_log",
"(",
"self",
",",
"msg",
"=",
"''",
",",
"level",
"=",
"20",
",",
"traceback",
"=",
"False",
")",
":",
"# Override this in subclasses as desired",
"sys",
".",
"stderr",
".",
"write",
"(",
"msg",
"+",
"'\\n'",
")",
"sys",
".",
"stderr"... | 32.933333 | 11.4 |
def main(args=None):
# type: (Optional[List[str]]) -> int
""" Main logic. """
cli_args = ArgumentParser()
cli_args.add_argument(
"-c",
"--coordinates",
default="",
type=str,
help="the part of the screen to capture: top, left, width, height",
)
cli_args.ad... | [
"def",
"main",
"(",
"args",
"=",
"None",
")",
":",
"# type: (Optional[List[str]]) -> int",
"cli_args",
"=",
"ArgumentParser",
"(",
")",
"cli_args",
".",
"add_argument",
"(",
"\"-c\"",
",",
"\"--coordinates\"",
",",
"default",
"=",
"\"\"",
",",
"type",
"=",
"st... | 31.029412 | 20.514706 |
def build_bsub_command(command_template, lsf_args):
"""Build and return a lsf batch command template
The structure will be 'bsub -s <key> <value> <command_template>'
where <key> and <value> refer to items in lsf_args
"""
if command_template is None:
return ""
full_command = 'bsub -o... | [
"def",
"build_bsub_command",
"(",
"command_template",
",",
"lsf_args",
")",
":",
"if",
"command_template",
"is",
"None",
":",
"return",
"\"\"",
"full_command",
"=",
"'bsub -o {logfile}'",
"for",
"key",
",",
"value",
"in",
"lsf_args",
".",
"items",
"(",
")",
":... | 35.666667 | 11.2 |
def _strip_feature_version(featureid):
"""
some feature versions are encoded as featureid.version, this strips those off, if they exist
"""
version_detector = re.compile(r"(?P<featureid>.*)(?P<version>\.\d+)")
match = version_detector.match(featureid)
if match:
return match.groupdict()["... | [
"def",
"_strip_feature_version",
"(",
"featureid",
")",
":",
"version_detector",
"=",
"re",
".",
"compile",
"(",
"r\"(?P<featureid>.*)(?P<version>\\.\\d+)\"",
")",
"match",
"=",
"version_detector",
".",
"match",
"(",
"featureid",
")",
"if",
"match",
":",
"return",
... | 35.7 | 17.5 |
def start(self):
""" Start the Manager process.
The worker loops on this:
1. If the last message sent was older than heartbeat period we send a heartbeat
2.
TODO: Move task receiving to a thread
"""
self.comm.Barrier()
logger.debug("Manager synced wit... | [
"def",
"start",
"(",
"self",
")",
":",
"self",
".",
"comm",
".",
"Barrier",
"(",
")",
"logger",
".",
"debug",
"(",
"\"Manager synced with workers\"",
")",
"self",
".",
"_kill_event",
"=",
"threading",
".",
"Event",
"(",
")",
"self",
".",
"_task_puller_thre... | 39.231579 | 23.157895 |
def check(self, line_info):
"""If the ifun is magic, and automagic is on, run it. Note: normal,
non-auto magic would already have been triggered via '%' in
check_esc_chars. This just checks for automagic. Also, before
triggering the magic handler, make sure that there is nothing in the... | [
"def",
"check",
"(",
"self",
",",
"line_info",
")",
":",
"if",
"not",
"self",
".",
"shell",
".",
"automagic",
"or",
"not",
"self",
".",
"shell",
".",
"find_magic",
"(",
"line_info",
".",
"ifun",
")",
":",
"return",
"None",
"# We have a likely magic method.... | 46.277778 | 24.277778 |
def filter_by_attrs(self, **kwargs):
"""Returns a ``Dataset`` with variables that match specific conditions.
Can pass in ``key=value`` or ``key=callable``. A Dataset is returned
containing only the variables for which all the filter tests pass.
These tests are either ``key=value`` for ... | [
"def",
"filter_by_attrs",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa",
"selection",
"=",
"[",
"]",
"for",
"var_name",
",",
"variable",
"in",
"self",
".",
"data_vars",
".",
"items",
"(",
")",
":",
"has_value_flag",
"=",
"False",
"for",
"att... | 45.684783 | 19.25 |
def pad_hex(long_int):
"""
Converts a Long integer (or hex string) to hex format padded with zeroes for hashing
:param {Long integer|String} long_int Number or string to pad.
:return {String} Padded hex string.
"""
if not isinstance(long_int, six.string_types):
hash_str = long_to_hex(lon... | [
"def",
"pad_hex",
"(",
"long_int",
")",
":",
"if",
"not",
"isinstance",
"(",
"long_int",
",",
"six",
".",
"string_types",
")",
":",
"hash_str",
"=",
"long_to_hex",
"(",
"long_int",
")",
"else",
":",
"hash_str",
"=",
"long_int",
"if",
"len",
"(",
"hash_st... | 34.4 | 12.533333 |
def super_glob(pattern):
'glob that understands **/ for all sub-directories recursively.'
pieces = pattern.split('/')
if '**' in pieces:
prefix = '/'.join(pieces[:pieces.index('**')])
postfix = '/'.join(pieces[pieces.index('**') + 1:])
roots = [dirname
for dirname, d... | [
"def",
"super_glob",
"(",
"pattern",
")",
":",
"pieces",
"=",
"pattern",
".",
"split",
"(",
"'/'",
")",
"if",
"'**'",
"in",
"pieces",
":",
"prefix",
"=",
"'/'",
".",
"join",
"(",
"pieces",
"[",
":",
"pieces",
".",
"index",
"(",
"'**'",
")",
"]",
... | 43.75 | 19.25 |
def iswhat(o):
"""Returns a dictionary of all possible identity checks available to
:mod:`inspect` applied to `o`.
Returns:
dict: keys are `inspect.is*` function names; values are `bool` results
returned by each of the methods.
"""
import inspect
isfs = {n: f for n, f in inspe... | [
"def",
"iswhat",
"(",
"o",
")",
":",
"import",
"inspect",
"isfs",
"=",
"{",
"n",
":",
"f",
"for",
"n",
",",
"f",
"in",
"inspect",
".",
"getmembers",
"(",
"inspect",
")",
"if",
"n",
"[",
"0",
":",
"2",
"]",
"==",
"\"is\"",
"}",
"return",
"{",
... | 36.090909 | 18.363636 |
def sql_reset(app, style, connection):
"Returns a list of the DROP TABLE SQL, then the CREATE TABLE SQL, for the given module."
return sql_delete(app, style, connection) + sql_all(app, style, connection) | [
"def",
"sql_reset",
"(",
"app",
",",
"style",
",",
"connection",
")",
":",
"return",
"sql_delete",
"(",
"app",
",",
"style",
",",
"connection",
")",
"+",
"sql_all",
"(",
"app",
",",
"style",
",",
"connection",
")"
] | 69.666667 | 31 |
def model_to_dict(model, exclude=None):
"""
Extract a SQLAlchemy model instance to a dictionary
:param model: the model to be extracted
:param exclude: Any keys to be excluded
:return: New dictionary consisting of property-values
"""
exclude = exclude or []
exclude.append('_sa_instance_s... | [
"def",
"model_to_dict",
"(",
"model",
",",
"exclude",
"=",
"None",
")",
":",
"exclude",
"=",
"exclude",
"or",
"[",
"]",
"exclude",
".",
"append",
"(",
"'_sa_instance_state'",
")",
"return",
"{",
"k",
":",
"v",
"for",
"k",
",",
"v",
"in",
"model",
"."... | 39 | 8.4 |
def connect(self):
"""
Create internal connection to AMQP service.
"""
logging.info("Connecting to {} with user {}.".format(self.host, self.username))
credentials = pika.PlainCredentials(self.username, self.password)
connection_params = pika.ConnectionParameters(host=self... | [
"def",
"connect",
"(",
"self",
")",
":",
"logging",
".",
"info",
"(",
"\"Connecting to {} with user {}.\"",
".",
"format",
"(",
"self",
".",
"host",
",",
"self",
".",
"username",
")",
")",
"credentials",
"=",
"pika",
".",
"PlainCredentials",
"(",
"self",
"... | 56.3 | 26.5 |
def pause(self):
""" Pauses playback. """
if self.decoder.status == mediadecoder.PAUSED:
self.decoder.pause()
self.paused = False
elif self.decoder.status == mediadecoder.PLAYING:
self.decoder.pause()
self.paused = True
else:
print("Player not in pausable state") | [
"def",
"pause",
"(",
"self",
")",
":",
"if",
"self",
".",
"decoder",
".",
"status",
"==",
"mediadecoder",
".",
"PAUSED",
":",
"self",
".",
"decoder",
".",
"pause",
"(",
")",
"self",
".",
"paused",
"=",
"False",
"elif",
"self",
".",
"decoder",
".",
... | 27.7 | 14.7 |
def GetRootFileEntry(self):
"""Retrieves the root file entry.
Returns:
GzipFileEntry: a file entry or None if not available.
"""
path_spec = gzip_path_spec.GzipPathSpec(parent=self._path_spec.parent)
return self.GetFileEntryByPathSpec(path_spec) | [
"def",
"GetRootFileEntry",
"(",
"self",
")",
":",
"path_spec",
"=",
"gzip_path_spec",
".",
"GzipPathSpec",
"(",
"parent",
"=",
"self",
".",
"_path_spec",
".",
"parent",
")",
"return",
"self",
".",
"GetFileEntryByPathSpec",
"(",
"path_spec",
")"
] | 33.125 | 17.875 |
def get_syslog_config(host, username, password, protocol=None, port=None, esxi_hosts=None, credstore=None):
'''
Retrieve the syslog configuration.
host
The location of the host.
username
The username used to login to the host, such as ``root``.
password
The password used t... | [
"def",
"get_syslog_config",
"(",
"host",
",",
"username",
",",
"password",
",",
"protocol",
"=",
"None",
",",
"port",
"=",
"None",
",",
"esxi_hosts",
"=",
"None",
",",
"credstore",
"=",
"None",
")",
":",
"cmd",
"=",
"'system syslog config get'",
"ret",
"="... | 36.125 | 28.40625 |
def prune(manager: Manager):
"""Prune nodes not belonging to any edges."""
nodes_to_delete = [
node
for node in tqdm(manager.session.query(Node), total=manager.count_nodes())
if not node.networks
]
manager.session.delete(nodes_to_delete)
manager.session.commit() | [
"def",
"prune",
"(",
"manager",
":",
"Manager",
")",
":",
"nodes_to_delete",
"=",
"[",
"node",
"for",
"node",
"in",
"tqdm",
"(",
"manager",
".",
"session",
".",
"query",
"(",
"Node",
")",
",",
"total",
"=",
"manager",
".",
"count_nodes",
"(",
")",
")... | 33.111111 | 17.888889 |
def parse_name(cls, name: str, default: T = None) -> T:
"""Parse specified name for IntEnum; return default if not found."""
if not name:
return default
name = name.lower()
return next((item for item in cls if name == item.name.lower()), default) | [
"def",
"parse_name",
"(",
"cls",
",",
"name",
":",
"str",
",",
"default",
":",
"T",
"=",
"None",
")",
"->",
"T",
":",
"if",
"not",
"name",
":",
"return",
"default",
"name",
"=",
"name",
".",
"lower",
"(",
")",
"return",
"next",
"(",
"(",
"item",
... | 47.5 | 17.166667 |
def deserialize(cls, target_class, array):
"""
:type target_class: core.SessionServer|type
:type array: list
:rtype: core.SessionServer
"""
session_server = target_class.__new__(target_class)
session_server.__dict__ = {
cls._ATTRIBUTE_ID: converter.d... | [
"def",
"deserialize",
"(",
"cls",
",",
"target_class",
",",
"array",
")",
":",
"session_server",
"=",
"target_class",
".",
"__new__",
"(",
"target_class",
")",
"session_server",
".",
"__dict__",
"=",
"{",
"cls",
".",
"_ATTRIBUTE_ID",
":",
"converter",
".",
"... | 36.086957 | 17.173913 |
def delimiter_groups(line, begin_delim=begin_delim,
end_delim=end_delim):
"""Split a line into alternating groups.
The first group cannot have a line feed inserted,
the next one can, etc.
"""
text = []
line = iter(line)
while True:
# First build and yield a... | [
"def",
"delimiter_groups",
"(",
"line",
",",
"begin_delim",
"=",
"begin_delim",
",",
"end_delim",
"=",
"end_delim",
")",
":",
"text",
"=",
"[",
"]",
"line",
"=",
"iter",
"(",
"line",
")",
"while",
"True",
":",
"# First build and yield an unsplittable group",
"... | 27.470588 | 14.617647 |
def genusspecific(self, analysistype='genesippr'):
"""
Creates simplified genus-specific reports. Instead of the % ID and the fold coverage, a simple +/- scheme is
used for presence/absence
:param analysistype: The variable to use when accessing attributes in the metadata object
... | [
"def",
"genusspecific",
"(",
"self",
",",
"analysistype",
"=",
"'genesippr'",
")",
":",
"# Dictionary to store all the output strings",
"results",
"=",
"dict",
"(",
")",
"for",
"genus",
",",
"genelist",
"in",
"self",
".",
"genedict",
".",
"items",
"(",
")",
":... | 61.179487 | 27.076923 |
def getObjectProfile(self, pid, asOfDateTime=None):
"""Get top-level information aboug a single Fedora object; optionally,
retrieve information as of a particular date-time.
:param pid: object pid
:param asOfDateTime: optional datetime; ``must`` be a non-naive datetime
so it... | [
"def",
"getObjectProfile",
"(",
"self",
",",
"pid",
",",
"asOfDateTime",
"=",
"None",
")",
":",
"# /objects/{pid} ? [format] [asOfDateTime]",
"http_args",
"=",
"{",
"}",
"if",
"asOfDateTime",
":",
"http_args",
"[",
"'asOfDateTime'",
"]",
"=",
"datetime_to_fedoratime... | 46.25 | 16.1875 |
def _convert_number_to_subscript(num):
"""
Converts number into subscript
input = ["a", "a1", "a2", "a3", "be2", "be3", "bad2", "bad3"]
output = ["a", "a₁", "a₂", "a₃", "be₂", "be₃", "bad₂", "bad₃"]
:param num: number called after sign
:return: number in subscript
... | [
"def",
"_convert_number_to_subscript",
"(",
"num",
")",
":",
"subscript",
"=",
"''",
"for",
"character",
"in",
"str",
"(",
"num",
")",
":",
"subscript",
"+=",
"chr",
"(",
"0x2080",
"+",
"int",
"(",
"character",
")",
")",
"return",
"subscript"
] | 32.142857 | 14.571429 |
def get_constraints(self, cursor, table_name):
"""
Retrieve any constraints or keys (unique, pk, fk, check, index) across
one or more columns. Also retrieve the definition of expression-based
indexes.
"""
constraints = {}
# Loop over the key table, collecting things as constraints. The colum... | [
"def",
"get_constraints",
"(",
"self",
",",
"cursor",
",",
"table_name",
")",
":",
"constraints",
"=",
"{",
"}",
"# Loop over the key table, collecting things as constraints. The column",
"# array must return column names in the same order in which they were",
"# created.",
"# The ... | 42.606061 | 17.434343 |
def restart(gandi, resource, background, force):
"""Restart a PaaS instance.
Resource can be a vhost, a hostname, or an ID
"""
output_keys = ['id', 'type', 'step']
possible_resources = gandi.paas.resource_list()
for item in resource:
if item not in possible_resources:
gandi... | [
"def",
"restart",
"(",
"gandi",
",",
"resource",
",",
"background",
",",
"force",
")",
":",
"output_keys",
"=",
"[",
"'id'",
",",
"'type'",
",",
"'step'",
"]",
"possible_resources",
"=",
"gandi",
".",
"paas",
".",
"resource_list",
"(",
")",
"for",
"item"... | 30.413793 | 19.37931 |
def from_helices(cls, assembly, cutoff=7.0, min_helix_length=8):
""" Generate KnobGroup from the helices in the assembly - classic socket functionality.
Notes
-----
Socket identifies knobs-into-holes (KIHs) packing motifs in protein structures.
The following resources can provid... | [
"def",
"from_helices",
"(",
"cls",
",",
"assembly",
",",
"cutoff",
"=",
"7.0",
",",
"min_helix_length",
"=",
"8",
")",
":",
"cutoff",
"=",
"float",
"(",
"cutoff",
")",
"helices",
"=",
"Assembly",
"(",
"[",
"x",
"for",
"x",
"in",
"assembly",
".",
"hel... | 39.38 | 18.86 |
def get_all_terms(self):
"""
Return all of the terms in the account.
https://canvas.instructure.com/doc/api/enrollment_terms.html#method.terms_api.index
"""
if not self._canvas_account_id:
raise MissingAccountID()
params = {"workflow_state": 'all', 'per_page'... | [
"def",
"get_all_terms",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_canvas_account_id",
":",
"raise",
"MissingAccountID",
"(",
")",
"params",
"=",
"{",
"\"workflow_state\"",
":",
"'all'",
",",
"'per_page'",
":",
"500",
"}",
"url",
"=",
"ACCOUNTS_API",... | 36.117647 | 16.823529 |
def _GetAPFSVolumeIdentifiers(self, scan_node):
"""Determines the APFS volume identifiers.
Args:
scan_node (dfvfs.SourceScanNode): scan node.
Returns:
list[str]: APFS volume identifiers.
Raises:
SourceScannerError: if the format of or within the source is not
supported or ... | [
"def",
"_GetAPFSVolumeIdentifiers",
"(",
"self",
",",
"scan_node",
")",
":",
"if",
"not",
"scan_node",
"or",
"not",
"scan_node",
".",
"path_spec",
":",
"raise",
"errors",
".",
"SourceScannerError",
"(",
"'Invalid scan node.'",
")",
"volume_system",
"=",
"apfs_volu... | 32.702128 | 20.93617 |
def format(self, title=None, subtitle=None, prologue_text=None, epilogue_text=None, items=None):
"""
Format the menu and return as a string.
:return: a string representation of the formatted menu.
"""
self.clear_data()
content = ''
# Header Section
if tit... | [
"def",
"format",
"(",
"self",
",",
"title",
"=",
"None",
",",
"subtitle",
"=",
"None",
",",
"prologue_text",
"=",
"None",
",",
"epilogue_text",
"=",
"None",
",",
"items",
"=",
"None",
")",
":",
"self",
".",
"clear_data",
"(",
")",
"content",
"=",
"''... | 38.333333 | 11.060606 |
def _parse_table(self):
"""Parse a wikicode table by starting with the first line."""
reset = self._head
self._head += 2
try:
self._push(contexts.TABLE_OPEN)
padding = self._handle_table_style("\n")
except BadRoute:
self._head = reset
... | [
"def",
"_parse_table",
"(",
"self",
")",
":",
"reset",
"=",
"self",
".",
"_head",
"self",
".",
"_head",
"+=",
"2",
"try",
":",
"self",
".",
"_push",
"(",
"contexts",
".",
"TABLE_OPEN",
")",
"padding",
"=",
"self",
".",
"_handle_table_style",
"(",
"\"\\... | 31.428571 | 15.821429 |
def revokeRegistIssue(self, CorpNum, mgtKey, orgConfirmNum, orgTradeDate, smssendYN=False, memo=None, UserID=None,
isPartCancel=False, cancelType=None, supplyCost=None, tax=None, serviceFee=None,
totalAmount=None):
""" 취소현금영수증 즉시발행
args
... | [
"def",
"revokeRegistIssue",
"(",
"self",
",",
"CorpNum",
",",
"mgtKey",
",",
"orgConfirmNum",
",",
"orgTradeDate",
",",
"smssendYN",
"=",
"False",
",",
"memo",
"=",
"None",
",",
"UserID",
"=",
"None",
",",
"isPartCancel",
"=",
"False",
",",
"cancelType",
"... | 37.358974 | 12.717949 |
def to_jsonf(self, fpath: str, encoding: str='utf8', indent: int=None, ignore_none: bool=True, ignore_empty: bool=False) -> str:
"""From instance to json file
:param fpath: Json file path
:param encoding: Json file encoding
:param indent: Number of indentation
:param ignore_none... | [
"def",
"to_jsonf",
"(",
"self",
",",
"fpath",
":",
"str",
",",
"encoding",
":",
"str",
"=",
"'utf8'",
",",
"indent",
":",
"int",
"=",
"None",
",",
"ignore_none",
":",
"bool",
"=",
"True",
",",
"ignore_empty",
":",
"bool",
"=",
"False",
")",
"->",
"... | 55.181818 | 27.727273 |
def reset_passwd(self, data):
""" Reset the user password """
error = False
msg = ""
# Check input format
if len(data["passwd"]) < 6:
error = True
msg = _("Password too short.")
elif data["passwd"] != data["passwd2"]:
error = True
... | [
"def",
"reset_passwd",
"(",
"self",
",",
"data",
")",
":",
"error",
"=",
"False",
"msg",
"=",
"\"\"",
"# Check input format",
"if",
"len",
"(",
"data",
"[",
"\"passwd\"",
"]",
")",
"<",
"6",
":",
"error",
"=",
"True",
"msg",
"=",
"_",
"(",
"\"Passwor... | 38.36 | 22.72 |
def _set_system_utilization(self, v, load=False):
"""
Setter method for system_utilization, mapped from YANG variable /telemetry/profile/system_utilization (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_system_utilization is considered as a private
method. Ba... | [
"def",
"_set_system_utilization",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
","... | 115.863636 | 55.636364 |
def json_get_default(json: JsonValue, path: str,
default: Any, expected_type: Any = ANY) -> Any:
"""Get a JSON value by path, optionally checking its type.
This works exactly like json_get(), but instead of raising
ValueError or IndexError when a path part is not found, return
the ... | [
"def",
"json_get_default",
"(",
"json",
":",
"JsonValue",
",",
"path",
":",
"str",
",",
"default",
":",
"Any",
",",
"expected_type",
":",
"Any",
"=",
"ANY",
")",
"->",
"Any",
":",
"try",
":",
"return",
"json_get",
"(",
"json",
",",
"path",
",",
"expe... | 33.73913 | 19.608696 |
def sub(self):
'''
:param fields:
Set fields to substitute
:returns:
Substituted Template with given fields.
If no fields were set up beforehand, :func:`raw` is used.
'''
if self.__fields:
return _Template(self.raw).substitute(self... | [
"def",
"sub",
"(",
"self",
")",
":",
"if",
"self",
".",
"__fields",
":",
"return",
"_Template",
"(",
"self",
".",
"raw",
")",
".",
"substitute",
"(",
"self",
".",
"__fields",
")",
"return",
"self",
".",
"raw"
] | 28.583333 | 22.083333 |
def process(self):
"""Process current event."""
try:
self.receiver(self)
# TODO RESTException
except Exception as e:
current_app.logger.exception('Could not process event.')
self.response_code = 500
self.response = dict(status=500, message=... | [
"def",
"process",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"receiver",
"(",
"self",
")",
"# TODO RESTException",
"except",
"Exception",
"as",
"e",
":",
"current_app",
".",
"logger",
".",
"exception",
"(",
"'Could not process event.'",
")",
"self",
"."... | 33.8 | 15.4 |
def _sorted_nicely(self, l):
"""Return list sorted in the way that humans expect.
:param l: iterable to be sorted
:returns: sorted list
"""
convert = lambda text: int(text) if text.isdigit() else text
alphanum_key = lambda key: [ convert(c) for c in re.split('([0... | [
"def",
"_sorted_nicely",
"(",
"self",
",",
"l",
")",
":",
"convert",
"=",
"lambda",
"text",
":",
"int",
"(",
"text",
")",
"if",
"text",
".",
"isdigit",
"(",
")",
"else",
"text",
"alphanum_key",
"=",
"lambda",
"key",
":",
"[",
"convert",
"(",
"c",
"... | 41.222222 | 14.666667 |
def disable_servicegroup_host_checks(self, servicegroup):
"""Disable host checks for a servicegroup
Format of the line that triggers function call::
DISABLE_SERVICEGROUP_HOST_CHECKS;<servicegroup_name>
:param servicegroup: servicegroup to disable
:type servicegroup: alignak.obj... | [
"def",
"disable_servicegroup_host_checks",
"(",
"self",
",",
"servicegroup",
")",
":",
"for",
"service_id",
"in",
"servicegroup",
".",
"get_services",
"(",
")",
":",
"if",
"service_id",
"in",
"self",
".",
"daemon",
".",
"services",
":",
"host_id",
"=",
"self",... | 43.5 | 19.071429 |
def check_spam(self, ip=None, email=None, name=None, login=None, realname=None,
subject=None, body=None, subject_type='plain', body_type='plain'):
""" http://api.yandex.ru/cleanweb/doc/dg/concepts/check-spam.xml
subject_type = plain|html|bbcode
body_type = plain|html|b... | [
"def",
"check_spam",
"(",
"self",
",",
"ip",
"=",
"None",
",",
"email",
"=",
"None",
",",
"name",
"=",
"None",
",",
"login",
"=",
"None",
",",
"realname",
"=",
"None",
",",
"subject",
"=",
"None",
",",
"body",
"=",
"None",
",",
"subject_type",
"=",... | 59.733333 | 27.266667 |
def txt(self, txt, h=None, at_x=None, to_x=None, change_style=None, change_size=None):
"""print string to defined (at_x) position
to_x can apply only if at_x is None and if used then forces align='R'
"""
h = h or self.height
self._change_props(change_style, change_size)
a... | [
"def",
"txt",
"(",
"self",
",",
"txt",
",",
"h",
"=",
"None",
",",
"at_x",
"=",
"None",
",",
"to_x",
"=",
"None",
",",
"change_style",
"=",
"None",
",",
"change_size",
"=",
"None",
")",
":",
"h",
"=",
"h",
"or",
"self",
".",
"height",
"self",
"... | 35.944444 | 15.777778 |
def jsonify_parameters(params):
"""
When sent in an authorized REST request, only strings and integers can be
transmitted accurately. Other types of data need to be encoded into JSON.
"""
result = {}
for param, value in params.items():
if isinstance(value, (int, str)):
result... | [
"def",
"jsonify_parameters",
"(",
"params",
")",
":",
"result",
"=",
"{",
"}",
"for",
"param",
",",
"value",
"in",
"params",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"(",
"int",
",",
"str",
")",
")",
":",
"result",
"[",
... | 33.5 | 14.333333 |
def label_from_re(self, pat:str, full_path:bool=False, label_cls:Callable=None, **kwargs)->'LabelList':
"Apply the re in `pat` to determine the label of every filename. If `full_path`, search in the full name."
pat = re.compile(pat)
def _inner(o):
s = str((os.path.join(self.path,o) ... | [
"def",
"label_from_re",
"(",
"self",
",",
"pat",
":",
"str",
",",
"full_path",
":",
"bool",
"=",
"False",
",",
"label_cls",
":",
"Callable",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
"->",
"'LabelList'",
":",
"pat",
"=",
"re",
".",
"compile",
"(",
... | 60.111111 | 30.555556 |
def urlopen(url, session, referrer=None, max_content_bytes=None,
timeout=ConnectionTimeoutSecs, raise_for_status=True,
stream=False, data=None, useragent=UserAgent):
"""Open an URL and return the response object."""
out.debug(u'Open URL %s' % url)
headers = {'User-Agent': useragent}
... | [
"def",
"urlopen",
"(",
"url",
",",
"session",
",",
"referrer",
"=",
"None",
",",
"max_content_bytes",
"=",
"None",
",",
"timeout",
"=",
"ConnectionTimeoutSecs",
",",
"raise_for_status",
"=",
"True",
",",
"stream",
"=",
"False",
",",
"data",
"=",
"None",
",... | 35.675676 | 15.540541 |
def merge_result(res):
"""
Merge all items in `res` into a list.
This command is used when sending a command to multiple nodes
and they result from each node should be merged into a single list.
"""
if not isinstance(res, dict):
raise ValueError('Value should be of dict type')
resu... | [
"def",
"merge_result",
"(",
"res",
")",
":",
"if",
"not",
"isinstance",
"(",
"res",
",",
"dict",
")",
":",
"raise",
"ValueError",
"(",
"'Value should be of dict type'",
")",
"result",
"=",
"set",
"(",
"[",
"]",
")",
"for",
"_",
",",
"v",
"in",
"res",
... | 25 | 19.705882 |
def print_help(self, classes=False):
"""Print the help for each Configurable class in self.classes.
If classes=False (the default), only flags and aliases are printed.
"""
self.print_subcommands()
self.print_options()
if classes:
if self.classes:
... | [
"def",
"print_help",
"(",
"self",
",",
"classes",
"=",
"False",
")",
":",
"self",
".",
"print_subcommands",
"(",
")",
"self",
".",
"print_options",
"(",
")",
"if",
"classes",
":",
"if",
"self",
".",
"classes",
":",
"print",
"\"Class parameters\"",
"print",... | 31.173913 | 17.130435 |
def sphere_constrained_cubic(dr, a, alpha):
"""
Sphere generated by a cubic interpolant constrained to be (1,0) on
(r0-sqrt(3)/2, r0+sqrt(3)/2), the size of the cube in the (111) direction.
"""
sqrt3 = np.sqrt(3)
b_coeff = a*0.5/sqrt3*(1 - 0.6*sqrt3*alpha)/(0.15 + a*a)
rscl = np.clip(dr, -0... | [
"def",
"sphere_constrained_cubic",
"(",
"dr",
",",
"a",
",",
"alpha",
")",
":",
"sqrt3",
"=",
"np",
".",
"sqrt",
"(",
"3",
")",
"b_coeff",
"=",
"a",
"*",
"0.5",
"/",
"sqrt3",
"*",
"(",
"1",
"-",
"0.6",
"*",
"sqrt3",
"*",
"alpha",
")",
"/",
"(",... | 35.5 | 17.333333 |
def main():
""" Main program. """
args = command.parse_args()
with btrfs.FileSystem(args.dir) as mount:
# mount.rescanSizes()
fInfo = mount.FS_INFO()
pprint.pprint(fInfo)
vols = mount.subvolumes
# for dev in mount.devices:
# pprint.pprint(dev)
... | [
"def",
"main",
"(",
")",
":",
"args",
"=",
"command",
".",
"parse_args",
"(",
")",
"with",
"btrfs",
".",
"FileSystem",
"(",
"args",
".",
"dir",
")",
"as",
"mount",
":",
"# mount.rescanSizes()",
"fInfo",
"=",
"mount",
".",
"FS_INFO",
"(",
")",
"pprint",... | 18.736842 | 21 |
def pave_event_space(fn=pair):
"""
:return:
a pair producer that ensures the seeder and delegator share the same event space.
"""
global _event_space
event_space = next(_event_space)
@_ensure_seeders_list
def p(seeders, delegator_factory, *args, **kwargs):
return fn(seeders ... | [
"def",
"pave_event_space",
"(",
"fn",
"=",
"pair",
")",
":",
"global",
"_event_space",
"event_space",
"=",
"next",
"(",
"_event_space",
")",
"@",
"_ensure_seeders_list",
"def",
"p",
"(",
"seeders",
",",
"delegator_factory",
",",
"*",
"args",
",",
"*",
"*",
... | 33.615385 | 20.538462 |
def parse(celf, s) :
"generates an Introspection tree from the given XML string description."
def from_string_elts(celf, attrs, tree) :
elts = dict((k, attrs[k]) for k in attrs)
child_tags = dict \
(
(childclass.tag_name, childclass)
... | [
"def",
"parse",
"(",
"celf",
",",
"s",
")",
":",
"def",
"from_string_elts",
"(",
"celf",
",",
"attrs",
",",
"tree",
")",
":",
"elts",
"=",
"dict",
"(",
"(",
"k",
",",
"attrs",
"[",
"k",
"]",
")",
"for",
"k",
"in",
"attrs",
")",
"child_tags",
"=... | 45.145455 | 22.2 |
def _proc_builtin(self, tarfile):
"""Process a builtin type or an unknown type which
will be treated as a regular file.
"""
self.offset_data = tarfile.fileobj.tell()
offset = self.offset_data
if self.isreg() or self.type not in SUPPORTED_TYPES:
# Skip the f... | [
"def",
"_proc_builtin",
"(",
"self",
",",
"tarfile",
")",
":",
"self",
".",
"offset_data",
"=",
"tarfile",
".",
"fileobj",
".",
"tell",
"(",
")",
"offset",
"=",
"self",
".",
"offset_data",
"if",
"self",
".",
"isreg",
"(",
")",
"or",
"self",
".",
"typ... | 37 | 14.5625 |
def dic(self):
r""" Returns the corrected Deviance Information Criterion (DIC) for all chains loaded into ChainConsumer.
If a chain does not have a posterior, this method will return `None` for that chain. **Note that
the DIC metric is only valid on posterior surfaces which closely resemble mul... | [
"def",
"dic",
"(",
"self",
")",
":",
"dics",
"=",
"[",
"]",
"dics_bool",
"=",
"[",
"]",
"for",
"i",
",",
"chain",
"in",
"enumerate",
"(",
"self",
".",
"parent",
".",
"chains",
")",
":",
"p",
"=",
"chain",
".",
"posterior",
"if",
"p",
"is",
"Non... | 39.792453 | 25.679245 |
def ReadResponsesForRequestId(self, session_id, request_id, timestamp=None):
"""Reads responses for one request.
Args:
session_id: The session id to use.
request_id: The id of the request.
timestamp: A timestamp as used in the data store.
Yields:
fetched responses for the request
... | [
"def",
"ReadResponsesForRequestId",
"(",
"self",
",",
"session_id",
",",
"request_id",
",",
"timestamp",
"=",
"None",
")",
":",
"request",
"=",
"rdf_flow_runner",
".",
"RequestState",
"(",
"id",
"=",
"request_id",
",",
"session_id",
"=",
"session_id",
")",
"fo... | 35.214286 | 20.357143 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.